This repository has been archived by the owner on Aug 19, 2018. It is now read-only.
/
BaseHttpServer.cs
1615 lines (1377 loc) · 60.3 KB
/
BaseHttpServer.cs
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Xml;
using System.Security.Cryptography.X509Certificates;
using System.Security.Authentication;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Amib.Threading;
using System.IO.Compression;
namespace OpenSim.Framework.Servers.HttpServer
{
public class BaseHttpServer : IHttpServer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Gets or sets the debug level.
/// </summary>
/// <value>
/// See MainServer.DebugLevel.
/// </value>
public int DebugLevel { get; set; }
private volatile uint RequestNumber = 0;
protected HttpListener m_httpListener;
protected Dictionary<string, XmlRpcMethod> m_rpcHandlers = new Dictionary<string, XmlRpcMethod>();
protected Dictionary<string, bool> m_rpcHandlersKeepAlive = new Dictionary<string, bool>();
protected Dictionary<string, LLSDMethod> m_llsdHandlers = new Dictionary<string, LLSDMethod>();
protected Dictionary<string, IRequestHandler> m_streamHandlers = new Dictionary<string, IRequestHandler>();
protected Dictionary<string, GenericHTTPMethod> m_HTTPHandlers = new Dictionary<string, GenericHTTPMethod>();
// The Main Thread Pool
protected const int c_ThreadIdleTimeout = 1000;
protected const int c_ThreadPoolMaxSize = 64;
protected const int c_ThreadPoolMinSize = 2;
protected SmartThreadPool m_Threads = new SmartThreadPool(c_ThreadIdleTimeout, c_ThreadPoolMaxSize, c_ThreadPoolMinSize);
// SSL Support
protected X509Certificate2 m_cert;
protected SslProtocols m_sslProtocol = SslProtocols.None;
protected bool m_isSecure;
protected uint m_port;
protected string m_hostName;
protected IPAddress m_listenIPAddress = IPAddress.Any;
public uint Port
{
get { return m_port; }
}
public bool Secure
{
get { return m_isSecure; }
}
public IPAddress ListenIPAddress
{
get { return m_listenIPAddress; }
set { m_listenIPAddress = value; }
}
public string HostName
{
get { return m_hostName; }
set { m_hostName = value; }
}
public string Protocol
{
get
{
string protocol = "http://";
if (Secure)
protocol = "https://";
return protocol;
}
}
public string FullHostName
{
get
{
string protocol = "http://";
if (Secure)
protocol = "https://";
return protocol + m_hostName;
}
}
/// <summary>
/// A well-formed URI for the host region server (namely "http://ExternalHostName:Port)
/// </summary>
public string ServerURI
{
get
{
string protocol = "http://";
if (Secure)
protocol = "https://";
return protocol + m_hostName + ":" + m_port.ToString();
}
}
public bool IsRunning
{
get { return m_httpListener.IsListening; }
}
public BaseHttpServer(uint port, IPAddress ipaddr)
{
m_Threads.Name = "HttpServer";
m_port = port;
m_isSecure = false;
if (ipaddr == null)
m_listenIPAddress = IPAddress.Any;
else
m_listenIPAddress = ipaddr;
}
private X509Certificate2 GetCertificateFromStore(string certName)
{
// Get the certificate store for the current user.
X509Store store = new X509Store(StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly);
// Place all certificates in an X509Certificate2Collection object.
X509Certificate2Collection certCollection = store.Certificates;
// If using a certificate with a trusted root you do not need to FindByTimeValid, instead:
// currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, true);
X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false);
if (signingCert.Count == 0)
return null;
// Return the first certificate in the collection, has the right name and is current.
return signingCert[0];
}
finally
{
store.Close();
}
}
/// <summary>
/// Set the SSL params based on lookup of the cert in the local store using
/// the common name provided.
/// </summary>
/// <param name="commonName"></param>
/// <param name="protocol"></param>
public void SetSecureParams(string commonName, SslProtocols protocol)
{
m_isSecure = true;
m_cert = GetCertificateFromStore(commonName);
m_sslProtocol = protocol;
}
/// <summary>
/// Set the SSL params based on a filepath and password to access and unlock a certificate.
/// </summary>
/// <param name="path"></param>
/// <param name="password"></param>
/// <param name="protocol"></param>
public void SetSecureParams(string path, string password, SslProtocols protocol)
{
m_isSecure = true;
m_cert = new X509Certificate2(path, password);
m_sslProtocol = protocol;
}
/// <summary>
/// Add a stream handler to the http server. If the handler already exists, then nothing happens.
/// </summary>
/// <param name="handler"></param>
public void AddStreamHandler(IRequestHandler handler)
{
string httpMethod = handler.HttpMethod;
string path = handler.Path;
string handlerKey = GetHandlerKey(httpMethod, path);
lock (m_streamHandlers)
{
if (!m_streamHandlers.ContainsKey(handlerKey))
{
// m_log.DebugFormat("[BASE HTTP SERVER]: Adding handler key {0}", handlerKey);
m_streamHandlers.Add(handlerKey, handler);
}
}
}
public List<string> GetStreamHandlerKeys()
{
lock (m_streamHandlers)
return new List<string>(m_streamHandlers.Keys);
}
private static string GetHandlerKey(string httpMethod, string path)
{
return httpMethod + ":" + path;
}
public bool AddXmlRPCHandler(string method, XmlRpcMethod handler)
{
return AddXmlRPCHandler(method, handler, true);
}
public bool AddXmlRPCHandler(string method, XmlRpcMethod handler, bool keepAlive)
{
lock (m_rpcHandlers)
{
m_rpcHandlers[method] = handler;
m_rpcHandlersKeepAlive[method] = keepAlive; // default
}
return true;
}
public XmlRpcMethod GetXmlRPCHandler(string method)
{
lock (m_rpcHandlers)
{
if (m_rpcHandlers.ContainsKey(method))
{
return m_rpcHandlers[method];
}
else
{
return null;
}
}
}
public List<string> GetXmlRpcHandlerKeys()
{
lock (m_rpcHandlers)
return new List<string>(m_rpcHandlers.Keys);
}
public bool AddHTTPHandler(string methodName, GenericHTTPMethod handler)
{
//m_log.DebugFormat("[BASE HTTP SERVER]: Registering {0}", methodName);
lock (m_HTTPHandlers)
{
if (!m_HTTPHandlers.ContainsKey(methodName))
{
m_HTTPHandlers.Add(methodName, handler);
return true;
}
}
//must already have a handler for that path so return false
return false;
}
public List<string> GetHTTPHandlerKeys()
{
lock (m_HTTPHandlers)
return new List<string>(m_HTTPHandlers.Keys);
}
public bool AddLLSDHandler(string path, LLSDMethod handler)
{
lock (m_llsdHandlers)
{
if (!m_llsdHandlers.ContainsKey(path))
{
m_llsdHandlers.Add(path, handler);
return true;
}
}
return false;
}
public List<string> GetLLSDHandlerKeys()
{
lock (m_llsdHandlers)
return new List<string>(m_llsdHandlers.Keys);
}
private void OnRequest(IAsyncResult result)
{
if (m_httpListener == null)
return;
try
{
HttpListenerContext context = m_httpListener.EndGetContext(result);
// *** Immediately set up the next context
if (m_httpListener.IsListening)
m_httpListener.BeginGetContext(new AsyncCallback(OnRequest), m_httpListener);
m_Threads.QueueWorkItem(HandleRequest, context);
}
catch (Exception e)
{
m_log.ErrorFormat("[BASE HTTP SERVER]: OnRequest() failed with {0}{1}", e.Message, e.StackTrace);
}
}
/// <summary>
/// This methods is the start of incoming HTTP request handling.
/// </summary>
/// <param name="request"></param>
/// <param name="response"></param>
public void HandleRequest(HttpListenerContext context)
{
OSHttpRequest request = new OSHttpRequest(context.Request);
OSHttpResponse response = new OSHttpResponse(context.Response);
request.SeqNo = RequestNumber++;
request.StartTime = Environment.TickCount;
string requestMethod = request.HttpMethod;
string uriString = request.RawUrl;
IRequestHandler requestHandler = null;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", true);
// If they ask for it we'll use it.
response.KeepAlive = request.KeepAlive;
response.SendChunked = false;
string path = request.RawUrl;
string handlerKey = GetHandlerKey(request.HttpMethod, path);
byte[] buffer = null;
try
{
if (String.IsNullOrEmpty(request.HttpMethod)) // Can't handle empty requests, not wasting a thread
{
buffer = SendHTML500(response);
}
else if (TryGetStreamHandler(handlerKey, out requestHandler))
{
if (DebugLevel >= 3)
LogIncomingToStreamHandler(request, requestHandler);
response.ContentType = requestHandler.ContentType; // Lets do this defaulting before in case handler has varying content type.
if (requestHandler is IAsyncRequestHandler)
{
// Call the request handler. The Response is sent Async from the handler
IAsyncRequestHandler asyncHandler = requestHandler as IAsyncRequestHandler;
asyncHandler.Handle(this, path, request, response);
return;
}
else if (requestHandler is IStreamedRequestHandler)
{
IStreamedRequestHandler streamedRequestHandler = requestHandler as IStreamedRequestHandler;
buffer = streamedRequestHandler.Handle(path, request.InputStream, request, response);
}
else if (requestHandler is IGenericHTTPHandler)
{
IGenericHTTPHandler HTTPRequestHandler = requestHandler as IGenericHTTPHandler;
Stream requestStream = request.InputStream;
Encoding encoding = Encoding.UTF8;
StreamReader reader = new StreamReader(requestStream, encoding);
string requestBody = reader.ReadToEnd();
reader.Close();
//requestStream.Close();
Hashtable keysvals = new Hashtable();
Hashtable headervals = new Hashtable();
//string host = String.Empty;
foreach (string queryname in request.QueryString.AllKeys)
keysvals.Add(queryname, request.QueryString[queryname]);
foreach (string headername in request.Headers.AllKeys)
headervals[headername] = request.Headers[headername];
headervals["remote_addr"] = request.RemoteIPEndPoint.ToString();
keysvals.Add("requestbody", requestBody);
keysvals.Add("headers", headervals);
if (keysvals.Contains("method"))
{
//m_log.Warn("[HTTP]: Contains Method");
//string method = (string)keysvals["method"];
//m_log.Warn("[HTTP]: " + requestBody);
}
buffer = DoHTTPGruntWork(HTTPRequestHandler.Handle(path, keysvals), request, response);
}
else
{
IStreamHandler streamHandler = (IStreamHandler)requestHandler;
using (MemoryStream memoryStream = new MemoryStream())
{
streamHandler.Handle(path, request.InputStream, memoryStream, request, response);
memoryStream.Flush();
buffer = memoryStream.ToArray();
}
}
}
else
{
switch (request.ContentType)
{
case null:
case "text/html":
if (DebugLevel >= 3)
m_log.DebugFormat(
"[BASE HTTP SERVER]: HTTP IN {0} :{1} {2} content type handler {3} {4} from {5}",
request.SeqNo, Port, request.ContentType, request.HttpMethod, request.Url.PathAndQuery, request.RemoteIPEndPoint);
buffer = HandleHTTPRequest(request, response);
break;
case "application/llsd+xml":
case "application/xml+llsd":
case "application/llsd+json":
if (DebugLevel >= 3)
m_log.DebugFormat(
"[BASE HTTP SERVER]: HTTP IN {0} :{1} {2} content type handler {3} {4} from {5}",
request.SeqNo, Port, request.ContentType, request.HttpMethod, request.Url.PathAndQuery, request.RemoteIPEndPoint);
buffer = HandleLLSDRequests(request, response);
break;
case "text/xml":
case "application/xml":
case "application/json":
default:
if (DoWeHaveALLSDHandler(request.RawUrl))
{
if (DebugLevel >= 3)
LogIncomingToContentTypeHandler(request);
buffer = HandleLLSDRequests(request, response);
}
else if (DoWeHaveAHTTPHandler(request.RawUrl))
{
if (DebugLevel >= 3)
LogIncomingToContentTypeHandler(request);
buffer = HandleHTTPRequest(request, response);
}
else
{
if (DebugLevel >= 3)
LogIncomingToXmlRpcHandler(request);
// generic login request.
buffer = HandleXmlRpcRequests(request, response);
}
break;
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[BASE HTTP SERVER] Caught exception while handling request: {0} {1}", path, e);
buffer = SendHTML500(response);
}
SendResponse(request, response, requestHandler, buffer);
}
public void SendResponse(OSHttpRequest request, OSHttpResponse response, IRequestHandler requestHandler, byte[] buffer)
{
try
{
request.InputStream.Close();
// Do not include the time taken to actually send the response to the caller in the measurement
// time. This is to avoid logging when it's the client that is slow to process rather than the
// server
request.EndTime = Environment.TickCount;
// Every month or so this will wrap and give bad numbers, not really a problem
// since its just for reporting
int tickdiff = request.EndTime - request.StartTime;
// Dont log EQG messages. They always run long due to the way the queue works
if ((tickdiff > 3000) && (request.Url.AbsolutePath.StartsWith("/CAPS/EQG") == false))
{
m_log.InfoFormat(
"[BASE HTTP SERVER]: Slow handling of {0} {1} {2} {3} {4} from {5} took {6}ms",
request.SeqNo,
request.HttpMethod,
request.Url.AbsolutePath,
requestHandler != null ? requestHandler.Name : String.Empty,
requestHandler != null ? requestHandler.Description : String.Empty,
request.RemoteIPEndPoint,
tickdiff);
}
else if (DebugLevel >= 4)
{
m_log.DebugFormat(
"[BASE HTTP SERVER]: HTTP IN {0} :{1} took {2}ms",
request.SeqNo,
Port,
tickdiff);
}
if (buffer != null)
{
//find the accept encoding key
string acceptEncodingKey = null;
foreach (string key in request.Headers.AllKeys)
{
if (key.ToLower() == "accept-encoding")
{
acceptEncodingKey = request.Headers[key];
}
}
// GZip compress the response if the client says they can handle that
if (acceptEncodingKey != null &&
request.Headers["accept-encoding"].Contains("gzip"))
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gs = new GZipStream(ms, CompressionMode.Compress))
{
gs.Write(buffer, 0, buffer.Length);
}
buffer = ms.ToArray();
}
response.AddHeader("Content-Encoding", "gzip");
}
if (!response.SendChunked)
response.ContentLength64 = buffer.LongLength;
response.OutputStream.BeginWrite(buffer, 0, buffer.Length, ResponseWriteFinished, Tuple.Create(request, response, requestHandler));
}
}
catch (Exception e)
{
//fill out request end time to get an actual count in case the exception is thrown in response.Write
request.EndTime = Environment.TickCount;
int tickdiff = request.EndTime - request.StartTime;
m_log.ErrorFormat(
"[BASE HTTP SERVER]: HandleRequest() threw {0} while processing {1} {2} {3} {4} {5} took {6}ms",
e,
request.SeqNo,
request.HttpMethod,
request.Url.AbsolutePath,
requestHandler != null ? requestHandler.Name : String.Empty,
requestHandler != null ? requestHandler.Description : String.Empty,
tickdiff);
// note that request.RemoteIPEndPoint is often disposed when we reach here (e.g. remote end has crashed)
}
}
private void ResponseWriteFinished(IAsyncResult ar)
{
var parms = (Tuple<OSHttpRequest, OSHttpResponse, IRequestHandler>)ar.AsyncState;
OSHttpRequest request = parms.Item1;
OSHttpResponse response = parms.Item2;
IRequestHandler requestHandler = parms.Item3;
try
{
response.OutputStream.EndWrite(ar);
parms.Item2.OutputStream.Flush(); //should be a NOP
parms.Item2.OutputStream.Close();
}
catch (Exception e)
{
m_log.ErrorFormat(
"[BASE HTTP SERVER]: ResponseWriteFinished() threw {0} while processing {1} {2} {3} {4} {5}",
e,
request.SeqNo,
request.HttpMethod,
request.Url.AbsolutePath,
requestHandler != null ? requestHandler.Name : String.Empty,
requestHandler != null ? requestHandler.Description : String.Empty);
try
{
parms.Item2.Response.Abort();
}
catch
{ }
}
}
private void LogIncomingToStreamHandler(OSHttpRequest request, IRequestHandler requestHandler)
{
m_log.DebugFormat(
"[BASE HTTP SERVER]: HTTP IN {0} :{1} stream handler {2} {3} {4} {5} from {6}",
request.SeqNo,
Port,
request.HttpMethod,
request.Url.PathAndQuery,
requestHandler.Name,
requestHandler.Description,
request.RemoteIPEndPoint);
if (DebugLevel >= 5)
LogIncomingInDetail(request);
}
private void LogIncomingToContentTypeHandler(OSHttpRequest request)
{
m_log.DebugFormat(
"[BASE HTTP SERVER]: HTTP IN {0} :{1} {2} content type handler {3} {4} from {5}",
request.SeqNo,
Port,
request.ContentType,
request.HttpMethod,
request.Url.PathAndQuery,
request.RemoteIPEndPoint);
if (DebugLevel >= 5)
LogIncomingInDetail(request);
}
private void LogIncomingToXmlRpcHandler(OSHttpRequest request)
{
m_log.DebugFormat(
"[BASE HTTP SERVER]: HTTP IN {0} :{1} assumed generic XMLRPC request {2} {3} from {4}",
request.SeqNo,
Port,
request.HttpMethod,
request.Url.PathAndQuery,
request.RemoteIPEndPoint);
if (DebugLevel >= 5)
LogIncomingInDetail(request);
}
private void LogIncomingInDetail(OSHttpRequest request)
{
using (StreamReader reader = new StreamReader(Util.Copy(request.InputStream), Encoding.UTF8))
{
string output;
if (DebugLevel == 5)
{
const int sampleLength = 80;
char[] sampleChars = new char[sampleLength];
reader.Read(sampleChars, 0, sampleLength);
output = new string(sampleChars);
}
else
{
output = reader.ReadToEnd();
}
m_log.DebugFormat("[BASE HTTP SERVER]: {0}...", output.Replace("\n", @"\n"));
}
}
private bool TryGetStreamHandler(string handlerKey, out IRequestHandler streamHandler)
{
string bestMatch = null;
lock (m_streamHandlers)
{
foreach (string pattern in m_streamHandlers.Keys)
{
if (handlerKey.StartsWith(pattern))
{
if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length)
{
bestMatch = pattern;
}
}
}
if (String.IsNullOrEmpty(bestMatch))
{
streamHandler = null;
return false;
}
else
{
streamHandler = m_streamHandlers[bestMatch];
return true;
}
}
}
private bool TryGetHTTPHandler(string handlerKey, out GenericHTTPMethod HTTPHandler)
{
// m_log.DebugFormat("[BASE HTTP HANDLER]: Looking for HTTP handler for {0}", handlerKey);
string bestMatch = null;
lock (m_HTTPHandlers)
{
foreach (string pattern in m_HTTPHandlers.Keys)
{
if (handlerKey.StartsWith(pattern))
{
if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length)
{
bestMatch = pattern;
}
}
}
if (String.IsNullOrEmpty(bestMatch))
{
HTTPHandler = null;
return false;
}
else
{
HTTPHandler = m_HTTPHandlers[bestMatch];
return true;
}
}
}
/// <summary>
/// Try all the registered xmlrpc handlers when an xmlrpc request is received.
/// Sends back an XMLRPC unknown request response if no handler is registered for the requested method.
/// </summary>
/// <param name="request"></param>
/// <param name="response"></param>
private byte[] HandleXmlRpcRequests(OSHttpRequest request, OSHttpResponse response)
{
Stream requestStream = request.InputStream;
Encoding encoding = Encoding.UTF8;
StreamReader reader = new StreamReader(requestStream, encoding);
string requestBody = reader.ReadToEnd();
reader.Close();
requestStream.Close();
string responseString = String.Empty;
XmlRpcRequest xmlRprcRequest = null;
string methodName = null;
try
{
xmlRprcRequest = (XmlRpcRequest) (new XmlRpcRequestDeserializer()).Deserialize(requestBody);
methodName = xmlRprcRequest.MethodName;
}
catch (XmlException e)
{
if (DebugLevel >= 2)
{
m_log.Warn(
string.Format(
"[BASE HTTP SERVER]: Got XMLRPC request with invalid XML from {0}. XML was '{1}'. Sending 404 response. Exception ",
request.RemoteIPEndPoint, requestBody),
e);
}
else if (DebugLevel >= 1)
{
m_log.WarnFormat(
"[BASE HTTP SERVER]: Got XMLRPC request with invalid XML from {0}, length {1}. Sending 404 response.",
request.RemoteIPEndPoint, requestBody.Length);
}
}
if ((xmlRprcRequest == null) || (methodName == null))
{
//HandleLLSDRequests(request, response);
response.ContentType = "text/plain";
response.StatusCode = 404;
response.StatusDescription = "Not Found";
response.ProtocolVersion = new System.Version("1.0");
responseString = "Not found";
response.KeepAlive = false;
if (DebugLevel >= 1)
{
m_log.WarnFormat(
"[BASE HTTP SERVER]: Handler not found for http request {0} {1}",
request.HttpMethod, request.Url.PathAndQuery);
}
}
else
{
xmlRprcRequest.Params.Add(request.RemoteIPEndPoint); // Param[1]
XmlRpcResponse xmlRpcResponse;
XmlRpcMethod method;
bool methodWasFound;
bool keepAlive = false;
lock (m_rpcHandlers)
{
methodWasFound = m_rpcHandlers.TryGetValue(methodName, out method);
if (methodWasFound)
keepAlive = m_rpcHandlersKeepAlive[methodName];
}
if (methodWasFound)
{
xmlRprcRequest.Params.Add(request.Url); // Param[2]
string xff = "X-Forwarded-For";
string xfflower = xff.ToLower();
foreach (string s in request.Headers.AllKeys)
{
if (s != null && s.Equals(xfflower))
{
xff = xfflower;
break;
}
}
xmlRprcRequest.Params.Add(request.Headers.Get(xff)); // Param[3]
try
{
xmlRpcResponse = method(xmlRprcRequest, request.RemoteIPEndPoint);
}
catch(Exception e)
{
string errorMessage
= String.Format(
"Requested method [{0}] from {1} threw exception: {2} {3}",
methodName, request.RemoteIPEndPoint.Address, e.Message, e.StackTrace);
m_log.ErrorFormat("[BASE HTTP SERVER]: {0}", errorMessage);
// if the registered XmlRpc method threw an exception, we pass a fault-code along
xmlRpcResponse = new XmlRpcResponse();
// Code probably set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
xmlRpcResponse.SetFault(-32603, errorMessage);
}
// if the method wasn't found, we can't determine KeepAlive state anyway, so lets do it only here
response.KeepAlive = keepAlive;
}
else
{
xmlRpcResponse = new XmlRpcResponse();
// Code set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
xmlRpcResponse.SetFault(
XmlRpcErrorCodes.SERVER_ERROR_METHOD,
String.Format("Requested method [{0}] not found", methodName));
}
response.ContentType = "text/xml";
responseString = XmlRpcResponseSerializer.Singleton.Serialize(xmlRpcResponse);
}
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.LongLength;
response.ContentEncoding = Encoding.UTF8;
response.SendChunked = false;
return buffer;
}
private byte[] HandleLLSDRequests(OSHttpRequest request, OSHttpResponse response)
{
//m_log.Warn("[BASE HTTP SERVER]: We've figured out it's a LLSD Request");
Stream requestStream = request.InputStream;
Encoding encoding = Encoding.UTF8;
StreamReader reader = new StreamReader(requestStream, encoding);
string requestBody = reader.ReadToEnd();
reader.Close();
requestStream.Close();
//m_log.DebugFormat("[OGP]: {0}:{1}", request.RawUrl, requestBody);
// If they ask for it we'll use it.
response.KeepAlive = request.KeepAlive;
OSD llsdRequest = null;
OSD llsdResponse = null;
bool LegacyLLSDLoginLibOMV = (requestBody.Contains("passwd") && requestBody.Contains("mac") && requestBody.Contains("viewer_digest"));
if (String.IsNullOrEmpty(requestBody))
// Get Request
{
requestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><llsd><map><key>request</key><string>get</string></map></llsd>";
}
try
{
llsdRequest = OSDParser.Deserialize(requestBody);
}
catch (Exception ex)
{
m_log.Warn("[BASE HTTP SERVER]: Error - " + ex.Message);
}
if (llsdRequest != null)// && m_defaultLlsdHandler != null)
{
LLSDMethod llsdhandler = null;
if (TryGetLLSDHandler(request.RawUrl, out llsdhandler) && !LegacyLLSDLoginLibOMV)
{
// we found a registered llsd handler to service this request
llsdResponse = llsdhandler(request.RawUrl, llsdRequest, request.RemoteIPEndPoint);
}
else
{
// we didn't find a registered llsd handler to service this request
// Oops, no handler for this.. give em the failed message
llsdResponse = GenerateNoLLSDHandlerResponse();
}
}
else
{
llsdResponse = GenerateNoLLSDHandlerResponse();
}
byte[] buffer = new byte[0];
if (llsdResponse.ToString() == "shutdown404!")
{
response.ContentType = "text/plain";
response.StatusCode = 404;
response.StatusDescription = "Not Found";
response.ProtocolVersion = new System.Version("1.0");
buffer = Encoding.UTF8.GetBytes("Not found");
}
else
{
// Select an appropriate response format
buffer = BuildLLSDResponse(request, response, llsdResponse);
}
response.SendChunked = false;
response.ContentLength64 = buffer.Length;
response.ContentEncoding = Encoding.UTF8;
return buffer;
}
private byte[] BuildLLSDResponse(OSHttpRequest request, OSHttpResponse response, OSD llsdResponse)
{
if (request.AcceptTypes != null && request.AcceptTypes.Length > 0)
{
foreach (string strAccept in request.AcceptTypes)
{
switch (strAccept)
{
case "application/llsd+xml":
case "application/xml":
case "text/xml":
response.ContentType = strAccept;
return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
case "application/llsd+json":
case "application/json":
response.ContentType = strAccept;
return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
}
}