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