ca5b54f88ed38b08e02b2ac2d8dc93a11918e5e1
[org.ibex.core.git] / src / org / xwt / XMLRPC.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.io.*;
5 import java.net.*;
6 import java.util.*;
7 import org.mozilla.javascript.*;
8 import org.xwt.util.*;
9
10 /**
11  *  An XML-RPC client implemented as a Rhino JavaScript Host
12  *  Object. See the XWT spec for information on its behavior.
13  *
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.
18  *
19  *  This client conforms to <a href="http://www.xmlrpc.com/spec">The
20  *  XML-RPC Spec</a>, subject to these limitations:
21  *  <ol>
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
29  *         convert.
30  *  </ol>
31  */
32 class XMLRPC extends XML implements Function {
33
34     /** should we use SSL? */
35     protected boolean ssl = false;
36
37     /** the url to connect to */
38     protected URL url = null;
39
40     /** the method name to invoke on the remove server */
41     protected String methodname = null;
42
43     /** the host portion of the url; not calculated until first call() */
44     protected String host = null;
45
46     /** the filename portion of the url; not calculated until first call() */
47     protected String filename = null;
48
49     /** the port to connect to; not calculated until the first call() */
50     protected int port = -1;
51
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);
54
55     /** The object stack. As we process xml elements, pieces of the
56      *  return value are pushed onto and popped off of this stack.
57      *
58      *  The general protocol is that any time a &lt;value&gt; tag is
59      *  encountered, an empty String ("") is pushed onto the stack. If
60      *  the &lt;value/&gt; node has content (either an anonymous
61      *  string or some other XML node), that content replaces the
62      *  empty string.
63      *
64      *  If an &lt;array&gt; tag is encountered, a null is pushed onto the
65      *  stack. When a &lt;/data&gt; 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.
68      *
69      *  If a &lt;struct&gt; tag is encountered, a JSObject is pushed
70      *  onto the stack. If a &lt;name&gt; tag is encountered, its CDATA is
71      *  pushed onto the stack. When a &lt;/member&gt; 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
74      *  element on stack).
75      */
76     protected Vec objects = null;
77
78     /** used to detect multi-ref data */
79     private Hash tracker;
80
81     /** True iff the return value is a fault (and should be thrown as an exception) */
82     protected boolean fault = false;
83
84
85     // Methods to Recieve and parse XML-RPC Response ////////////////////////////////////////////////////
86
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("");
92     }
93
94     public void endElement(String name, int line, int col) {
95
96         if (name.equals("int") || name.equals("i4"))
97             objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
98
99         else if (name.equals("boolean"))
100             objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
101
102         else if (name.equals("string"))
103             objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
104
105         else if (name.equals("double"))
106             objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
107
108         else if (name.equals("base64"))
109             objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
110
111         else if (name.equals("name"))
112             objects.addElement(new String(content.getBuf(), 0, content.size()));
113
114         else if (name.equals("value") && "".equals(objects.lastElement()))
115             objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
116
117         else if (name.equals("dateTime.iso8601")) {
118             String s = new String(content.getBuf(), 0, content.size());
119
120             // strip whitespace
121             int i=0;
122             while(Character.isWhitespace(s.charAt(i))) i++;
123             if (i > 0) s = s.substring(i);
124
125             try {
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(),
133                                                            (double)0
134                                                            );
135                 nd.jsFunction_setTime(NativeDate.internalUTC(date));
136                 objects.setElementAt(nd, objects.size() - 1);
137
138             } catch (Exception e) {
139                 if (Log.on) Log.log(this, "error parsing date : " + s);
140                 if (Log.on) Log.log(this, e);
141             }
142
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);
149
150         } else if (name.equals("data")) {
151             int i;
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);
157
158         }
159
160         content.reset();
161     }
162
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);
168         }
169     }
170
171     // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
172
173     /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
174     void appendObject(Object o, StringBuffer sb) throws JavaScriptException {
175
176         if (o == null) {
177             throw new JavaScriptException("attempted to send a null value via XML-RPC");
178
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");
184             } else {
185                 sb.append("                <value><double>");
186                 sb.append(o);
187                 sb.append("</double></value>\n");
188             }
189
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");
194
195         } else if (o instanceof String) {
196             sb.append("                <value><string>");
197             String s = (String)o;
198             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
199                 sb.append(s);
200             } else {
201                 char[] cbuf = s.toCharArray();
202                 int oldi = 0, i=0;
203                 while(true) {
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("&lt;");
208                     else if (cbuf[i] == '&') sb.append("&amp;");
209                     i = oldi = i + 1;
210                     if (i >= cbuf.length) break;
211                 }
212             }
213             sb.append("</string></value>\n");
214
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");
223
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");
234             }
235             sb.append("                </struct></value>\n");
236
237         } else {
238             throw new JavaScriptException("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
239
240         }
241     }
242
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();
248
249             InetAddress addr;
250             try { addr = InetAddress.getByName(host); }
251             catch (UnknownHostException uhe) { throw new JavaScriptException("could not resolve hostname \"" + host + "\""); }
252             byte[] quadbyte = addr.getAddress();
253             
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)) {
258                 filename = null;
259                 throw new JavaScriptException("security violation: " + host + " [" + addr.getHostAddress() + "] is in a firewalled netblock");
260             }
261         }
262
263         Socket s;
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");
267
268         s.setTcpNoDelay(true);
269         OutputStream os = new BufferedOutputStream(s.getOutputStream(), 4000);
270         InputStream is = new BufferedInputStream(new Filter(s.getInputStream()));
271         
272         PrintWriter ps;
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 {
276                     super.write(i);
277                     if (Log.on) Log.log(this, "send: " + ((char)i));
278                 }
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));
282                 }
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));
286                 }
287             });
288         
289         BufferedReader br;
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));
295                     return i;
296                 }
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));
301                     return ret;
302                 }
303             });
304         
305         if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
306         return send(args, br, ps);
307     }
308
309     protected Object send(Object[] args, BufferedReader br, PrintWriter ps) throws JavaScriptException, IOException {
310
311         // Construct payload
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");
324             }
325             content.append("        </params>\n");
326         }
327         content.append("    </methodCall>");
328         
329         // Header
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");
335         ps.print("\r\n");
336         ps.print(content);
337         ps.print("\n");
338         ps.flush();
339
340         // throw away HTTP reply headers
341         while(!br.readLine().equals("")) { }
342
343         // parse XML reply
344         try {
345             parse(br);
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);
349         }
350         
351         if (fault) throw new JavaScriptException(objects.elementAt(0));
352         
353         if (objects.size() == 0) return null;
354         return objects.elementAt(0);
355
356     }
357
358     public final Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) throws JavaScriptException {
359
360         if (tracker == null) tracker = new Hash();
361         else tracker.clear();
362
363         if (objects == null) objects = new Vec();
364         else objects.setSize(0);
365
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");
370             return null;
371         }
372         ThreadMessage mythread = (ThreadMessage)thread;
373         mythread.setPriority(Thread.MIN_PRIORITY);
374         mythread.done.release();
375
376         try {
377             return connect(args);
378
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);
383
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);
389             }
390             throw jse;
391
392         } finally {
393             // okay, let ourselves be brought to the foreground
394             MessageQueue.add(mythread);
395             mythread.setPriority(Thread.NORM_PRIORITY);
396             mythread.go.block();
397         }
398
399     }
400
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);
404     }
405
406     public XMLRPC(String urlstr, String methodname) { this(urlstr, methodname, false); }
407     public XMLRPC(String urlstr, String methodname, boolean ssl) {
408         this.ssl = ssl;
409         try {
410             if (urlstr.startsWith("https:")) {
411                 urlstr = "http" + urlstr.substring(5);
412                 this.ssl = true;
413             }
414             URL url = new URL(urlstr);
415             if (methodname == null) methodname = "";
416             this.methodname = methodname;
417             this.url = url;
418
419         } catch (MalformedURLException e) {
420             if (Log.on) Log.log(this, e);
421
422         }
423     }
424
425     // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
426
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); }
431     }
432
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 {
437             Thread.yield();
438             while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
439             return super.read();
440         }
441         public int read(byte[] b) throws IOException {
442             Thread.yield();
443             while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
444             return super.read(b);
445         }
446         public int read(byte[] b, int i, int j) throws IOException {
447             Thread.yield();
448             while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
449             return super.read(b, i, j);
450         }
451     }
452
453     // Methods Required by Rhino ////////////////////////////////////////////////////////
454
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[] { }; }
471
472 }