Menu

[r190]: / phprpc_3.0 / java / PHPRPC_Client.java  Maximize  Restore  History

Download this file

669 lines (621 with data), 26.0 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
/**********************************************************\
| |
| The implementation of PHPRPC Protocol 3.0 |
| |
| PHPRPC_Client.java |
| |
| Release 3.0.0 beta 2 |
| Copyright (c) 2005-2007 by Team-PHPRPC |
| |
| WebSite: http://www.phprpc.org/ |
| http://www.phprpc.com/ |
| http://sourceforge.net/projects/php-rpc/ |
| |
| Authors: Ma Bingyao <andot@ujn.edu.cn> |
| |
| This file may be distributed and/or modified under the |
| terms of the GNU Lesser General Public License (LGPL) |
| version 2.1 as published by the Free Software Foundation |
| and appearing in the included file LICENSE. |
| |
\**********************************************************/
/* PHPRPC_Client class.
*
* Copyright (C) 2007 Ma Bingyao <andot@ujn.edu.cn>
* Version: 3.0.0 beta 2
* LastModified: Apr 18, 2007
* This library is free. You can redistribute it and/or modify it.
*
/*
* Example usage:
*
import org.phprpc.PHPRPC_Client;
interface remoteFunctions {
public int add(int a, int b);
public double add(double a, double b);
public String add(String a, String b);
}
public class SinTest
{
public static void main(String[] args) {
PHPRPC_Client rpc = new PHPRPC_Client("http://www.phprpc.org/server.php");
remoteFunctions rf = (remoteFunctions)rpc.useService(remoteFunctions.class);
rpc.setKeyLength(1024);
rpc.setEncryptMode(2);
System.out.println(rf.add(1, 2));
System.out.println(rf.add(1.5, 2.6));
System.out.println(rf.add("1", "2"));
}
}
*
*/
package org.phprpc;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Random;
import java.util.zip.GZIPInputStream;
import java.math.BigInteger;
import java.net.URL;
import java.net.Socket;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import org.phprpc.util.Base64;
import org.phprpc.util.XXTEA;
import org.phprpc.util.PHPSerializer;
class PHPRPC_InvocationHandler implements InvocationHandler {
private PHPRPC_Client rpc;
private PHPSerializer phpser;
PHPRPC_InvocationHandler(PHPRPC_Client rpc) {
this.rpc = rpc;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return this.rpc.__phpser.cast(this.rpc.invoke(method.getName(), args), method.getReturnType());
}
}
public class PHPRPC_Client {
protected PHPSerializer __phpser = null;
private HashMap __server = null;
private HashMap __proxy = null;
private int __timeout = 30000;
private PHPRPC_Error __warning = null;
private byte[] __key = null;
private int __keylen = 128;
private int __encryptMode = 0;
private String __cookie = "";
private String __charset = "utf-8";
private String __output = "";
private Socket __socket = null;
private String __httpVersion = "1.1";
private boolean __keepAlive = true;
public PHPRPC_Client() {
}
public PHPRPC_Client(String serverURL) {
this.useService(serverURL);
}
public final Object useService(Class type) {
PHPRPC_InvocationHandler handler = new PHPRPC_InvocationHandler(this);
if (type.isInterface()) {
return Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { type }, handler);
}
else {
return Proxy.newProxyInstance(this.getClass().getClassLoader(), type.getInterfaces(), handler);
}
}
public final Object useService(Class[] interfaces) {
PHPRPC_InvocationHandler handler = new PHPRPC_InvocationHandler(this);
return Proxy.newProxyInstance(this.getClass().getClassLoader(), interfaces, handler);
}
public final boolean useService(String serverURL) {
return useService(serverURL, null, null);
}
public final Object useService(String serverURL, Class type) {
if (useService(serverURL, null, null)) {
return useService(type);
}
else {
return null;
}
}
public final Object useService(String serverURL, Class[] interfaces) {
if (useService(serverURL, null, null)) {
return useService(interfaces);
}
else {
return null;
}
}
public final boolean useService(String serverURL, String username, String password) {
URL url;
try {
url = new URL(serverURL);
}
catch (MalformedURLException e) {
return false;
}
if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) {
return false;
}
this.__server = new HashMap();
this.__server.put("scheme", url.getProtocol());
this.__server.put("host", url.getHost());
this.__server.put("port", new Integer((url.getPort() == -1) ? url.getDefaultPort() : url.getPort()));
this.__server.put("path", url.getFile());
this.__server.put("userinfo", ((username == null) ? url.getUserInfo() : username + ':' + password));
this.__disconnect();
this.__httpVersion = "1.1";
this.__keepAlive = true;
this.__key = null;
this.__keylen = 128;
this.__encryptMode = 0;
this.__cookie = "";
this.__phpser = new PHPSerializer();
this.setCharset("utf-8");
return true;
}
public final Object useService(String serverURL, String username, String password, Class type) {
if (useService(serverURL, username, password)) {
return useService(type);
}
else {
return null;
}
}
public final Object useService(String serverURL, String username, String password, Class[] interfaces) {
if (useService(serverURL, username, password)) {
return useService(interfaces);
}
else {
return null;
}
}
public final void setProxy(String address) throws MalformedURLException {
if (address == null) {
this.__proxy = null;
}
else {
URL url = new URL(address);
this.setProxy(url.getHost(), ((url.getPort() == -1) ? url.getDefaultPort() : url.getPort()), url.getUserInfo());
}
}
public final void setProxy(String host, int port) {
this.setProxy(host, port, null);
}
public final void setProxy(String host, int port, String username, String password) {
this.setProxy(host, port, ((username == null) ? null : username + ':' + password));
}
private final void setProxy(String host, int port, String userinfo) {
this.__proxy = new HashMap();
this.__proxy.put("host", host);
this.__proxy.put("port", new Integer(port));
this.__proxy.put("userinfo", userinfo);
}
public final boolean setKeyLength(int keyLength) {
if (this.__key != null) {
return false;
}
else {
this.__keylen = keyLength;
return true;
}
}
public final int getKeyLength() {
return this.__keylen;
}
public final boolean setEncryptMode(int encryptMode) {
if ((encryptMode >= 0) && (encryptMode <= 3)) {
this.__encryptMode = encryptMode;
return true;
}
else {
this.__encryptMode = 0;
return false;
}
}
public final void setCharset(String charset) {
this.__charset = charset;
this.__phpser.setCharset(this.__charset);
}
public final String getCharset() {
return this.__charset;
}
public final void setTimeout(int timeout) {
this.__timeout = timeout;
}
public final int getTimeout() {
return this.__timeout;
}
public final String getOutput() {
return this.__output;
}
public final PHPRPC_Error getWarning() {
return this.__warning;
}
public Object invoke(String function, Object[] args) {
return this.invoke(function, args, false);
}
public Object invoke(String function, Object[] args, boolean byRef) {
try {
this.__keyExchange();
StringBuffer requestBody = new StringBuffer();
requestBody.append("phprpc_func=").append(function);
if (args != null && args.length > 0) {
requestBody.append("&phprpc_args=");
requestBody.append(Base64.encode(this.__encrypt(this.__phpser.serialize(args), 1)).replaceAll("\\+", "%2B"));
}
requestBody.append("&phprpc_encrypt=").append(this.__encryptMode);
if (!byRef) {
requestBody.append("&phprpc_ref=false");
}
HashMap result = this.__post(requestBody.toString());
int errno = Integer.parseInt((String) result.get("phprpc_errno"));
if (errno > 0) {
String errstr = new String(Base64.decode((String) result.get("phprpc_errstr")), this.__charset);
this.__warning = new PHPRPC_Error(errno, errstr);
}
else {
this.__warning = null;
}
if (result.containsKey("phprpc_output")) {
byte[] output = Base64.decode((String) result.get("phprpc_output"));
if (Double.parseDouble((String) this.__server.get("version")) >= 3) {
output = this.__decrypt(output, 3);
}
this.__output = new String(output, this.__charset);
}
else {
this.__output = "";
}
if (result.containsKey("phprpc_result")) {
if (result.containsKey("phprpc_args")) {
Object[] arguments = (Object[]) this.__phpser.unserialize(this.__decrypt(Base64.decode((String) result.get("phprpc_args")), 1), Object[].class);
for (int i = 0; i < Math.min(args.length, arguments.length); i++) {
args[i] = arguments[i];
}
}
return this.__phpser.unserialize(this.__decrypt(Base64.decode((String) result.get("phprpc_result")), 2));
}
else {
return this.__warning;
}
}
catch (PHPRPC_Error e) {
return e;
}
catch (Exception e) {
StackTraceElement[] st = e.getStackTrace();
StringBuffer es = new StringBuffer(e.toString()).append("\r\n");
for (int i = 0, n = st.length; i < n; i++) {
es.append(st[i].toString()).append("\r\n");
}
return new PHPRPC_Error(1, es.toString());
}
}
private final void __connect() throws IOException {
SocketFactory sf;
if (((String) this.__server.get("scheme")).equals("https")) {
sf = SSLSocketFactory.getDefault();
}
else {
sf = SocketFactory.getDefault();
}
String host;
int port;
if (this.__proxy != null) {
host = (String) this.__proxy.get("host");
port = ((Integer) this.__proxy.get("port")).intValue();
}
else {
host = (String) this.__server.get("host");
port = ((Integer) this.__server.get("port")).intValue();
}
this.__socket = sf.createSocket(host, port);
this.__socket.setSoTimeout(this.__timeout);
this.__socket.setKeepAlive(this.__keepAlive);
this.__socket.setTcpNoDelay(true);
}
private final void __disconnect() {
if (this.__socket != null) {
if (!this.__socket.isClosed()) {
try {
this.__socket.close();
}
catch (IOException e) {
this.__disconnect();
}
}
this.__socket = null;
}
}
private final void __sendRequest(String requestBody) throws IOException {
StringBuffer url = new StringBuffer();
StringBuffer connection = new StringBuffer();
if (this.__proxy == null) {
url.append(this.__server.get("path"));
connection.append("Connection: ");
connection.append(this.__keepAlive ? "Keep-Alive" : "close");
connection.append("\r\n");
connection.append("Pragma: no-cache\r\n");
connection.append("Cache-Control: no-cache\r\n");
}
else {
url.append(this.__server.get("scheme"));
url.append("://");
url.append(this.__server.get("host"));
url.append(":");
url.append(this.__server.get("port"));
url.append(this.__server.get("path"));
connection.append("Proxy-Connection: ");
connection.append(this.__keepAlive ? "Keep-Alive" : "close");
connection.append("\r\n");
if (this.__proxy.get("userinfo") != null) {
connection.append("Proxy-Authorization: Basic ");
connection.append(Base64.encode(((String) this.__proxy.get("userinfo")).getBytes(this.__charset)));
connection.append("\r\n");
}
}
StringBuffer auth = new StringBuffer();
if (this.__server.get("userinfo") != null) {
auth.append("Authorization: Basic ");
auth.append(Base64.encode(((String) this.__server.get("userinfo")).getBytes(this.__charset)));
auth.append("\r\n");
}
StringBuffer cookie = new StringBuffer();
if (this.__cookie != null) {
cookie.append("Cookie: ");
cookie.append(this.__cookie);
cookie.append("\r\n");
}
byte[] rb = requestBody.getBytes();
StringBuffer requestHeader = new StringBuffer();
requestHeader.append("POST ").append(url).append(" HTTP/").append(this.__httpVersion).append("\r\n");
requestHeader.append("Host: ").append(this.__server.get("host")).append(':').append(this.__server.get("port")).append("\r\n");
requestHeader.append("User-Agent: PHPRPC Client 3.0 for Java\r\n");
requestHeader.append(auth).append(connection).append(cookie);
requestHeader.append("Accept: */*\r\n");
requestHeader.append("Accept-Encoding: gzip,deflate\r\n");
requestHeader.append("Content-Type: application/x-www-form-urlencoded; charset=").append(this.__charset).append("\r\n");
requestHeader.append("Content-Length: ").append(rb.length).append("\r\n");
requestHeader.append("\r\n");
BufferedOutputStream os = new BufferedOutputStream(this.__socket.getOutputStream());
os.write(requestHeader.toString().getBytes());
os.write(rb);
os.flush();
}
private final void __removeCookie(StringBuffer cookies, String name) {
int pos1 = cookies.indexOf(name);
if (pos1 > -1) {
int pos2 = cookies.indexOf(";", pos1);
if (pos2 == -1) {
pos2 = cookies.length();
} else {
pos2++;
}
cookies.delete(pos1, pos2);
}
}
private final void __parseHeader(HashMap responseHeader) throws PHPRPC_Error {
String statuscode = (String) responseHeader.get("statuscode");
if (statuscode == null) {
throw new PHPRPC_Error(1, "Wrong HTTP server.");
}
if (!statuscode.equals("100") && !statuscode.equals("200")) {
throw new PHPRPC_Error(Integer.parseInt(statuscode), (String) responseHeader.get("status"));
}
this.__httpVersion = (String) responseHeader.get("version");
String xPowerdBy = (String) responseHeader.get("x-powered-by");
if (xPowerdBy == null) {
throw new PHPRPC_Error(1, "Wrong PHPRPC server.");
}
if (xPowerdBy.startsWith("PHPRPC Server/")) {
this.__server.put("version", xPowerdBy.substring(14));
}
else {
throw new PHPRPC_Error(1, "Wrong PHPRPC server.");
}
if (responseHeader.containsKey("content-type")) {
String charset = (String)responseHeader.get("content-type");
if (charset.startsWith("text/plain; charset=")) {
this.setCharset(charset.substring(20));
}
}
if (responseHeader.containsKey("set-cookie")) {
StringBuffer cookies = new StringBuffer((String) responseHeader.get("set-cookie"));
this.__removeCookie(cookies, "path=");
this.__removeCookie(cookies, "domain=");
this.__removeCookie(cookies, "expires=");
this.__cookie = cookies.toString();
}
}
private final String __readLine(InputStream is) throws IOException {
StringBuffer sb = new StringBuffer();
int c;
while ((c = is.read()) > -1) {
if (c == 13) {
c = is.read();
if (c != 10) {
throw new IOException();
}
else {
return sb.toString();
}
}
else {
sb.append((char) c);
}
}
return sb.toString();
}
private final HashMap __readResponseHeader(String requestBody) throws IOException, PHPRPC_Error {
this.__sendRequest(requestBody);
HashMap responseHeader;
boolean cont;
do {
InputStream is = this.__socket.getInputStream();
responseHeader = new HashMap();
String buf;
while (!(buf = this.__readLine(is)).equals("")) {
if (buf.startsWith("HTTP/")) {
responseHeader.put("version", buf.substring(5, 8));
responseHeader.put("statuscode", buf.substring(9, 12));
responseHeader.put("status", buf.substring(13));
} else {
int pos = buf.indexOf(":");
if (pos > -1) {
responseHeader.put(buf.substring(0, pos).toLowerCase(), buf.substring(pos + 1).trim());
}
}
}
try {
this.__parseHeader(responseHeader);
}
catch (PHPRPC_Error e) {
this.__disconnect();
throw e;
}
cont = ((String) responseHeader.get("statuscode")).equals("100");
if (cont) {
BufferedOutputStream os = new BufferedOutputStream(this.__socket.getOutputStream());
os.write(new String("\r\n").getBytes());
os.flush();
}
} while (cont);
return responseHeader;
}
private final byte[] __ungzip(HashMap responseHeader, byte[] responseBodyByteArray) throws IOException, PHPRPC_Error {
String contentEncoding = (String) responseHeader.get("content-encoding");
if (contentEncoding != null && contentEncoding.toLowerCase().equals("gzip")) {
ByteArrayInputStream bais = new ByteArrayInputStream(responseBodyByteArray);
GZIPInputStream gzipis = new GZIPInputStream(bais);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int n = responseBodyByteArray.length;
byte[] buf = new byte[n];
int len;
while ((len = gzipis.read(buf, 0, n)) > -1) {
baos.write(buf, 0, len);
}
responseBodyByteArray = baos.toByteArray();
}
return responseBodyByteArray;
}
private final HashMap __parseBody(byte[] responseBodyByteArray) throws IOException, PHPRPC_Error {
ByteArrayInputStream is = new ByteArrayInputStream(responseBodyByteArray);
HashMap result = new HashMap();
String buf;
while (!(buf = this.__readLine(is)).equals("")) {
int p = buf.indexOf("=");
if (p > -1) {
result.put(buf.substring(0, p), buf.substring(p + 2, buf.length() - 2));
}
}
return result;
}
private final HashMap __readResponseBody(HashMap responseHeader) throws IOException, PHPRPC_Error {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = this.__socket.getInputStream();
if (responseHeader.get("content-length") == null) {
String te = (String) responseHeader.get("transfer-encoding");
if (te != null && te.toLowerCase().equals("chunked")) {
int n;
while ((n = Integer.parseInt(this.__readLine(is), 16)) > 0) {
byte[] b = new byte[n];
int len;
while (n > 0 && (len = is.read(b, 0, n)) > -1) {
baos.write(b, 0, len);
n -= len;
}
is.skip(2);
}
}
else {
byte[] b = new byte[2048];
int len;
while ((len = is.read(b, 0, 2048)) > -1) {
baos.write(b, 0, len);
}
this.__keepAlive = false;
this.__disconnect();
}
}
else {
int n = Integer.parseInt((String) responseHeader.get("content-length"));
byte[] b = new byte[n];
int len;
while (n > 0 && (len = is.read(b, 0, n)) > -1) {
baos.write(b, 0, len);
n -= len;
}
}
return this.__parseBody(this.__ungzip(responseHeader, baos.toByteArray()));
}
private final HashMap __post(String requestBody) throws IOException, PHPRPC_Error {
if (this.__socket == null) {
this.__connect();
}
HashMap responseHeader = this.__readResponseHeader(requestBody);
HashMap responseBody = this.__readResponseBody(responseHeader);
String connection = (String) responseHeader.get("connection");
if (this.__keepAlive && connection != null && connection.equals("close")) {
this.__keepAlive = false;
}
if (!this.__keepAlive) this.__disconnect();
return responseBody;
}
private void __keyExchange() throws IOException, IllegalAccessException, NoSuchAlgorithmException, PHPRPC_Error {
if (this.__key != null || this.__encryptMode == 0) return;
HashMap result = this.__post("phprpc_encrypt=true&phprpc_keylen=" + this.__keylen);
if (result.containsKey("phprpc_keylen")) {
this.__keylen = Integer.parseInt((String) result.get("phprpc_keylen"));
}
else {
this.__keylen = 128;
}
if (result.containsKey("phprpc_encrypt")) {
HashMap encrypt = (HashMap) this.__phpser.unserialize(Base64.decode((String) result.get("phprpc_encrypt")), HashMap.class);
BigInteger x = (new BigInteger(this.__keylen - 1, new Random())).setBit(this.__keylen - 2);
BigInteger y = new BigInteger((String) encrypt.get("y"));
BigInteger p = new BigInteger((String) encrypt.get("p"));
BigInteger g = new BigInteger((String) encrypt.get("g"));
BigInteger k = y.modPow(x, p);
byte[] key;
if (this.__keylen == 128) {
key = k.toByteArray();
}
else {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(k.toString().getBytes());
key = md5.digest();
}
this.__key = new byte[16];
for (int i = 1, n = Math.min(key.length, 16); i <= n; i++) {
this.__key[16 - i] = key[key.length - i];
}
this.__post("phprpc_encrypt=" + g.modPow(x, p).toString());
}
else {
this.__key = null;
this.__encryptMode = 0;
}
}
private byte[] __encrypt(byte[] s, int level) {
if (this.__key != null && this.__encryptMode >= level) {
s = XXTEA.encrypt(s, this.__key);
}
return s;
}
private byte[] __decrypt(byte[] s, int level) {
if (this.__key != null && this.__encryptMode >= level) {
s = XXTEA.decrypt(s, this.__key);
}
return s;
}
}
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.