1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
7 import org.mozilla.javascript.*;
9 import org.bouncycastle.util.encoders.Base64;
12 * An XML-RPC client implemented as a Rhino JavaScript Host
13 * Object. See the XWT spec for information on its behavior.
15 * NOTE: this client is EXTREMELY lenient in the responses it will
16 * accept; there are many, many invalid responses that it will
17 * successfully parse and return. Do NOT use this to determine the
18 * validity of your server.
20 * This client conforms to <a href="http://www.xmlrpc.com/spec">The
21 * XML-RPC Spec</a>, subject to these limitations:
23 * <li> XMLRPC cannot invoke methods that require a <base64/> argument
24 * <li> if a return value contains a <base64/>, it will be returned as a string
25 * <li> The decision to pass a number as <i4/> or <double/> is based
26 * entirely on whether or not the argument is fractional. Thus, it
27 * is impossible to pass a non-fractional number to an xmlrpc
28 * method that insists on being called with a <double/> element. We
29 * hope that most xml-rpc servers will be able to automatically
33 class XMLRPC extends XML implements Function {
35 /** should we use SSL? */
36 protected boolean ssl = false;
38 /** the url to connect to */
39 protected URL url = null;
41 /** the method name to invoke on the remove server */
42 protected String methodname = null;
44 /** the host portion of the url; not calculated until first call() */
45 protected String host = null;
47 /** the filename portion of the url; not calculated until first call() */
48 protected String filename = null;
50 /** the port to connect to; not calculated until the first call() */
51 protected int port = -1;
53 /** this holds character content as we read it in -- since there is only one per instance, we don't support mixed content */
54 protected AccessibleCharArrayWriter content = new AccessibleCharArrayWriter(100);
56 /** The object stack. As we process xml elements, pieces of the
57 * return value are pushed onto and popped off of this stack.
59 * The general protocol is that any time a <value> tag is
60 * encountered, an empty String ("") is pushed onto the stack. If
61 * the <value/> node has content (either an anonymous
62 * string or some other XML node), that content replaces the
65 * If an <array> tag is encountered, a null is pushed onto the
66 * stack. When a </data> is encountered, we search back on the
67 * stack to the last null, replace it with a NativeArray, and
68 * insert into it all elements above it on the stack.
70 * If a <struct> tag is encountered, a JSObject is pushed
71 * onto the stack. If a <name> tag is encountered, its CDATA is
72 * pushed onto the stack. When a </member> is encountered, the
73 * name (second element on stack) and value (top of stack) are
74 * popped off the stack and inserted into the struct (third
77 protected Vec objects = null;
79 /** used to detect multi-ref data */
82 /** True iff the return value is a fault (and should be thrown as an exception) */
83 protected boolean fault = false;
86 // Methods to Recieve and parse XML-RPC Response ////////////////////////////////////////////////////
88 public void startElement(String name, String[] keys, Object[] vals, int line, int col) {
89 if (name.equals("fault")) fault = true;
90 else if (name.equals("struct")) objects.setElementAt(new JSObject(false), objects.size() - 1);
91 else if (name.equals("array")) objects.setElementAt(null, objects.size() - 1);
92 else if (name.equals("value")) objects.addElement("");
95 public void endElement(String name, int line, int col) {
97 if (name.equals("int") || name.equals("i4"))
98 objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
100 else if (name.equals("boolean"))
101 objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
103 else if (name.equals("string"))
104 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
106 else if (name.equals("double"))
107 objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
109 else if (name.equals("base64"))
110 objects.setElementAt(new String(Base64.decode(new String(content.getBuf(), 0, content.size()))), objects.size() - 1);
112 else if (name.equals("name"))
113 objects.addElement(new String(content.getBuf(), 0, content.size()));
115 else if (name.equals("value") && "".equals(objects.lastElement()))
116 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
118 else if (name.equals("dateTime.iso8601")) {
119 String s = new String(content.getBuf(), 0, content.size());
123 while(Character.isWhitespace(s.charAt(i))) i++;
124 if (i > 0) s = s.substring(i);
127 NativeDate nd = (NativeDate)Context.enter().newObject(org.xwt.util.JSObject.defaultObjects, "Date");
128 double date = NativeDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
129 Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
130 Double.valueOf(s.substring(6, 8)).doubleValue(),
131 Double.valueOf(s.substring(9, 11)).doubleValue(),
132 Double.valueOf(s.substring(12, 14)).doubleValue(),
133 Double.valueOf(s.substring(15, 17)).doubleValue(),
136 nd.jsFunction_setTime(NativeDate.internalUTC(date));
137 objects.setElementAt(nd, objects.size() - 1);
139 } catch (Exception e) {
140 if (Log.on) Log.log(this, "error parsing date : " + s);
141 if (Log.on) Log.log(this, e);
144 } else if (name.equals("member")) {
145 Object memberValue = objects.elementAt(objects.size() - 1);
146 String memberName = (String)objects.elementAt(objects.size() - 2);
147 Scriptable struct = (Scriptable)objects.elementAt(objects.size() - 3);
148 struct.put(memberName, struct, memberValue);
149 objects.setSize(objects.size() - 2);
151 } else if (name.equals("data")) {
153 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
154 Object[] arr = new Object[objects.size() - i - 1];
155 for(int j = i + 1; j<objects.size(); j++) arr[j - i - 1] = objects.elementAt(j);
156 objects.setElementAt(Context.enter().newArray(org.xwt.util.JSObject.defaultObjects, arr), i);
157 objects.setSize(i + 1);
164 public void content(char[] ch, int start, int length, int line, int col) {
165 try { content.write(ch, start, length); }
166 catch (Exception e) {
167 if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
168 if (Log.on) Log.log(this, e);
172 // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
174 /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
175 void appendObject(Object o, StringBuffer sb) throws JavaScriptException {
178 throw new JavaScriptException("attempted to send a null value via XML-RPC");
180 } else if (o instanceof Number) {
181 if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
182 sb.append(" <value><i4>");
183 sb.append(((Number)o).intValue());
184 sb.append("</i4></value>\n");
186 sb.append(" <value><double>");
188 sb.append("</double></value>\n");
191 } else if (o instanceof Boolean) {
192 sb.append(" <value><boolean>");
193 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
194 sb.append("</boolean></value>\n");
196 } else if (o instanceof String) {
197 sb.append(" <value><string>");
198 String s = (String)o;
199 if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
202 char[] cbuf = s.toCharArray();
205 while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
206 sb.append(cbuf, oldi, i - oldi);
207 if (i >= cbuf.length) break;
208 if (cbuf[i] == '<') sb.append("<");
209 else if (cbuf[i] == '&') sb.append("&");
211 if (i >= cbuf.length) break;
214 sb.append("</string></value>\n");
216 } else if (o instanceof NativeArray) {
217 if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
218 tracker.put(o, Boolean.TRUE);
219 sb.append(" <value><array><data>\n");
220 NativeArray na = (NativeArray)o;
221 for(int i=0; i<na.jsGet_length(); i++)
222 appendObject(na.get(i, na), sb);
223 sb.append(" </data></array></value>\n");
225 } else if (o instanceof Scriptable && !(o instanceof Undefined)) {
226 if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
227 tracker.put(o, Boolean.TRUE);
228 Scriptable s = (Scriptable)o;
229 sb.append(" <value><struct>\n");
230 Object[] ids = s.getIds();
231 for(int i=0; i<ids.length; i++) {
232 sb.append(" <member><name>" + ids[i] + "</name>\n");
233 appendObject(s.get(ids[i].toString(), s), sb);
234 sb.append(" </member>\n");
236 sb.append(" </struct></value>\n");
239 throw new JavaScriptException("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
244 private Object connect(Object[] args) throws JavaScriptException, IOException {
245 if (filename == null) {
246 filename = url.getFile();
247 host = url.getHost();
248 port = url.getPort();
251 try { addr = InetAddress.getByName(host); }
252 catch (UnknownHostException uhe) { throw new JavaScriptException("could not resolve hostname \"" + host + "\""); }
253 byte[] quadbyte = addr.getAddress();
255 if (quadbyte[0] == 10 ||
256 (quadbyte[0] == 192 && quadbyte[1] == 168) ||
257 (quadbyte[0] == 172 && (quadbyte[1] & 0xF0) == 16) &&
258 !addr.equals(Main.originAddr)) {
260 throw new JavaScriptException("security violation: " + host + " [" + addr.getHostAddress() + "] is in a firewalled netblock");
265 if (ssl) s = Platform.getSocket(host, port == -1 ? 443 : port, true);
266 else if (url.getProtocol().equals("http")) s = Platform.getSocket(host, port == -1 ? 80 : port, false);
267 else throw new JavaScriptException("only http[s] is supported");
269 s.setTcpNoDelay(true);
270 OutputStream os = new BufferedOutputStream(s.getOutputStream(), 4000);
271 InputStream is = new BufferedInputStream(new Filter(s.getInputStream()));
274 if (!Log.verbose) ps = new PrintWriter(os);
275 else ps = new PrintWriter(new FilterWriter(new OutputStreamWriter(os)) {
276 public void write(int i) throws IOException {
278 if (Log.on) Log.log(this, "send: " + ((char)i));
280 public void write(String s, int start, int len) throws IOException {
281 super.write(s, start, len);
282 if (Log.on) Log.log(this, "send: " + s.substring(start, start + len));
284 public void write(char[] c, int start, int len) throws IOException {
285 super.write(c, start, len);
286 if (Log.on) Log.log(this, "send: " + new String(c, start, len));
291 if (!Log.verbose) br = new BufferedReader(new InputStreamReader(is));
292 else br = new BufferedReader(new FilterReader(new InputStreamReader(is)) {
293 public int read() throws IOException {
294 int i = super.read();
295 if (Log.on) Log.log(this, "recv: " + ((char)i));
298 public int read(char[] c, int off, int len) throws IOException {
299 int ret = super.read(c, off, len);
300 if (ret == -1) return ret;
301 if (Log.on) Log.log(this, "recv: " + new String(c, off, ret));
306 if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
307 return send(args, br, ps);
310 protected Object send(Object[] args, BufferedReader br, PrintWriter ps) throws JavaScriptException, IOException {
313 StringBuffer content = new StringBuffer();
314 content.append("<?xml version=\"1.0\"?>\n");
315 content.append(" <methodCall>\n");
316 content.append(" <methodName>");
317 content.append(methodname);
318 content.append("</methodName>\n");
319 if (args.length > 0) {
320 content.append(" <params>\n");
321 for(int i=0; i<args.length; i++) {
322 content.append(" <param>\n");
323 appendObject(args[i], content);
324 content.append(" </param>\n");
326 content.append(" </params>\n");
328 content.append(" </methodCall>");
331 ps.print("POST " + filename + " HTTP/1.0\r\n");
332 ps.print("Host: " + host + "\r\n");
333 ps.print("User-Agent: XWT (http://www.xwt.org/)\r\n");
334 ps.print("Content-Type: text/xml\r\n");
335 ps.print("Content-length: " + (content.length() + 1) + "\r\n");
341 // throw away HTTP reply headers
342 while(!br.readLine().equals("")) { }
347 } catch (XML.SAXException e) {
348 if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
349 throw new JavaScriptException("reply from server was not well-formed XML: " + e);
352 if (fault) throw new JavaScriptException(objects.elementAt(0));
354 if (objects.size() == 0) return null;
355 return objects.elementAt(0);
359 public final Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) throws JavaScriptException {
361 if (tracker == null) tracker = new Hash();
362 else tracker.clear();
364 if (objects == null) objects = new Vec();
365 else objects.setSize(0);
367 // put ourselves in the background
368 Thread thread = Thread.currentThread();
369 if (!(thread instanceof ThreadMessage)) {
370 if (Log.on) Log.log(this, "RPC calls may only be made from background threads");
373 ThreadMessage mythread = (ThreadMessage)thread;
374 mythread.setPriority(Thread.MIN_PRIORITY);
375 mythread.done.release();
378 return connect(args);
380 } catch (IOException se) {
381 if (Log.on) Log.log(this, se);
382 if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
383 throw new JavaScriptException("socket exception: " + se);
385 } catch (JavaScriptException jse) {
386 Object val = jse.getValue();
387 if (val instanceof String) {
388 if (Log.on) Log.log(this, val.toString());
389 if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
394 // okay, let ourselves be brought to the foreground
395 MessageQueue.add(mythread);
396 mythread.setPriority(Thread.NORM_PRIORITY);
402 /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
403 public Object get(String name, Scriptable start) {
404 return new XMLRPC(url.toString(), (methodname.equals("") ? "" : methodname + ".") + name, ssl);
407 public XMLRPC(String urlstr, String methodname) { this(urlstr, methodname, false); }
408 public XMLRPC(String urlstr, String methodname, boolean ssl) {
411 if (urlstr.startsWith("https:")) {
412 urlstr = "http" + urlstr.substring(5);
415 URL url = new URL(urlstr);
416 if (methodname == null) methodname = "";
417 this.methodname = methodname;
420 } catch (MalformedURLException e) {
421 if (Log.on) Log.log(this, e);
426 // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
428 /** CharArrayWriter that lets us touch its buffer */
429 protected static class AccessibleCharArrayWriter extends CharArrayWriter {
430 public char[] getBuf() { return buf; }
431 public AccessibleCharArrayWriter(int i) { super(i); }
434 /** private filter class to make sure that network transfers don't interfere with UI responsiveness */
435 private static class Filter extends FilterInputStream {
436 public Filter(InputStream is) { super(is); }
437 public int read() throws IOException {
439 while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
442 public int read(byte[] b) throws IOException {
444 while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
445 return super.read(b);
447 public int read(byte[] b, int i, int j) throws IOException {
449 while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
450 return super.read(b, i, j);
454 // Methods Required by Rhino ////////////////////////////////////////////////////////
456 public String getClassName() { return "XMLRPC"; }
457 public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
458 public void delete(String name) { }
459 public Scriptable getParentScope() { return null; }
460 public void setParentScope(Scriptable p) { }
461 public boolean hasInstance(Scriptable value) { return false; }
462 public Scriptable getPrototype() { return null; }
463 public void setPrototype(Scriptable p) { }
464 public void delete(int i) { }
465 public Object getDefaultValue(Class hint) { return "XML-RPC"; }
466 public void put(int i, Scriptable start, Object value) { }
467 public Object get(int i, Scriptable start) { return null; }
468 public void put(String name, Scriptable start, Object value) { }
469 public boolean has(String name, Scriptable start) { return true; }
470 public boolean has(int i, Scriptable start) { return false; }
471 public Object[] getIds() { return new Object[] { }; }