-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cs
More file actions
1331 lines (1214 loc) · 51.5 KB
/
Server.cs
File metadata and controls
1331 lines (1214 loc) · 51.5 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
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
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Author: Michael J. Froelich
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace FAP //Functional active pages , Functional programming And Pages, Free API Production, FAP seems like a good name!
{
/// <summary>
/// Server.
/// </summary>
public class Server
{
/* Constants */
//Have a maximum of this many connections possible, set at 21000 as of 1.0.9
const int SERVERWARM = 21000;
//When reading for headers, retry this amount of times before giving up and returning 444
//Unused in favour of using the timeout variable from the socket, throws an exception caught and then responded to with 444
//const int READRETRIES = 10000;
//If the connection count falls below this level, quickly make a lot more, set at 7000 as of 1.0.9 as it's the highest expected RPS
// const int SERVERCOOL = 700;
//Socket backlog, when initialising the socket for listening
const int SOCKETBACKLOG = 10000;
//This causes issues if set to anything greater or lesser (excluding 1.0)
const string HTTP = "HTTP/1.1 ";
//current FAP version,
const string VERSION = "1.1.2";
//Timeout for both send and receive
const int TIMEOUT = 32;
//Nagle no delay thing, leave as "true" for more efficient chunking
const bool NODELAY = true;
//Default value for CacheMaxAge, an hour, used to determine session variable timeout
const int CACHEMAXAGEDEFAULT = 3600000;
//Read buffer, best left between 1024 to 8192
const int READBUFFER = 8192;
//The only socket
Socket listener;
//the main listener, will be duplicated in later versions, perhaps for added speed
//Queue<TcpClient> incomming;
//The queue
Dictionary<string, Page> pagelist;
//Where all the pages are kept
//Dictionary<string, HashSet<int>> cache304;
//List<IAsyncResult> listenerlist; //This has... no way of actually workin
//bool ever = true;
/// <summary>
/// Returns whether the listening/timing loop is currently running
/// </summary>
/// <value><c>true</c> if this instance is running; otherwise, <c>false</c>.</value>
public bool IsRunning {
get { return listener != null && listener.IsBound; }
}
int port;
/// <summary>
/// Gets the application port, the setter was removed as it's no longer possible to reset the callbacks using the current connection method
/// </summary>
/// <value>The application port.</value>
public int Port {
get { return port; }
}
/// <summary>
/// Defines the method of replicating classes per instance, manual is fast, reflection copies everything, binary serialises it and then deserialises it
/// Custom requires that the CustomMethod function is defined
/// </summary>
public enum CloneMethod{
/// <summary>
/// The most performant way, but only ensures the 4 HTTP verbs
/// </summary>
Manual,
/// <summary>
/// Uses reflection, not as performant as binary but ensures most things get copied
/// </summary>
Reflection,
/// <summary>
/// Serialises/deserialises the class with BinaryFormatter, but requires everything is either attributed with [Serializable] or [NonSerialized]
/// </summary>
Binary,
/// <summary>
/// Relies on CustomMethod being defined or will revert to manual and print an error
/// </summary>
Custom
}
Page manualmethod(Page thispage, Page staticpage)
{
thispage.Path = staticpage.Path;
thispage.get = staticpage.get;
thispage.put = staticpage.put;
thispage.post = staticpage.post;
thispage.delete = staticpage.delete;
return thispage;
}
/// <summary>
/// Defines the custom method of replicating classes per instance, for instance for JSON.NET users:
/// CustomMethod = p => JToken.FromObject(p).DeepClone();
/// This function takes the static page and must return a cloned page. Do not return the static page.
/// </summary>
public Func<Page,Page> CustomMethod { get; set; }
/// <summary>
/// Defines the method of replicating Page objects, manual is fast and default, reflection copies everything, custom is however you like
/// </summary>
public CloneMethod Method { get; set; } = CloneMethod.Manual;
//Port to listen on
/// <summary>
/// Address to listen on
/// </summary>
/// <value>The address.</value>
IPAddress address;
/// <summary>
/// Gets the ip address, the setter was removed as it's no longer possible to reset the callbacks using the current connection method
/// </summary>
/// <value>The ip address.</value>
public IPAddress Address {
get { return address; }
}
/// <summary>
/// Changes the value of the query character, ie localhost/yourpage? where the query character here is '?'. Default is '?'.
/// </summary>
/// <value>The query character.</value>
public char QueryCharacter {
get;
set;
}
/// <summary>
/// Gets or sets the maximum age of a cached page, such that page instances will remain in memory for a maximum of this amount of time,
/// provided that the page is not accessed by a client user.
/// </summary>
/// <value>The page cache's max age in milliseconds. Default is an hour (3600000 milliseconds)</value>
public int CacheMaxAge {
get;
set;
}
/// <summary>
/// Gets or sets the Maximum Transmission Unit, used for determining whether to use chunked transfer encoding or not.
/// Note, if you're using this framework as intended (proxied through NGINX or Apache), your static webserver/proxy may chunk anyway.
/// </summary>
/// <value>The Maximum Transmission Unit.</value>
public int MTU {
get;
set;
}
/// <summary>
/// Adds a page, mostly
/// </summary>
/// <param name="p">Pages, single pages</param>
public void AddPage(Page p)
{
if (p != null) {
Page.SetStatic(p);
pagelist.Add(p.Path, p);
}
}
/// <summary>
/// Adds a list of pages
/// </summary>
/// <param name="inList">A list or array of pages through any container implementing IEnumerable.</param>
public void AddPage(IEnumerable<Page> inList)
{
foreach (Page p in inList)
if (p != null) {
Page.SetStatic(p);
pagelist.Add(p.Path, p);
}
}
/// <summary>
/// Removes a page, mostly
/// </summary>
/// <param name="p">Pages, single pages</param>
public void RemovePage(Page p)
{
if (p != null && pagelist.ContainsKey(p.Path))
pagelist.Remove(p.Path);
}
/// <summary>
/// Removes a list of pages
/// </summary>
/// <param name="inList">A list or array of pages through any container implementing IEnumerable.</param>
public void RemovePage(IEnumerable<Page> inList)
{
foreach (Page p in inList)
if (p != null && pagelist.ContainsKey(p.Path))
pagelist.Remove(p.Path);
}
/// <summary>
/// Clears all the pages, so you can reload a new list in.
/// </summary>
public void ClearPages()
{
pagelist.Clear();
}
/// <summary>
/// Stops the server
/// </summary>
public void Stop()
{
//ever = false;
listener.Close();
}
/// <summary>
/// Initializes a new instance of the <see cref="FAP.Server"/> class.
/// </summary>
/// <param name="inList">An IEnumerable of pages, try "Your data structure".Values</param>
/// <param name="IpAddress">IP address, likely the default: 127.0.0.1 (please use a static webserver in conjunction with FAP.net)</param>
/// <param name="port">Port or application port for a complete socket, default is 1024</param>
/// <param name="mtu">mtu or Maximum Transmission Unit is the maximum size of a tcp packet afterwhich chunking is used, set to below zero to disable chunking altogether</param>
public Server(IEnumerable<Page> inList = null, string IpAddress = "127.0.0.1", int port = 1024, int mtu = 65535)
{
pagelist = new Dictionary<string, Page>();
address = IPAddress.Parse(IpAddress);
this.port = port;
QueryCharacter = '?';
CacheMaxAge = CACHEMAXAGEDEFAULT; //About an hour 3600000
MTU = mtu; // Essentially the current MTU max
listener = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);//new TcpListener(Address, Port);
//cache304 = new Dictionary<string, HashSet<int>>();
listener.NoDelay = NODELAY;
listener.Bind(new IPEndPoint(address, port));
listener.Listen(SOCKETBACKLOG);
listener.ReceiveTimeout = TIMEOUT;
listener.SendTimeout = TIMEOUT;
if (inList != null)
foreach (Page p in inList)
if (p != null) {
Page.SetStatic(p);
pagelist.Add(p.Path, p);
}
LoadListeners();
//Task.Factory.StartNew(() => ResetListener()); //Calls LoadListeners
}
void LoadListeners()
{
//while (listenercount < SERVERWARM) //Calling the following code multiple times still provides a proven benefit through benchmarking
//{
for (int i = 0; i < SERVERWARM; i++) {
var ev = new SocketAsyncEventArgs();
ev.Completed += CallBack;
listener.AcceptAsync(ev);
}
//listener.BeginAccept(ListenerCallback, listener);
//}
}
void CallBack(object sender, SocketAsyncEventArgs eve)
{/*
try {*/
Parse(eve.AcceptSocket);
eve.AcceptSocket.Disconnect(false);
var ev = new SocketAsyncEventArgs();
ev.Completed += CallBack;
listener.AcceptAsync(ev);
eve.AcceptSocket.Close();
//If you close, you can't reuse SAEA even on .NET. If you don't close, you'l get a too many open files exception on mono
//If anyonee knows a solution, please contact me!
/*
} catch (Exception e) {
Console.Error.WriteLine("07: Connection error, " + e.Message);
}*/
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the <see cref="FAP.Server"/> is
/// reclaimed by garbage collection.
/// </summary>
~Server()
{
Stop();
}
async void Parse(Socket client)
{
//char input;
char method1 = '\0';
char method2 = '\0';
string code = "404"; //404 fail safe
string message = string.Empty;
string ipaddress = null;
string output = string.Empty;
string querystring = string.Empty;
string path = string.Empty;
string contenttype = string.Empty;
string headers = string.Empty;
string useragent = string.Empty;
string requestEtag = string.Empty;
//long contentlength = long.MinValue;
int currentHash = -1;
long outputbytelength = 0;
int hashsum;
long bytestowrite = 0;
byte[] fs = null;
string hashinfo = string.Empty;
bool isCacheable = false;
bool isGzip = false;
Encoding encoder = Encoding.UTF8; //Used to switch between UTF8 and BigEndianUnicode for a last ditch attempt at binary safety
Encoding inputencoder = Encoding.UTF8;
//bool isIE = false;
//HashSet<int> clientCache = null;
StringBuilder outputheaderbuilder = new StringBuilder();
StringBuilder inputheaderbuilder = new StringBuilder();
List<byte> utf8bytes = new List<byte>(); //Used for a whole number of times I read/write with utf8
List<byte> outputbytes = new List<byte>();//It's actually not easy to chunk without two...
Page thispage;
Page staticpage;
//client.NoDelay = NODELAY; //This is actually pointless after the connection has been opened, set on the TcpListener.Server instead
/*if (!client.Poll(1000, SelectMode.SelectRead))
return;*/
try {
#region inputparser
byte[] bytesreceived = new byte[READBUFFER]; //whilst assigning data is expensive, I changed this code with the assumption that system calls are more expensive. See my blog
long bytestoread = 0;
string header;
int seek = 0;
while (true) {
while ((bytestoread = client.Available) <= 0) {
} //The idea behind polling, instead of grabbing all data through async methods, is to process headers whilst data is still being received
if (bytestoread > READBUFFER)
bytestoread = READBUFFER;
client.Receive(bytesreceived, (int)bytestoread, 0);
//retryread = 0;
for (seek = 0; seek < bytestoread; seek++) {
if (bytesreceived[seek] == '\n') {
header = Encoding.UTF8.GetString(utf8bytes.ToArray());//header = builder.ToString();
switch (header[0]) {
case 'H':
case 'G':
case 'P':
case 'D':
if (method1 == '\0') { //First line condition
method1 = header[0];
method2 = header[1];
var spaceindex = header.LastIndexOf(' ');
var pagefinderindex = header.IndexOf('/') + 1;
var querycharacterindex = header.IndexOf(QueryCharacter, pagefinderindex) + 1;
if (querycharacterindex > 1 && querycharacterindex <= spaceindex) { //incase the query character is 'H', 'T', 'P', '1', '2', '.', or '/'
path = header.Substring(pagefinderindex, querycharacterindex - pagefinderindex - 1);
querystring = header.Substring(querycharacterindex, spaceindex - querycharacterindex);
} else { //For no query string queries, such as page requests for FAP.React or blank queries from NGINX (which will drop the querycharacter)
querycharacterindex = header.IndexOf(' ', pagefinderindex) + 1; //query character becomes ' '
path = header.Substring(pagefinderindex, querycharacterindex - pagefinderindex - 1);
}
//header = header.Substring(spaceindex + 1, (header.Length - spaceindex) - 1); //Gets the HTTP version
}
break;
case 'C': //Content-Length might not be possible
if (header.StartsWith("Content-Type", StringComparison.Ordinal)) {
const string CHARSET = "charset=";
int contentbegin = header.IndexOf(CHARSET);
if(contentbegin > 0) {
inputencoder = Encoding.GetEncoding(header.Substring(contentbegin + CHARSET.Length));
}
if(header.Contains("image") || header.Contains("audio")) { //Override if charset was also given
inputencoder = Encoding.BigEndianUnicode; //These need the BigEndian hack
}
}
break;
case 'I':
const string IFNONEMATCH = "If-None-Match";
if (header.StartsWith(IFNONEMATCH, StringComparison.Ordinal)) {
requestEtag = header.Substring(header.IndexOf("\"") + 1, 8);
}
break;
case 'U':
const string USERAGENT = "User-Agent";
if (header.StartsWith(USERAGENT, StringComparison.Ordinal)) {
useragent = header.Substring(12, header.Length - 12 - 1);
}
break;
case 'X':
const string XFORWARDEDFOR = "X-Forwarded-For";
const string XREALIP = "X-Real-IP";
if (header.StartsWith(XFORWARDEDFOR, StringComparison.Ordinal)) {
var endcr = header.IndexOf('\r');
var endco = header.IndexOf(',');
if (endco > 0)
ipaddress = header.Substring(17, endco - 17);
else
ipaddress = header.Substring(17, endcr - 17);
} else if (header.StartsWith(XREALIP, StringComparison.Ordinal)) {
var endcr = header.IndexOf('\r');
var endco = header.IndexOf(',');
if (endco > 0)
ipaddress = header.Substring(11, endco - 11);
else
ipaddress = header.Substring(11, endcr - 11);
}
hashinfo += header; //generally, any X- header has enough logic to uniquely identify clients
break;
}
inputheaderbuilder.Append(header); //No matter what, append the header
inputheaderbuilder.Append('\n');
utf8bytes.Clear();//builder.Clear();
if (bytesreceived[seek + 1] == '\r') {
goto HeadersDone; //It's just more efficient...
}
} else
utf8bytes.Add(bytesreceived[seek]);//builder.Append((char)bytesreceived[seek]);
}
}
HeadersDone:
headers = inputheaderbuilder.ToString();
if (ipaddress == null) { //Next best guess for the ip address
ipaddress = hashinfo = (((IPEndPoint)client.RemoteEndPoint).Address.ToString());
}
if (bytestoread >= seek + 3) {
byte[] messagestart = new byte[bytestoread - (seek + 3)];
Array.Copy(bytesreceived, seek + 3, messagestart, 0, bytestoread - (seek + 3));
utf8bytes.AddRange(messagestart);
}
while ((bytestoread = client.Available) > 0) { //By this time, all the data has been received so we can just expect to read all
if (bytestoread > READBUFFER)
bytestoread = READBUFFER;
if (bytestoread != bytesreceived.Length)
bytesreceived = new byte[bytestoread];
client.Receive(bytesreceived, (int)bytestoread, 0);
utf8bytes.AddRange(bytesreceived);
}
message = inputencoder.GetString(utf8bytes.ToArray());
#endregion
#region PageProcessor
if (querystring.Length > MTU && MTU > 0) {
code = "414"; //If the query string turns out to be greater than the MTU, generate an URI too big error
headers = string.Empty; //Necessary, as otherwise the framework will append the request headers on error
} else if (headers.Length > MTU && MTU > 0) {
code = "431"; //If the query string turns out to be greater than the MTU, generate an URI too big error
headers = string.Empty;
} else if (!string.IsNullOrEmpty(path) && pagelist.TryGetValue(path, out staticpage)) {
//thispage = (Page)Activator.CreateInstance(staticpage.GetType());
hashsum = hashinfo.GetHashCode() + useragent.GetHashCode();
if (!staticpage.PageCache.TryGetValue(hashsum, out thispage)) {
var type = staticpage.GetType();
thispage = (Page)Activator.CreateInstance(type);
switch(Method) {
case CloneMethod.Manual:
thispage = manualmethod(thispage,staticpage);
thispage.UserIP = ipaddress;
thispage.UserAgent = useragent;
break;
case CloneMethod.Custom:
if (CustomMethod == null) {
Console.Error.WriteLine("08: Custom clone method exception, method appears undefined");
thispage = manualmethod(thispage, staticpage);
}
else
thispage = CustomMethod(staticpage);
thispage.UserIP = ipaddress; //Somethings FAP really needs
thispage.UserAgent = useragent;
break;
case CloneMethod.Reflection:
var fields = type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
foreach (var field in fields) { //This is a pure sacrifice of efficiency
var value = field.GetValue(staticpage); //Objects with millions of public members can bottleneck here
if(value != null)
field.SetValue(thispage, value);
} //As always, the old ways are left for some may feel they are better
break;
case CloneMethod.Binary:
Page newpage;
try {
using (var s = new System.IO.MemoryStream()) {
var serialiser = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
serialiser.Serialize(s, staticpage);
s.Position = 0;
newpage = serialiser.Deserialize(s) as Page;
}
}
catch (Exception e) {
Console.Error.WriteLine("09: Binary clone method exception, are you missing a [Serializable] attribute?]. Message:\n" + e.Message);
newpage = null;
}
if (newpage != null)
thispage = newpage;
else {
thispage = manualmethod(thispage, staticpage);
thispage.UserIP = ipaddress;
thispage.UserAgent = useragent;
}
break;
}
Task.Factory.StartNew(() => cacheAdd(hashsum, thispage, staticpage)); //Add it to the page cache in case the visitor returns
}
thispage.isstatic = false;
staticpage.lastpage = thispage; //Allows setting the header from a static class
thispage.Headers = headers; //this is assured to always need an update
//For functionals
staticpage.Headers = headers;
staticpage.UserIP = ipaddress;
staticpage.UserAgent = useragent;
thispage.StaticParent = staticpage;
switch (method1) {
case 'H': //Head
case 'G': //Get
{ //"HEAD" is identical to "GET", except no content is generated, this is ensured later
isCacheable = true;
output = await Task.FromResult<string>(thispage.Get(querystring, message));
if (thispage.GetFile != null) {//only 64 bytes are used for hashing.. it's from both ends at least
fs = thispage.GetFile;//also, processing short strings is faster than processing longs strings
utf8bytes = new List<byte>(fs);//files are potentially upwards of 3mb whereas web pages are rarely over 800kb
if (utf8bytes.Count > 31) { //this is intended to allow HTTP codes before binary data
output += Encoding.BigEndianUnicode.GetString(utf8bytes.GetRange(0, 32).ToArray());//utf8bytes is reused later
output += Encoding.BigEndianUnicode.GetString(utf8bytes.GetRange(fs.Length - 32, 32).ToArray());
}
else
output += Encoding.BigEndianUnicode.GetString(utf8bytes.ToArray());
thispage.GetFile = null; //for the next user...
}
currentHash = hashsum + querystring.GetHashCode() + output.GetHashCode(); //your file might be massive
//Tested with a C# stopwatch, performing GetHashCode multiple times is indeed A LOT faster than concatenation, please ignore the integer overflows behind the curtain
if (requestEtag == String.Format("{0:x8}", currentHash)) //String.Format is slightly faster than int.Parse
code = "304";
}
break;
case 'P':
{
if (method2 == 'U' || method2 == 'u')
output = await Task.FromResult<string>(thispage.Put(querystring, message));
else if (method2 == 'O' || method2 == 'o')
{
output = await Task.FromResult<string>(thispage.PostFile(querystring, utf8bytes));
if(output == null)
output = await Task.FromResult<string>(thispage.Post(querystring, message));
}
break;
}
case 'D':
{
output = await Task.FromResult<string>(thispage.Delete(querystring, message));
break;
}
default:
code = "501";
break;
}
if (headers == thispage.Headers)
headers = string.Empty;
else {
const string contenttypeheader = "content-type:";
headers = "\r\n" + thispage.Headers; //Ensures at least one new line and prevents a concatenation later on
foreach (string s in headers.Split('\n')) { //This has about a 50-100ns bottleneck, solution: forget about headers
if (s.ToLower().StartsWith(contenttypeheader)) {
contenttype = s.Substring(contenttypeheader.Length);
contenttype.Replace("\r", null); //Remove the possible carriage return character
contenttype.Replace("\n", null); //Remove the possible new line character
headers.Replace(s + '\n', null); //Remove the entire content type line from the headers (or else there'll be double)
int startencoding;
if ((startencoding = contenttype.IndexOf('=')) > 0) {
encoder = Encoding.GetEncoding(contenttype.Substring(startencoding + 1));
}
int endrealcontenttype = contenttype.IndexOf(';');
if (endrealcontenttype > 0)
contenttype = contenttype.Substring(0, endrealcontenttype);
}
}
}
if (!string.IsNullOrEmpty(thispage.Code)) {
code = thispage.Code;
}
} else
headers = string.Empty;
#endregion PageProcessor
#region outputparse
if (code != "304" && !string.IsNullOrEmpty(output)) { //If we haven't generated a 304 or a nothing response
if (code == "404") {
code = "200"; //Begin code as 200 for default success, but now include user HTTP codes
if (output.Length >= 5 && //Using the string length, not UTF8 length here as we're doing string operations
char.IsDigit(output[0]) && //If the first three characters are digits
char.IsDigit(output[1]) &&
char.IsDigit(output[2]) &&
output[3] == '\r' && //If these three digits end with a line breaker
output[4] == '\n') {
code = output.Substring(0, 3); //Then we have the code
output = (output.Length > 5) ? output.Remove(0, 5) : string.Empty; //And we can remove it from the output
}
}
if (fs != null) {
outputbytelength = fs.LongLength; //this is why it's a byte[] in the Page API... I need the length in long
}
else {
var oldoutputbytes = encoder.GetBytes(output);
outputbytelength = oldoutputbytes.LongLength; //the golden length against.. what are you doing that's producing over 2GB of script?
outputbytes = new List<byte>(oldoutputbytes); //This has to be done anyway
}
if (contenttype == string.Empty) { //If the contenttype is undefined
contenttype = "text/plain"; //Fail safe with text/plain
if (output.Length >= 2) { //If we have the bytes to sniff for a content type
var bytes = Encoding.ASCII.GetBytes(output.ToCharArray(0, 2)); //No longer using unicode, in fact ASCII does seem correct...
//If length of the resultant output is greater MTU OR the first two bytes indicate some sort of GZIP/ZIP encoding
isGzip = ((bytes[0] == (char)0x1f) && (bytes[1] == (char)0x8b || bytes[1] == (char)0x3f)); //Gzip is NOT a mime type
switch (output[0]) { //mime/content type handling
case (char)0:
{
if (output.Length > 3) { //Throughout this entire if block it's performing string manipuation, therefore output.Lenght is needed
if (output[0] == (char)0 && output[1] == (char)0 && output[2] == (char)1) {
contenttype = "image/x-icon";
encoder = Encoding.BigEndianUnicode; //Seems to create binary compatibility
} //Headers are still encoded using UTF8
if (output.Length > 9 && "ftyp" == output.Substring(4, 4)) {
contenttype = "video/mp4";
encoder = Encoding.BigEndianUnicode;
}
}
break;
}
case '[':
{
if (output[output.Length - 1] == ']') //output.Length != length, length is for writing only
contenttype = "application/json"; //As always, this framework promotes the use of JSON over CSV or XML or null terminated strings
break;
}
case '{'://0x7b
{
if (output[output.Length - 1] == '}')
contenttype = "application/json";
break;
}
case '<'://0x3c
{
if (output[output.Length - 1] == '>') {
if (output.Length > 3 && output[2] == 'x') { //<?xm
contenttype = "text/xml";
} else
contenttype = "text/html";
}
break;
}
case '%'://0x25
{
if (output.Length > 4 && (output.Substring(1, 3) == "PDF")) {
contenttype = "application/pdf"; //
encoder = Encoding.BigEndianUnicode;
}
break;
}
case (char)0x42:
{
if (output[1] == (char)0x4D) {
contenttype = "image/bmp";
encoder = Encoding.BigEndianUnicode;
}
break;
}
case (char)0x47:
{
if (output[1] == (char)0x49) {
contenttype = "image/gif";
encoder = Encoding.BigEndianUnicode;
}
break;
}
case (char)0x49:
{
if (output[1] == (char)0x44) {
contenttype = "audio/mpeg";
encoder = Encoding.BigEndianUnicode;
}
break;
}
case (char)0x4d:
{
if (output[1] == (char)0x54) {
contenttype = "audio/midi";
encoder = Encoding.BigEndianUnicode;
}
break;
}
case (char)0x4f:
{
if (output[1] == (char)0x67) {
contenttype = "audio/ogg";
encoder = Encoding.BigEndianUnicode;
}
break;
}
case (char)0x66:
{
if (output[1] == (char)0xfc) {
contenttype = "audio/flac";
encoder = Encoding.BigEndianUnicode;
}
break;
}
case (char)0x89:
{
if (output[1] == (char)0x50) {
contenttype = "image/png";
encoder = Encoding.BigEndianUnicode;
}
break;
}
case (char)0xff: //It's unlikely these work, as it's unlikely BigEndianUnicode is truly binary safe... but one can dream
{
if (output[1] == (char)0xd8) {
contenttype = "image/jpeg";
encoder = Encoding.BigEndianUnicode;
} else if (output[1] == (char)0xfb) {
contenttype = "audio/mpeg";
encoder = Encoding.BigEndianUnicode;
}
break;
}
default:
if (isGzip) {
contenttype = "application/x-gzip"; //Send this type if Gziped
encoder = Encoding.BigEndianUnicode;
}
break;
}
}
}
if (fs != null) {
if (contenttype == "text/plain") {
contenttype = "application/octet-stream"; //This is more appropriate if unknown binary data is sent
}
}
} else
outputbytelength = 0;
#endregion outputparse
#region httpcodeparser
switch (code[0]) {
case '1':
{
#region 1xx
switch (code[1]) {
case '0':
outputbytelength = 0;
outputheaderbuilder.Append(HTTP + H.S100 + headers + "\r\n\r\n");
break;
case '1':
outputbytelength = 0;
outputheaderbuilder.Append(HTTP + H.S101 + headers + "\r\n\r\n");
break;
case '2':
outputbytelength = 0;
outputheaderbuilder.Append(HTTP + H.S102 + headers + "\r\n\r\n");
break;
default:
outputbytelength = 0;
outputheaderbuilder.Append(HTTP + H.S1xx + headers + "\r\n\r\n");
break;
}
break;
#endregion
}
case '2':
{
#region 2xx
switch (code[2]) {
case '0':
outputheaderbuilder.Append(HTTP + H.S200);
break;
case '1':
outputheaderbuilder.Append(HTTP + H.S201);
break;
case '2':
outputheaderbuilder.Append(HTTP + H.S202);
break;
case '3':
outputheaderbuilder.Append(HTTP + H.S203);
break;
case '4':
outputbytelength = 0; //204 does not generate content
outputheaderbuilder.Append(HTTP + H.S204);
break;
case '5':
outputheaderbuilder.Append(HTTP + H.S205);
break;
case '6':
outputheaderbuilder.Append(HTTP + H.S206);
break;
default:
outputheaderbuilder.Append(HTTP + code);
break;
}
outputheaderbuilder.Append(String.Format(
"\r\nServer: FAP.NET {0} Codename: Meisscanne\r\n" +
"Date: {1}\r\n" +
"Connection: keep-alive\r\n{2}{3}" +
"Cache-Control: private, max-age=0, must-revalidate\r\n" +
"{4}",
VERSION,
DateTime.UtcNow.ToString("R"),
(outputbytelength > 0 || MTU < 0 ? "Content-type: " + contenttype + "; charset=" + encoder.WebName + "\r\n" : string.Empty),
(headers.Length > 0 ? headers.Substring(2) + "\r\n" : string.Empty),
//CacheMaxAge + (isIE ? string.Empty : ", no-cache"),
(isCacheable ? "Etag: \"" + String.Format("{0:x8}", currentHash) + "\"\r\n" : string.Empty)
));
if (isGzip) {
outputheaderbuilder.Append("Content-Encoding: gzip\r\nTransfer-Encoding: Chunked\r\n\r\n");
} else {
if (outputbytelength < MTU || MTU < 0) {
outputheaderbuilder.Append("Content-Length: " + outputbytelength + "\r\n\r\n");
} else
outputheaderbuilder.Append("Transfer-Encoding: Chunked\r\n\r\n");
}
break;
#endregion 2xx
}
case '3':
{
#region 3xx
switch (code[2]) {
case '0':
outputheaderbuilder.Append(HTTP + H.R300 + headers + "\r\n\r\n");
break;
case '1':
outputheaderbuilder.Append(HTTP + H.R301 + headers + "\r\n\r\n");
break;
case '2':
outputheaderbuilder.Append(HTTP + H.R302 + headers + "\r\n\r\n");
break;
case '3':
outputheaderbuilder.Append(HTTP + H.R303 + headers + "\r\n\r\n");
break;
case '4':
outputbytelength = 0;
outputheaderbuilder.Append(HTTP + H.R304 + String.Format("\r\n" +
"Server: FAP.NET {0} Codename: Meisscanne\r\n" +
"Date: {1}\r\n" +
"Connection: keep-alive\r\n" +
"Cache-control: private, max-age=0, must-revalidate\r\n" +
"Etag: \"{2}\"\r\n\r\n",
VERSION,
DateTime.UtcNow.ToString("R"),
//CacheMaxAge + (isIE ? string.Empty : ", no-cache"),
String.Format("{0:x8}", currentHash)));
break;
case '5':
outputheaderbuilder.Append(HTTP + H.R305 + headers + "\r\n\r\n");
break;
case '6':
outputheaderbuilder.Append(HTTP + H.R306 + headers + "\r\n\r\n");
break;
case '7':
outputheaderbuilder.Append(HTTP + H.R307 + headers + "\r\n\r\n");
break;
case '8':
outputheaderbuilder.Append(HTTP + H.R308 + headers + "\r\n\r\n");
break;
default:
outputheaderbuilder.Append(HTTP + code + headers + "\r\n\r\n");
break;
}
break;
#endregion 3xx
}
case '4':
{
#region 4xx
switch (code[1]) {
case '0':
switch (code[2]) {
case '0':
outputheaderbuilder.Append(HTTP + H.E400 + headers + "\r\n\r\n");
break;
case '1':
outputheaderbuilder.Append(HTTP + H.E401 + headers + "\r\n\r\n");
break;
case '2':
outputheaderbuilder.Append(HTTP + H.E402 + headers + "\r\n\r\n");
break;
case '3':
outputheaderbuilder.Append(HTTP + H.E403 + headers + "\r\n\r\n");
break;
case '4':
outputheaderbuilder.Append(HTTP + H.E404 + headers + "\r\n\r\n");
break;
case '5':
outputheaderbuilder.Append(HTTP + H.E405 + headers + "\r\n\r\n");
break;
case '6':
outputheaderbuilder.Append(HTTP + H.E406 + headers + "\r\n\r\n");
break;
case '7':
outputheaderbuilder.Append(HTTP + H.E407 + headers + "\r\n\r\n");
break;
case '8':
outputheaderbuilder.Append(HTTP + H.E408 + headers + "\r\n\r\n");
break;
case '9':
outputheaderbuilder.Append(HTTP + H.E409 + headers + "\r\n\r\n");
break;
default:
outputheaderbuilder.Append(HTTP + H.E404 + headers + "\r\n\r\n");
break;
}
break;
case '1':
switch (code[2]) {
case '0':
outputheaderbuilder.Append(HTTP + H.E410 + headers + "\r\n\r\n");
break;
case '1':
outputheaderbuilder.Append(HTTP + H.E411 + headers + "\r\n\r\n");
break;
case '2':
outputheaderbuilder.Append(HTTP + H.E412 + headers + "\r\n\r\n");
break;
case '3':
outputheaderbuilder.Append(HTTP + H.E413 + headers + "\r\n\r\n");
break;
case '4':
outputheaderbuilder.Append(HTTP + H.E414 + headers + "\r\n\r\n");
break;
case '5':
outputheaderbuilder.Append(HTTP + H.E415 + headers + "\r\n\r\n");
break;
case '6':
outputheaderbuilder.Append(HTTP + H.E416 + headers + "\r\n\r\n");
break;