Menu

[r492]: / phprpc_3.0 / dotNET / PHPRPC_Server.cs  Maximize  Restore  History

Download this file

668 lines (605 with data), 25.6 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
/**********************************************************\
| |
| The implementation of PHPRPC Protocol 3.0 |
| |
| PHPRPC_Server.cs |
| |
| Release 3.0.1 |
| Copyright (c) 2005-2008 by Team-PHPRPC |
| |
| WebSite: http://www.phprpc.org/ |
| http://www.phprpc.net/ |
| 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 3.0 as published by the Free Software Foundation |
| and appearing in the included file LICENSE. |
| |
\**********************************************************/
/* PHPRPC Server library.
*
* Copyright (C) 2005-2008 Ma Bingyao <andot@ujn.edu.cn>
* Version: 3.0
* LastModified: Dec 19, 2008
* This library is free. You can redistribute it and/or modify it.
*/
#if !(PocketPC || Smartphone || WindowsCE || ClientOnly)
namespace org.phprpc {
using System;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.SessionState;
using org.phprpc.util;
using System.Globalization;
using System.Collections.Specialized;
public class PHPRPC_Server {
private class RemoteFunction {
public Object obj;
public MethodInfo[] functions;
public RemoteFunction(Object obj, MethodInfo[] functions) {
this.obj = obj;
this.functions = functions;
}
}
private HttpRequest request = HttpContext.Current.Request;
private HttpResponse response = HttpContext.Current.Response;
private HttpSessionState session = HttpContext.Current.Session;
private HttpServerUtility server = HttpContext.Current.Server;
private Hashtable functions = new Hashtable();
private PHPFormatter formatter = null;
private Boolean debug = false;
private Encoding encoding = new UTF8Encoding();
private Boolean encode = true;
private Boolean byref = false;
private Boolean encrypt = false;
private Byte encryptMode = 0;
private Byte[] key = null;
private UInt32 keylen = 128;
private BigInteger y = null;
private String output = String.Empty;
private String callback = String.Empty;
private Int32 errno = 0;
private String errstr = String.Empty;
private String cid = String.Empty;
private StringBuilder buffer = new StringBuilder();
private static Regex test = new Regex(@"[\0-\037\042\047\134\177]", RegexOptions.Compiled);
private static Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
private static Hashtable globalFunctions = new Hashtable();
public PHPRPC_Server() {
formatter = new PHPFormatter(encoding, assemblies);
}
public static Boolean AddGlobal(Object obj) {
Type type = obj.GetType();
return AddGlobal(GetAllFunctions(type, BindingFlags.Instance), obj, type, null);
}
public static Boolean AddGlobal(Type type) {
return AddGlobal(GetAllFunctions(type, BindingFlags.Static), null, type, null);
}
public static Boolean AddGlobal(String function, Object obj) {
return AddGlobal(new String[] { function }, obj, obj.GetType(), null);
}
public static Boolean AddGlobal(String function, Object obj, String alias) {
return AddGlobal(new String[] { function }, obj, obj.GetType(), new String[] { alias });
}
public static Boolean AddGlobal(String[] functions, Object obj) {
return AddGlobal(functions, obj, obj.GetType(), null);
}
public static Boolean AddGlobal(String[] functions, Object obj, String[] aliases) {
return AddGlobal(functions, obj, obj.GetType(), aliases);
}
public static Boolean AddGlobal(String function, Type type) {
return AddGlobal(new String[] { function }, null, type, null);
}
public static Boolean AddGlobal(String function, Type type, String alias) {
return AddGlobal(new String[] { function }, null, type, new String[] { alias });
}
public static Boolean AddGlobal(String[] functions, Type type) {
return AddGlobal(functions, null, type, null);
}
public static Boolean AddGlobal(String[] functions, Type type, String[] aliases) {
return AddGlobal(functions, null, type, aliases);
}
public Boolean Add(Object obj) {
Type type = obj.GetType();
return Add(GetAllFunctions(type, BindingFlags.Instance), obj, type, null);
}
public Boolean Add(Type type) {
return Add(GetAllFunctions(type, BindingFlags.Static), null, type, null);
}
public Boolean Add(String function, Object obj) {
return Add(new String[] { function }, obj, obj.GetType(), null);
}
public Boolean Add(String function, Object obj, String alias) {
return Add(new String[] { function }, obj, obj.GetType(), new String[] { alias });
}
public Boolean Add(String[] functions, Object obj) {
return Add(functions, obj, obj.GetType(), null);
}
public Boolean Add(String[] functions, Object obj, String[] aliases) {
return Add(functions, obj, obj.GetType(), aliases);
}
public Boolean Add(String function, Type type) {
return Add(new String[] { function }, null, type, null);
}
public Boolean Add(String function, Type type, String alias) {
return Add(new String[] { function }, null, type, new String[] { alias });
}
public Boolean Add(String[] functions, Type type) {
return Add(functions, null, type, null);
}
public Boolean Add(String[] functions, Type type, String[] aliases) {
return Add(functions, null, type, aliases);
}
public void Start() {
buffer = new StringBuilder();
try {
InitErrorHandler();
InitClientID();
InitEncode();
InitCallback();
InitRef();
InitEncrypt();
if (request.Params["phprpc_func"] != null) {
CallFunction();
}
else if (encrypt != false || y != null) {
KeyExchange();
}
else {
SendFunctions();
}
}
catch (Exception e) {
errno = 1;
if (debug) {
errstr = e.ToString();
}
else {
errstr = e.Message;
}
SendError();
}
}
public String Charset {
get {
return encoding.WebName;
}
set {
encoding = Encoding.GetEncoding(value);
formatter.Encoding = encoding;
}
}
public Boolean DebugMode {
get {
return debug;
}
set {
debug = value;
}
}
private static String[] GetAllFunctions(Type type, BindingFlags bindingFlags) {
MethodInfo[] methods = type.GetMethods(BindingFlags.Public | bindingFlags);
ArrayList names = new ArrayList();
for (Int32 i = 0, n = methods.Length; i < n; i++) {
String fn = methods[i].Name.ToLower(CultureInfo.InvariantCulture);
if (!names.Contains(fn)) {
names.Add(fn);
}
}
return (String[])names.ToArray(typeof(String));
}
private static Boolean Add(String[] funcnames, Object obj, Type type, String[] aliases, Hashtable functions) {
if (funcnames == null) {
return false;
}
if (aliases == null) {
aliases = funcnames;
}
if (funcnames.Length != aliases.Length) {
return false;
}
BindingFlags bindingflags = BindingFlags.Public;
if (obj == null) {
bindingflags |= BindingFlags.Static;
}
else {
bindingflags |= BindingFlags.Instance;
}
MethodInfo[] methods = type.GetMethods(bindingflags);
for (Int32 i = 0, n = funcnames.Length; i < n; i++) {
ArrayList fs = new ArrayList();
for (Int32 j = 0, m = methods.Length; j < m; j++) {
MethodInfo method = methods[j];
if (funcnames[i].ToLower(CultureInfo.InvariantCulture).Equals(method.Name.ToLower(CultureInfo.InvariantCulture))) {
fs.Add(method);
}
}
functions[aliases[i].ToLower(CultureInfo.InvariantCulture)] = new RemoteFunction(obj, (MethodInfo[])fs.ToArray(typeof(MethodInfo)));
}
return true;
}
private static Boolean AddGlobal(String[] funcnames, Object obj, Type type, String[] aliases) {
return Add(funcnames, obj, type, aliases, globalFunctions);
}
private Boolean Add(String[] funcnames, Object obj, Type type, String[] aliases) {
return Add(funcnames, obj, type, aliases, functions);
}
private String JsReplace(Match m) {
return String.Format("\\x{0:x2}", (Int32)m.Value[0]);
}
private String AddJsSlashes(String str) {
return test.Replace(str, new MatchEvaluator(JsReplace));
}
private String AddJsSlashes(Byte[] data) {
StringBuilder sb = new StringBuilder();
for (int i = 0, n = data.Length; i < n; i++) {
if (data[i] <= 31 || data[i] == 34 || data[i] == 39 || data[i] == 92 || data[i] >= 127) {
sb.Append(String.Format("\\x{0:x2}", data[i]));
}
else {
sb.Append((Char)data[i]);
}
}
return sb.ToString();
}
private String EncodeString(String str) {
if (encode) {
return Convert.ToBase64String(encoding.GetBytes(str));
}
else {
return AddJsSlashes(str);
}
}
private String EncodeString(Byte[] data) {
if (encode) {
return Convert.ToBase64String(data);
}
else {
return AddJsSlashes(data);
}
}
private Byte[] Base64Decode(String data) {
if (data == null) {
return null;
}
if (data == String.Empty) {
return new Byte[0];
}
return Convert.FromBase64String(data);
}
private Byte[] EncryptString(Byte[] data, Byte level) {
if (encryptMode >= level) {
data = XXTEA.Encrypt(data, key);
}
return data;
}
private Byte[] DecryptString(Byte[] data, Byte level) {
if (encryptMode >= level) {
data = XXTEA.Decrypt(data, key);
}
return data;
}
private Byte[] Serialize(Object obj) {
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, obj);
Byte[] result = ms.ToArray();
ms.Close();
return result;
}
private Object Deserialize(Byte[] data) {
MemoryStream ms = new MemoryStream(data);
ms.Position = 0;
Object result = formatter.Deserialize(ms);
ms.Close();
return result;
}
private void SendURL() {
if (session.IsNewSession) {
StringBuilder url = new StringBuilder(request.Path);
String[] keys = request.QueryString.AllKeys;
if (keys.Length > 0) {
url.Append('?');
foreach (String key in keys) {
if (!key.ToLower().StartsWith("phprpc_")) {
String[] values = request.QueryString.GetValues(key);
for (Int32 i = 0, n = values.Length; i < n; i++) {
url.Append(key).Append('=').Append(server.UrlEncode(values[i])).Append('&');
}
}
}
url.Length--;
}
buffer.Append("phprpc_url=\"");
buffer.Append(EncodeString(response.ApplyAppPathModifier(url.ToString())));
buffer.Append("\";\r\n");
}
}
private void SendCallback() {
buffer.Append(callback);
Byte[] data = encoding.GetBytes(buffer.ToString());
SendHeader();
response.AppendHeader("Content-Length", data.Length.ToString());
response.Clear();
if (data.Length > 0) {
response.BinaryWrite(data);
}
}
private void SendFunctions() {
buffer.Append("phprpc_functions=\"");
foreach (DictionaryEntry de in globalFunctions) {
functions.Add(de.Key, de.Value);
}
buffer.Append(EncodeString(Serialize(functions.Keys)));
buffer.Append("\";\r\n");
SendCallback();
}
private void SendOutput() {
if (encryptMode >= 3) {
buffer.Append("phprpc_output=\"");
buffer.Append(EncodeString(XXTEA.Encrypt(encoding.GetBytes(output), key)));
buffer.Append("\";\r\n");
}
else {
buffer.Append("phprpc_output=\"");
buffer.Append(EncodeString(output));
buffer.Append("\";\r\n");
}
}
private void SendError() {
buffer.Append("phprpc_errno=\"");
buffer.Append(errno);
buffer.Append("\";\r\n");
buffer.Append("phprpc_errstr=\"");
buffer.Append(EncodeString(errstr));
buffer.Append("\";\r\n");
SendOutput();
SendCallback();
}
private void SendHeader() {
response.ContentType = "text/plain; charset=" + Charset;
response.AppendHeader("P3P", "CP=\"CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV\"");
response.AppendHeader("X-Powered-By", "PHPRPC Server/3.0");
response.Cache.SetExpires(DateTime.Now);
response.Cache.SetNoStore();
response.Cache.AppendCacheExtension("no-cache");
response.Cache.AppendCacheExtension("must-revalidate");
response.Cache.SetMaxAge(new TimeSpan(0));
}
private Byte[] Call(MethodInfo function, Object obj, ArrayList arguments) {
ParameterInfo[] p = function.GetParameters();
String funcname = function.Name;
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms, encoding);
Int32 size = arguments.Count;
if (p.Length != size) {
if (p.Length == size + 1) {
Type type = p[p.Length - 1].ParameterType;
if (type == typeof(TextWriter) || type == typeof(StreamWriter)) {
arguments.Add(sw);
}
else {
throw new ArgumentException("number of arguments mismatch for " + funcname + "().");
}
}
else {
throw new ArgumentException("number of arguments mismatch for " + funcname + "().");
}
}
Object[] args = arguments.ToArray();
if (size < arguments.Count) {
arguments.RemoveAt(size);
}
for (Int32 i = 0, n = args.Length; i < n; i++) {
if (args[i] != null) {
args[i] = PHPConvert.ChangeType(args[i], p[i].ParameterType, encoding);
}
}
Byte[] result = Serialize(function.Invoke(obj, args));
sw.Close();
output = encoding.GetString(ms.ToArray());
ms.Close();
for (Int32 i = 0; i < size; i++) {
arguments[i] = args[i];
}
return result;
}
private Boolean GetBooleanRequest(String name) {
Boolean var = true;
if (request.Params[name] != null &&
request.Params[name].ToLower(CultureInfo.InvariantCulture).Equals("false")) {
var = false;
}
return var;
}
private void InitEncode() {
encode = GetBooleanRequest("phprpc_encode");
}
private void InitRef() {
byref = GetBooleanRequest("phprpc_ref");
}
private void InitErrorHandler() {
errno = 0;
errstr = String.Empty;
output = String.Empty;
}
private void InitCallback() {
if (request.Params["phprpc_callback"] != null) {
callback = encoding.GetString(Base64Decode(request.Params["phprpc_callback"]));
}
else {
callback = String.Empty;
}
}
private void InitClientID() {
cid = "0";
if (request.Params["phprpc_id"] != null) {
cid = request.Params["phprpc_id"];
}
cid = "phprpc_" + cid;
}
private void InitKeylen() {
if (request.Params["phprpc_keylen"] != null) {
keylen = UInt32.Parse(request.Params["phprpc_keylen"]);
}
else {
Hashtable sessionObject = (Hashtable)session.Contents[cid];
keylen = 128;
if (sessionObject != null) {
lock (sessionObject.SyncRoot) {
if (sessionObject["keylen"] != null) {
keylen = (UInt32)sessionObject["keylen"];
}
}
}
}
}
private void InitEncrypt() {
encrypt = false;
encryptMode = 0;
y = null;
if (request.Params["phprpc_encrypt"] != null) {
String enc = request.Params["phprpc_encrypt"].ToLower(CultureInfo.InvariantCulture);
switch (enc) {
case "true":
encrypt = true;
break;
case "false":
encrypt = false;
break;
case "0":
encryptMode = 0;
break;
case "1":
encryptMode = 1;
break;
case "2":
encryptMode = 2;
break;
case "3":
encryptMode = 3;
break;
default:
y = BigInteger.Parse(enc);
break;
}
}
}
private void InitKey() {
Hashtable sessionObject = (Hashtable)session.Contents[cid];
if (sessionObject != null) {
lock (sessionObject.SyncRoot) {
key = (Byte[])sessionObject["key"];
}
}
if (key == null && encryptMode > 0) {
encryptMode = 0;
throw new Exception("Can't find the key for decryption.");
}
}
private ArrayList GetArguments() {
ArrayList arguments;
if (request.Params["phprpc_args"] != null) {
arguments = ((AssocArray)Deserialize(DecryptString(Base64Decode(request.Params["phprpc_args"]), 1))).toArrayList();
}
else {
arguments = new ArrayList();
}
return arguments;
}
private void CallFunction() {
String funcname = request.Params["phprpc_func"].ToLower(CultureInfo.InvariantCulture);
RemoteFunction rf = null;
if (functions.ContainsKey(funcname)) {
rf = (RemoteFunction)functions[funcname];
}
else if (globalFunctions.ContainsKey(funcname)) {
rf = (RemoteFunction)globalFunctions[funcname];
}
else {
throw new Exception("Can't find this function " + request.Params["phprpc_func"] + "().");
}
InitKey();
ArrayList arguments = GetArguments();
String result = null;
for (Int32 i = 0, n = rf.functions.Length; i < n; i++) {
try {
result = EncodeString(EncryptString(Call(rf.functions[i], rf.obj, arguments), 2));
break;
}
catch (Exception e) {
if (i == n - 1) {
throw e;
}
}
}
buffer.Append("phprpc_result=\"");
buffer.Append(result);
buffer.Append("\";\r\n");
if (byref) {
buffer.Append("phprpc_args=\"");
buffer.Append(EncodeString(EncryptString(Serialize(arguments), 1)));
buffer.Append("\";\r\n");
}
SendError();
}
private void KeyExchange() {
Hashtable sessionObject;
InitKeylen();
if (encrypt) {
DHParams dhParams = new DHParams(keylen);
keylen = dhParams.GetL();
BigInteger p = dhParams.GetP();
BigInteger g = dhParams.GetG();
BigInteger x = dhParams.GetX();
BigInteger y = g.ModPow(x, p);
sessionObject = new Hashtable();
sessionObject["x"] = x;
sessionObject["p"] = p;
sessionObject["keylen"] = keylen;
session.Contents[cid] = sessionObject;
Hashtable dhp = dhParams.GetDHParams();
dhp["y"] = y.ToString();
buffer.Append("phprpc_encrypt=\"");
buffer.Append(EncodeString(Serialize(dhp)));
buffer.Append("\";\r\n");
if (keylen != 128) {
buffer.Append("phprpc_keylen=\"");
buffer.Append(keylen);
buffer.Append("\";\r\n");
}
SendURL();
}
else {
sessionObject = (Hashtable)session.Contents[cid];
lock (sessionObject.SyncRoot) {
BigInteger x = (BigInteger)sessionObject["x"];
BigInteger p = (BigInteger)sessionObject["p"];
if (keylen == 128) {
key = new byte[16];
Byte[] k = y.ModPow(x, p).GetBytes();
for (Int32 i = 1, n = Math.Min(k.Length, 16); i <= n; i++) {
this.key[16 - i] = k[n - i];
}
}
else {
key = MD5.Hash(Encoding.ASCII.GetBytes(y.ModPow(x, p).ToString()));
}
sessionObject["key"] = key;
sessionObject.Remove("x");
sessionObject.Remove("p");
session.Contents[cid] = sessionObject;
}
}
SendCallback();
}
}
}
#endif
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.