1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
7 import org.mozilla.javascript.*;
11 * An XML-RPC client implemented as a Rhino JavaScript Host
12 * Object. See the XWT spec for information on its behavior.
14 * NOTE: this client is EXTREMELY lenient in the responses it will
15 * accept; there are many, many invalid responses that it will
16 * successfully parse and return. Do NOT use this to determine the
17 * validity of your server.
19 * This client conforms to <a href="http://www.xmlrpc.com/spec">The
20 * XML-RPC Spec</a>, subject to these limitations:
22 * <li> XMLRPC cannot invoke methods that require a <base64/> argument
23 * <li> if a return value contains a <base64/>, it will be returned as a string
24 * <li> The decision to pass a number as <i4/> or <double/> is based
25 * entirely on whether or not the argument is fractional. Thus, it
26 * is impossible to pass a non-fractional number to an xmlrpc
27 * method that insists on being called with a <double/> element. We
28 * hope that most xml-rpc servers will be able to automatically
32 class XMLRPC extends XML implements Function {
34 /** should we use SSL? */
35 protected boolean ssl = false;
37 /** the url to connect to */
38 protected URL url = null;
40 /** the method name to invoke on the remove server */
41 protected String methodname = null;
43 /** the host portion of the url; not calculated until first call() */
44 protected String host = null;
46 /** the filename portion of the url; not calculated until first call() */
47 protected String filename = null;
49 /** the port to connect to; not calculated until the first call() */
50 protected int port = -1;
52 /** this holds character content as we read it in -- since there is only one per instance, we don't support mixed content */
53 protected AccessibleCharArrayWriter content = new AccessibleCharArrayWriter(100);
55 /** The object stack. As we process xml elements, pieces of the
56 * return value are pushed onto and popped off of this stack.
58 * The general protocol is that any time a <value> tag is
59 * encountered, an empty String ("") is pushed onto the stack. If
60 * the <value/> node has content (either an anonymous
61 * string or some other XML node), that content replaces the
64 * If an <array> tag is encountered, a null is pushed onto the
65 * stack. When a </data> is encountered, we search back on the
66 * stack to the last null, replace it with a NativeArray, and
67 * insert into it all elements above it on the stack.
69 * If a <struct> tag is encountered, a JSObject is pushed
70 * onto the stack. If a <name> tag is encountered, its CDATA is
71 * pushed onto the stack. When a </member> is encountered, the
72 * name (second element on stack) and value (top of stack) are
73 * popped off the stack and inserted into the struct (third
76 protected Vec objects = null;
78 /** used to detect multi-ref data */
81 /** True iff the return value is a fault (and should be thrown as an exception) */
82 protected boolean fault = false;
85 // Methods to Recieve and parse XML-RPC Response ////////////////////////////////////////////////////
87 public void startElement(String name, String[] keys, Object[] vals, int line, int col) {
88 if (name.equals("fault")) fault = true;
89 else if (name.equals("struct")) objects.setElementAt(new JSObject(false), objects.size() - 1);
90 else if (name.equals("array")) objects.setElementAt(null, objects.size() - 1);
91 else if (name.equals("value")) objects.addElement("");
94 public void endElement(String name, int line, int col) {
96 if (name.equals("int") || name.equals("i4"))
97 objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
99 else if (name.equals("boolean"))
100 objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
102 else if (name.equals("string"))
103 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
105 else if (name.equals("double"))
106 objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
108 else if (name.equals("base64"))
109 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
111 else if (name.equals("name"))
112 objects.addElement(new String(content.getBuf(), 0, content.size()));
114 else if (name.equals("value") && "".equals(objects.lastElement()))
115 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
117 else if (name.equals("dateTime.iso8601")) {
118 String s = new String(content.getBuf(), 0, content.size());
122 while(Character.isWhitespace(s.charAt(i))) i++;
123 if (i > 0) s = s.substring(i);
126 NativeDate nd = (NativeDate)Context.enter().newObject(org.xwt.util.JSObject.defaultObjects, "Date");
127 double date = NativeDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
128 Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
129 Double.valueOf(s.substring(6, 8)).doubleValue(),
130 Double.valueOf(s.substring(9, 11)).doubleValue(),
131 Double.valueOf(s.substring(12, 14)).doubleValue(),
132 Double.valueOf(s.substring(15, 17)).doubleValue(),
135 nd.jsFunction_setTime(NativeDate.internalUTC(date));
136 objects.setElementAt(nd, objects.size() - 1);
138 } catch (Exception e) {
139 if (Log.on) Log.log(this, "error parsing date : " + s);
140 if (Log.on) Log.log(this, e);
143 } else if (name.equals("member")) {
144 Object memberValue = objects.elementAt(objects.size() - 1);
145 String memberName = (String)objects.elementAt(objects.size() - 2);
146 Scriptable struct = (Scriptable)objects.elementAt(objects.size() - 3);
147 struct.put(memberName, struct, memberValue);
148 objects.setSize(objects.size() - 2);
150 } else if (name.equals("data")) {
152 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
153 Object[] arr = new Object[objects.size() - i - 1];
154 for(int j = i + 1; j<objects.size(); j++) arr[j - i - 1] = objects.elementAt(j);
155 objects.setElementAt(Context.enter().newArray(org.xwt.util.JSObject.defaultObjects, arr), i);
156 objects.setSize(i + 1);
163 public void content(char[] ch, int start, int length, int line, int col) {
164 try { content.write(ch, start, length); }
165 catch (Exception e) {
166 if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
167 if (Log.on) Log.log(this, e);
171 // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
173 /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
174 void appendObject(Object o, StringBuffer sb) throws JavaScriptException {
177 throw new JavaScriptException("attempted to send a null value via XML-RPC");
179 } else if (o instanceof Number) {
180 if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
181 sb.append(" <value><i4>");
182 sb.append(((Number)o).intValue());
183 sb.append("</i4></value>\n");
185 sb.append(" <value><double>");
187 sb.append("</double></value>\n");
190 } else if (o instanceof Boolean) {
191 sb.append(" <value><boolean>");
192 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
193 sb.append("</boolean></value>\n");
195 } else if (o instanceof String) {
196 sb.append(" <value><string>");
197 String s = (String)o;
198 if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
201 char[] cbuf = s.toCharArray();
204 while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
205 sb.append(cbuf, oldi, i - oldi);
206 if (i >= cbuf.length) break;
207 if (cbuf[i] == '<') sb.append("<");
208 else if (cbuf[i] == '&') sb.append("&");
210 if (i >= cbuf.length) break;
213 sb.append("</string></value>\n");
215 } else if (o instanceof NativeArray) {
216 if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
217 tracker.put(o, Boolean.TRUE);
218 sb.append(" <value><array><data>\n");
219 NativeArray na = (NativeArray)o;
220 for(int i=0; i<na.jsGet_length(); i++)
221 appendObject(na.get(i, na), sb);
222 sb.append(" </data></array></value>\n");
224 } else if (o instanceof Scriptable && !(o instanceof Undefined)) {
225 if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
226 tracker.put(o, Boolean.TRUE);
227 Scriptable s = (Scriptable)o;
228 sb.append(" <value><struct>\n");
229 Object[] ids = s.getIds();
230 for(int i=0; i<ids.length; i++) {
231 sb.append(" <member><name>" + ids[i] + "</name>\n");
232 appendObject(s.get(ids[i].toString(), s), sb);
233 sb.append(" </member>\n");
235 sb.append(" </struct></value>\n");
238 throw new JavaScriptException("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
243 private Object connect(Object[] args) throws JavaScriptException, IOException {
244 if (filename == null) {
245 filename = url.getFile();
246 host = url.getHost();
247 port = url.getPort();
250 try { addr = InetAddress.getByName(host); }
251 catch (UnknownHostException uhe) { throw new JavaScriptException("could not resolve hostname \"" + host + "\""); }
252 byte[] quadbyte = addr.getAddress();
254 if (quadbyte[0] == 10 ||
255 (quadbyte[0] == 192 && quadbyte[1] == 168) ||
256 (quadbyte[0] == 172 && (quadbyte[1] & 0xF0) == 16) &&
257 !addr.equals(Main.originAddr)) {
259 throw new JavaScriptException("security violation: " + host + " [" + addr.getHostAddress() + "] is in a firewalled netblock");
264 if (ssl) s = Platform.getSocket(host, port == -1 ? 443 : port, true);
265 else if (url.getProtocol().equals("http")) s = Platform.getSocket(host, port == -1 ? 80 : port, false);
266 else throw new JavaScriptException("only http[s] is supported");
268 s.setTcpNoDelay(true);
269 OutputStream os = new BufferedOutputStream(s.getOutputStream(), 4000);
270 InputStream is = new BufferedInputStream(new Filter(s.getInputStream()));
273 if (!Log.verbose) ps = new PrintWriter(os);
274 else ps = new PrintWriter(new FilterWriter(new OutputStreamWriter(os)) {
275 public void write(int i) throws IOException {
277 if (Log.on) Log.log(this, "send: " + ((char)i));
279 public void write(String s, int start, int len) throws IOException {
280 super.write(s, start, len);
281 if (Log.on) Log.log(this, "send: " + s.substring(start, start + len));
283 public void write(char[] c, int start, int len) throws IOException {
284 super.write(c, start, len);
285 if (Log.on) Log.log(this, "send: " + new String(c, start, len));
290 if (!Log.verbose) br = new BufferedReader(new InputStreamReader(is));
291 else br = new BufferedReader(new FilterReader(new InputStreamReader(is)) {
292 public int read() throws IOException {
293 int i = super.read();
294 if (Log.on) Log.log(this, "recv: " + ((char)i));
297 public int read(char[] c, int off, int len) throws IOException {
298 int ret = super.read(c, off, len);
299 if (ret == -1) return ret;
300 if (Log.on) Log.log(this, "recv: " + new String(c, off, ret));
305 if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
306 return send(args, br, ps);
309 protected Object send(Object[] args, BufferedReader br, PrintWriter ps) throws JavaScriptException, IOException {
312 StringBuffer content = new StringBuffer();
313 content.append("<?xml version=\"1.0\"?>\n");
314 content.append(" <methodCall>\n");
315 content.append(" <methodName>");
316 content.append(methodname);
317 content.append("</methodName>\n");
318 if (args.length > 0) {
319 content.append(" <params>\n");
320 for(int i=0; i<args.length; i++) {
321 content.append(" <param>\n");
322 appendObject(args[i], content);
323 content.append(" </param>\n");
325 content.append(" </params>\n");
327 content.append(" </methodCall>");
330 ps.print("POST " + filename + " HTTP/1.0\r\n");
331 ps.print("Host: " + host + "\r\n");
332 ps.print("User-Agent: XWT (http://www.xwt.org/)\r\n");
333 ps.print("Content-Type: text/xml\r\n");
334 ps.print("Content-length: " + (content.length() + 1) + "\r\n");
340 // throw away HTTP reply headers
341 while(!br.readLine().equals("")) { }
346 } catch (XML.SAXException e) {
347 if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
348 throw new JavaScriptException("reply from server was not well-formed XML: " + e);
351 if (fault) throw new JavaScriptException(objects.elementAt(0));
353 if (objects.size() == 0) return null;
354 return objects.elementAt(0);
358 public final Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) throws JavaScriptException {
360 if (tracker == null) tracker = new Hash();
361 else tracker.clear();
363 if (objects == null) objects = new Vec();
364 else objects.setSize(0);
366 // put ourselves in the background
367 Thread thread = Thread.currentThread();
368 if (!(thread instanceof ThreadMessage)) {
369 if (Log.on) Log.log(this, "RPC calls may only be made from background threads");
372 ThreadMessage mythread = (ThreadMessage)thread;
373 mythread.setPriority(Thread.MIN_PRIORITY);
374 mythread.done.release();
377 return connect(args);
379 } catch (IOException se) {
380 if (Log.on) Log.log(this, se);
381 if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
382 throw new JavaScriptException("socket exception: " + se);
384 } catch (JavaScriptException jse) {
385 Object val = jse.getValue();
386 if (val instanceof String) {
387 if (Log.on) Log.log(this, val.toString());
388 if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
393 // okay, let ourselves be brought to the foreground
394 MessageQueue.add(mythread);
395 mythread.setPriority(Thread.NORM_PRIORITY);
401 /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
402 public Object get(String name, Scriptable start) {
403 return new XMLRPC(url.toString(), (methodname.equals("") ? "" : methodname + ".") + name, ssl);
406 public XMLRPC(String urlstr, String methodname) { this(urlstr, methodname, false); }
407 public XMLRPC(String urlstr, String methodname, boolean ssl) {
410 if (urlstr.startsWith("https:")) {
411 urlstr = "http" + urlstr.substring(5);
414 URL url = new URL(urlstr);
415 if (methodname == null) methodname = "";
416 this.methodname = methodname;
419 } catch (MalformedURLException e) {
420 if (Log.on) Log.log(this, e);
425 // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
427 /** CharArrayWriter that lets us touch its buffer */
428 protected static class AccessibleCharArrayWriter extends CharArrayWriter {
429 public char[] getBuf() { return buf; }
430 public AccessibleCharArrayWriter(int i) { super(i); }
433 /** private filter class to make sure that network transfers don't interfere with UI responsiveness */
434 private static class Filter extends FilterInputStream {
435 public Filter(InputStream is) { super(is); }
436 public int read() throws IOException {
438 while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
441 public int read(byte[] b) throws IOException {
443 while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
444 return super.read(b);
446 public int read(byte[] b, int i, int j) throws IOException {
448 while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
449 return super.read(b, i, j);
453 // Methods Required by Rhino ////////////////////////////////////////////////////////
455 public String getClassName() { return "XMLRPC"; }
456 public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
457 public void delete(String name) { }
458 public Scriptable getParentScope() { return null; }
459 public void setParentScope(Scriptable p) { }
460 public boolean hasInstance(Scriptable value) { return false; }
461 public Scriptable getPrototype() { return null; }
462 public void setPrototype(Scriptable p) { }
463 public void delete(int i) { }
464 public Object getDefaultValue(Class hint) { return "XML-RPC"; }
465 public void put(int i, Scriptable start, Object value) { }
466 public Object get(int i, Scriptable start) { return null; }
467 public void put(String name, Scriptable start, Object value) { }
468 public boolean has(String name, Scriptable start) { return true; }
469 public boolean has(int i, Scriptable start) { return false; }
470 public Object[] getIds() { return new Object[] { }; }