-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathWebServer.m
3665 lines (3283 loc) · 85.1 KB
/
WebServer.m
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) 2004 Free Software Foundation, Inc.
Written by: Richard Frith-Macdonald <[email protected]>
Date: June 2004
This file is part of the WebServer Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
$Date$ $Revision$
*/
#import <Foundation/Foundation.h>
#import <Performance/GSThreadPool.h>
#define WEBSERVERINTERNAL 1
#import "WebServer.h"
#import "Internal.h"
#define MAXCONNECTIONS 10000
static Class NSArrayClass = Nil;
static Class NSDataClass = Nil;
static Class NSDateClass = Nil;
static Class NSDictionaryClass = Nil;
static Class NSMutableArrayClass = Nil;
static Class NSMutableDataClass = Nil;
static Class NSMutableDictionaryClass = Nil;
static Class NSMutableStringClass = Nil;
static Class NSStringClass = Nil;
static Class GSMimeDocumentClass = Nil;
static Class WebServerHeaderClass = Nil;
static Class WebServerResponseClass = Nil;
static NSZone *defaultMallocZone = 0;
static NSSet *defaultPermittedMethods = nil;
#define Alloc(X) [(X) allocWithZone: defaultMallocZone]
static void
untrusted(WebServerRequest *request, NSString *key, NSMutableArray **array)
{
if (nil != [[request headerNamed: key] value])
{
if (nil == *array)
{
*array = [NSMutableArray array];
}
[*array addObject: key];
[request deleteHeaderNamed: key];
}
}
@implementation WebServer
+ (void) initialize
{
if (NSDataClass == Nil)
{
static id m[2] = { @"GET", @"POST" };
defaultMallocZone = NSDefaultMallocZone();
NSStringClass = [NSString class];
NSArrayClass = [NSArray class];
NSDataClass = [NSData class];
NSDateClass = [NSDate class];
NSDictionaryClass = [NSDictionary class];
NSMutableArrayClass = [NSMutableArray class];
NSMutableDataClass = [NSMutableData class];
NSMutableDictionaryClass = [NSMutableDictionary class];
NSMutableStringClass = [NSMutableString class];
GSMimeDocumentClass = [GSMimeDocument class];
WebServerHeaderClass = [WebServerHeader class];
WebServerResponseClass = [WebServerResponse class];
defaultPermittedMethods = [[NSSet alloc] initWithObjects: m count: 2];
}
}
static NSUInteger
unescapeData(const uint8_t *bytes, NSUInteger length, uint8_t *buf)
{
NSUInteger to = 0;
NSUInteger from = 0;
while (from < length)
{
uint8_t c = bytes[from++];
if (c == '+')
{
c = ' ';
}
else if (c == '%' && from < length - 1)
{
uint8_t tmp;
tmp = bytes[from++];
if (tmp <= '9' && tmp >= '0')
{
c = tmp - '0';
}
else if (tmp <= 'F' && tmp >= 'A')
{
c = tmp + 10 - 'A';
}
else if (tmp <= 'f' && tmp >= 'a')
{
c = tmp + 10 - 'a';
}
else
{
c = 0;
}
c <<= 4;
tmp = bytes[from++];
if (tmp <= '9' && tmp >= '0')
{
c += tmp - '0';
}
else if (tmp <= 'F' && tmp >= 'A')
{
c += tmp + 10 - 'A';
}
else if (tmp <= 'f' && tmp >= 'a')
{
c += tmp + 10 - 'a';
}
else
{
c = 0;
}
}
buf[to++] = c;
}
return to;
}
+ (NSURL*) baseURLForRequest: (WebServerRequest*)request
{
NSString *host = [request address];
NSString *scheme = [[request headerNamed: @"x-http-scheme"] value];
NSString *path = [[request headerNamed: @"x-http-path"] value];
NSString *query = [[request headerNamed: @"x-http-query"] value];
NSString *str;
NSURL *url;
if (nil == host)
{
host = [[request headerNamed: @"host"] value];
}
/* An HTTP/1.1 request MUST contain the host header, but older requests
* may not ... in which case we have to use our local IP address and port.
*/
if ([host length] == 0)
{
host = [NSString stringWithFormat: @"%@:%@",
[[request headerNamed: @"x-local-address"] value],
[[request headerNamed: @"x-local-port"] value]];
}
if ([query length] > 0)
{
str = [NSString stringWithFormat: @"%@://%@%@?%@",
scheme, host, path, query];
}
else
{
str = [NSString stringWithFormat: @"%@://%@%@", scheme, host, path];
}
url = [NSURL URLWithString: str];
return url;
}
+ (NSUInteger) decodeURLEncodedForm: (NSData*)data
into: (NSMutableDictionary*)dict
{
const uint8_t *bytes = (const uint8_t *)[data bytes];
NSUInteger length = [data length];
NSUInteger pos = 0;
NSUInteger fields = 0;
while (pos < length)
{
NSUInteger keyStart = pos;
NSUInteger keyEnd;
NSUInteger valStart;
NSUInteger valEnd;
uint8_t *buf;
NSUInteger buflen;
BOOL escape = NO;
NSData *d;
NSString *k;
NSMutableArray *a;
while (pos < length && bytes[pos] != '&')
{
pos++;
}
valEnd = pos;
if (pos < length)
{
pos++; // Step past '&'
}
keyEnd = keyStart;
while (keyEnd < pos && bytes[keyEnd] != '=')
{
if (bytes[keyEnd] == '%' || bytes[keyEnd] == '+')
{
escape = YES;
}
keyEnd++;
}
if (escape)
{
buf = NSZoneMalloc(NSDefaultMallocZone(), keyEnd - keyStart);
buflen = unescapeData(&bytes[keyStart], keyEnd - keyStart, buf);
d = [Alloc(NSDataClass) initWithBytesNoCopy: buf
length: buflen
freeWhenDone: YES];
}
else
{
d = [Alloc(NSDataClass) initWithBytesNoCopy: (void*)&bytes[keyStart]
length: keyEnd - keyStart
freeWhenDone: NO];
}
k = [Alloc(NSStringClass) initWithData: d
encoding: NSUTF8StringEncoding];
if (k == nil)
{
[NSException raise: NSInvalidArgumentException
format: @"Bad UTF-8 form data (key of field %"PRIuPTR")",
fields];
}
RELEASE(d);
valStart = keyEnd;
if (valStart < pos)
{
valStart++; // Step past '='
}
if (valStart < valEnd)
{
buf = NSZoneMalloc(NSDefaultMallocZone(), valEnd - valStart);
buflen = unescapeData(&bytes[valStart], valEnd - valStart, buf);
d = [Alloc(NSDataClass) initWithBytesNoCopy: buf
length: buflen
freeWhenDone: YES];
}
else
{
d = [NSDataClass new];
}
a = [dict objectForKey: k];
if (a == nil)
{
a = [Alloc(NSMutableArrayClass) initWithCapacity: 1];
[dict setObject: a forKey: k];
RELEASE(a);
}
[a addObject: d];
RELEASE(d);
RELEASE(k);
fields++;
}
return fields;
}
static NSMutableData*
escapeData(const uint8_t *bytes, NSUInteger length, NSMutableData *d)
{
uint8_t *dst;
NSUInteger spos = 0;
NSUInteger dpos = [d length];
/* RFC3986 says that alphanumeric, hyphen, dot, underscore and tilde
* are the only characters that should not be escaped in a URL.
*/
[d setLength: dpos + 3 * length];
dst = (uint8_t *)[d mutableBytes];
while (spos < length)
{
uint8_t c = bytes[spos++];
if (isalnum(c) || '-' == c || '.' == c || '_' == c || '~' == c)
{
dst[dpos++] = c;
}
else
{
uint8_t hi;
uint8_t lo;
dst[dpos++] = '%';
hi = (c & 0xf0) >> 4;
dst[dpos++] = (hi > 9) ? 'A' + hi - 10 : '0' + hi;
lo = (c & 0x0f);
dst[dpos++] = (lo > 9) ? 'A' + lo - 10 : '0' + lo;
}
}
[d setLength: dpos];
return d;
}
+ (NSUInteger) encodeURLEncodedForm: (NSDictionary*)dict
charset: (NSString*)charset
into: (NSMutableData*)data
{
CREATE_AUTORELEASE_POOL(arp);
NSEnumerator *keyEnumerator;
NSStringEncoding enc;
id key;
NSUInteger valueCount = 0;
NSMutableData *md = [NSMutableDataClass dataWithCapacity: 100];
if (nil == charset)
{
enc = NSUTF8StringEncoding;
}
else
{
enc = [GSMimeDocument encodingFromCharset: charset];
if (GSUndefinedEncoding == enc)
{
enc = NSUTF8StringEncoding;
}
}
keyEnumerator = [dict keyEnumerator];
while ((key = [keyEnumerator nextObject]) != nil)
{
id values = [dict objectForKey: key];
NSData *keyData;
NSEnumerator *valueEnumerator;
id value;
if ([key isKindOfClass: NSDataClass])
{
keyData = key;
}
else
{
key = [key description];
keyData = [key dataUsingEncoding: enc];
if (nil == keyData)
{
keyData = [key dataUsingEncoding: NSUTF8StringEncoding];
}
}
[md setLength: 0];
escapeData([keyData bytes], [keyData length], md);
keyData = md;
if ([values isKindOfClass: NSArrayClass] == NO)
{
values = [NSArrayClass arrayWithObject: values];
}
valueEnumerator = [values objectEnumerator];
while ((value = [valueEnumerator nextObject]) != nil)
{
NSData *valueData;
if ([data length] > 0)
{
[data appendBytes: "&" length: 1];
}
[data appendData: keyData];
[data appendBytes: "=" length: 1];
if ([value isKindOfClass: NSDataClass])
{
valueData = value;
}
else
{
value = [value description];
valueData = [value dataUsingEncoding: enc];
if (nil == valueData)
{
valueData = [value dataUsingEncoding: NSUTF8StringEncoding];
}
}
escapeData([valueData bytes], [valueData length], data);
valueCount++;
}
}
RELEASE(arp);
return valueCount;
}
+ (NSUInteger) encodeURLEncodedForm: (NSDictionary*)dict
into: (NSMutableData*)data
{
return [self encodeURLEncodedForm: dict
charset: nil
into: data];
}
+ (NSString*) escapeHTML: (NSString*)str
{
NSUInteger length = [str length];
NSUInteger output = 0;
unichar *from;
NSUInteger i = 0;
BOOL escape = NO;
if (length == 0)
{
return str;
}
from = NSZoneMalloc (NSDefaultMallocZone(), sizeof(unichar) * length);
[str getCharacters: from];
for (i = 0; i < length; i++)
{
unichar c = from[i];
if ((c >= 0x20 && c <= 0xd7ff)
|| c == 0x9 || c == 0xd || c == 0xa
|| (c >= 0xe000 && c <= 0xfffd))
{
switch (c)
{
case '"':
case '\'':
output += 6;
escape = YES;
break;
case '&':
output += 5;
escape = YES;
break;
case '<':
case '>':
output += 4;
escape = YES;
break;
default:
/*
* For non-ascii characters, we can use &#nnnn; escapes
*/
if (c > 127)
{
output += 5;
while (c >= 1000)
{
output++;
c /= 10;
}
escape = YES;
}
output++;
break;
}
}
else
{
escape = YES; // Need to remove bad characters
}
}
if (escape)
{
unichar *to;
NSUInteger j = 0;
to = NSZoneMalloc (NSDefaultMallocZone(), sizeof(unichar) * output);
for (i = 0; i < length; i++)
{
unichar c = from[i];
if ((c >= 0x20 && c <= 0xd7ff)
|| c == 0x9 || c == 0xd || c == 0xa
|| (c >= 0xe000 && c <= 0xfffd))
{
switch (c)
{
case '"':
to[j++] = '&';
to[j++] = 'q';
to[j++] = 'u';
to[j++] = 'o';
to[j++] = 't';
to[j++] = ';';
break;
case '\'':
to[j++] = '&';
to[j++] = 'a';
to[j++] = 'p';
to[j++] = 'o';
to[j++] = 's';
to[j++] = ';';
break;
case '&':
to[j++] = '&';
to[j++] = 'a';
to[j++] = 'm';
to[j++] = 'p';
to[j++] = ';';
break;
case '<':
to[j++] = '&';
to[j++] = 'l';
to[j++] = 't';
to[j++] = ';';
break;
case '>':
to[j++] = '&';
to[j++] = 'g';
to[j++] = 't';
to[j++] = ';';
break;
default:
if (c > 127)
{
char buf[12];
char *ptr = buf;
to[j++] = '&';
to[j++] = '#';
sprintf(buf, "%u", c);
while (*ptr != '\0')
{
to[j++] = *ptr++;
}
to[j++] = ';';
}
else
{
to[j++] = c;
}
break;
}
}
}
str = [[NSString alloc] initWithCharacters: to length: output];
NSZoneFree (NSDefaultMallocZone (), to);
[str autorelease];
}
NSZoneFree (NSDefaultMallocZone (), from);
return str;
}
+ (BOOL) matchIP: (NSString*)address to: (NSString*)pattern
{
uint32_t remote;
NSArray *parts;
NSArray *items;
unsigned count;
unsigned index;
parts = [address componentsSeparatedByString: @"."];
remote = [[parts objectAtIndex: 0] intValue];
remote = remote * 256 + [[parts objectAtIndex: 1] intValue];
remote = remote * 256 + [[parts objectAtIndex: 2] intValue];
remote = remote * 256 + [[parts objectAtIndex: 3] intValue];
items = [pattern componentsSeparatedByString: @","];
count = [items count];
for (index = 0; index < count; index++)
{
pattern = [[items objectAtIndex: index] stringByTrimmingSpaces];
if ([pattern length] > 0)
{
NSRange r = [pattern rangeOfString: @"/"];
uint32_t want;
if (0 == r.length)
{
/* An IPv4 address in dot format (nnn.nnn.nnn.nnn)
*/
parts = [pattern componentsSeparatedByString: @"."];
want = [[parts objectAtIndex: 0] intValue];
want = want * 256 + [[parts objectAtIndex: 1] intValue];
want = want * 256 + [[parts objectAtIndex: 2] intValue];
want = want * 256 + [[parts objectAtIndex: 3] intValue];
if (remote == want)
{
return YES;
}
}
else
{
int bits;
uint32_t mask;
int i;
/* An IPv4 mask in dot format with a number of bits specified
* after a slash (nnn.nnn.nnn.nnn/bits)
*/
parts = [pattern componentsSeparatedByString: @"/"];
bits = [[parts objectAtIndex: 1] intValue];
pattern = [parts objectAtIndex: 0];
parts = [pattern componentsSeparatedByString: @"."];
want = [[parts objectAtIndex: 0] intValue];
want = want * 256 + [[parts objectAtIndex: 1] intValue];
want = want * 256 + [[parts objectAtIndex: 2] intValue];
want = want * 256 + [[parts objectAtIndex: 3] intValue];
mask = 0xffffffff;
bits = 32 - bits;
for (i = 0; i < bits; i++)
{
mask &= ~(1<<i);
}
NSAssert((want & mask) == want, NSInternalInconsistencyException);
if ((remote & mask) == want)
{
return YES;
}
}
}
}
return NO;
}
+ (NSURL*) linkPath: (NSString*)newPath
relative: (NSURL*)oldURL
query: (NSDictionary*)fields, ...
{
va_list ap;
NSMutableDictionary *m;
id key;
id val;
NSRange r;
m = [fields mutableCopy];
va_start (ap, fields);
while ((key = va_arg(ap, id)) != nil && (val = va_arg(ap, id)) != nil)
{
if (m == nil)
{
m = [[NSMutableDictionary alloc] initWithCapacity: 2];
}
[m setObject: val forKey: key];
}
va_end (ap);
/* The new path must NOT contain a query string.
*/
r = [newPath rangeOfString: @"?"];
if (r.length > 0)
{
newPath = [newPath substringToIndex: r.location];
}
if ([m count] > 0)
{
NSMutableData *data;
data = [[newPath dataUsingEncoding: NSUTF8StringEncoding] mutableCopy];
[data appendBytes: "?" length: 1];
[self encodeURLEncodedForm: m charset: nil into: data];
newPath = [NSString alloc];
newPath = [newPath initWithData: data encoding: NSUTF8StringEncoding];
[newPath autorelease];
[data release];
}
[m release];
if (oldURL == nil)
{
return [NSURL URLWithString: newPath];
}
else
{
return [NSURL URLWithString: newPath relativeToURL: oldURL];
}
}
+ (NSData*) parameter: (NSString*)name
at: (NSUInteger)index
from: (NSDictionary*)params
{
NSArray *a = [params objectForKey: name];
if (a == nil)
{
NSEnumerator *e = [params keyEnumerator];
NSString *k;
while ((k = [e nextObject]) != nil)
{
if ([k caseInsensitiveCompare: name] == NSOrderedSame)
{
a = [params objectForKey: k];
break;
}
}
}
if (index >= [a count])
{
return nil;
}
return [a objectAtIndex: index];
}
+ (NSString*) parameterString: (NSString*)name
at: (NSUInteger)index
from: (NSDictionary*)params
charset: (NSString*)charset
{
NSData *d = [self parameter: name at: index from: params];
NSString *s = nil;
if (d != nil)
{
s = Alloc(NSStringClass);
if (charset == nil || [charset length] == 0)
{
s = [s initWithData: d encoding: NSUTF8StringEncoding];
}
else
{
NSStringEncoding enc;
enc = [GSMimeDocumentClass encodingFromCharset: charset];
s = [s initWithData: d encoding: enc];
}
}
return AUTORELEASE(s);
}
+ (BOOL) redirectRequest: (WebServerRequest*)request
response: (WebServerResponse*)response
to: (id)destination
{
NSString *s;
NSString *type;
NSString *body;
/* If the destination is not an NSURL, take it as a string defining a
* relative URL from the request base URL.
*/
if (NO == [destination isKindOfClass: [NSURL class]])
{
s = [destination description];
destination = [self baseURLForRequest: request];
if (s != nil)
{
destination = [NSURL URLWithString: s relativeToURL: destination];
}
}
s = [destination absoluteString];
[response setHeader: @"Location" value: s parameters: nil];
[response setHeader: @"http"
value: @"HTTP/1.1 302 Found"
parameters: nil];
type = @"text/html";
body = [NSString stringWithFormat:
@"<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
@"<html><head><title>continue</title>"
@"</head><body><a href=\"%@\">continue</a></body></html>",
[self escapeHTML: s]];
s = [[request headerNamed: @"accept"] value];
if ([s length] > 0)
{
NSEnumerator *e;
/* Enumerate through all the supported types.
*/
e = [[s componentsSeparatedByString: @","] objectEnumerator];
while ((s = [e nextObject]) != nil)
{
/* Separate the type from any parameters.
*/
s = [[[s componentsSeparatedByString: @";"] objectAtIndex: 0]
stringByTrimmingSpaces];
if ([s isEqualToString: @"text/html"]
|| [s isEqualToString: @"text/xhtml"]
|| [s isEqualToString: @"application/xhtml+xml"]
|| [s isEqualToString: @"application/vnd.wap.xhtml+xml"]
|| [s isEqualToString: @"text/vnd.wap.wml"])
{
type = s;
break;
}
}
}
[response setContent: body type: type];
return YES;
}
- (BOOL) accessRequest: (WebServerRequest*)request
response: (WebServerResponse*)response
{
NSDictionary *conf = [_defs dictionaryForKey: @"WebServerAccess"];
NSString *path = [[request headerNamed: @"x-http-path"] value];
NSDictionary *access = nil;
NSString *stored = nil;
NSString *username;
NSString *password;
while (access == nil)
{
access = [conf objectForKey: path];
if ([access isKindOfClass: NSDictionaryClass] == NO)
{
NSRange r;
access = nil;
r = [path rangeOfString: @"/" options: NSBackwardsSearch];
if (r.length > 0)
{
path = [path substringToIndex: r.location];
}
else
{
return YES; // No access dictionary - permit access
}
}
}
username = [[request headerNamed: @"x-http-username"] value];
password = [[request headerNamed: @"x-http-password"] value];
if ([access objectForKey: @"Users"] != nil)
{
NSDictionary *users = [access objectForKey: @"Users"];
stored = [users objectForKey: username];
}
if (username == nil || password == nil || [password isEqual: stored] == NO)
{
NSString *realm = [access objectForKey: @"Realm"];
NSString *auth;
auth = [NSStringClass stringWithFormat: @"Basic realm=\"%@\"", realm];
/*
* Return status code 401 (Aunauthorised)
*/
[response setHeader: @"http"
value: @"HTTP/1.1 401 Unauthorised"
parameters: nil];
[response setHeader: @"WWW-authenticate"
value: auth
parameters: nil];
[response setContent:
@"<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
@"<html><head><title>401 Authorization Required</title></head><body>\n"
@"<h1>Authorization Required</h1>\n"
@"<p>This server could not verify that you "
@"are authorized to access the resource "
@"requested. Either you supplied the wrong "
@"credentials (e.g., bad password), or your "
@"browser doesn't understand how to supply "
@"the credentials required.</p>\n"
@"</body></html>\n"
type: @"text/html"];
return NO;
}
else
{
return YES; // OK to access
}
}
- (NSString*) address
{
NSString *s;
[_lock lock];
s = [_addr retain];
[_lock unlock];
return [s autorelease];
}
- (NSTimeInterval) authenticationFailureBanTime
{
return _authFailureBanTime;
}
- (NSUInteger) authenticationFailureMaxRetry
{
return _authFailureMaxRetry;
}
- (NSTimeInterval) authenticationFailureFindTime
{
return _authFailureFindTime;
}
- (void) closeConnectionAfter: (WebServerResponse*)response
{
[_lock lock];
[[response webServerConnection] setShouldClose: YES];
[_lock unlock];
}
- (void) completedWithResponse: (WebServerResponse*)response
{
if (NO == [response isKindOfClass: WebServerResponseClass])
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] argument is not a valid response object",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
}
if (YES == [response completing])
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] argument is already completing",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
}
if (YES == _doPostProcess)
{
[_pool scheduleSelector: @selector(_process4:)
onReceiver: self
withObject: response];
}
else
{
WebServerConnection *connection = nil;
BOOL wasCompleting;
[_lock lock];
wasCompleting = [response completing];
if (NO == wasCompleting)
{
[response setCompleting];
_processingCount--;
connection = [[response webServerConnection] retain];
}
[response setWebServerConnection: nil];
[_lock unlock];
if (YES == wasCompleting)
{
if (YES == _conf->verbose)
{
[self _log: @"Called -completedWithResponse: for a response"
@" which is already complete: %@", response];
}
}
else if (nil == connection)
{
if (YES == _conf->verbose)
{
[self _log: @"The client has already closed the connection"
@" for response: %@", response];
}
}
else
{
[_pool scheduleSelector: @selector(respond:)
onReceiver: connection
withObject: nil];
[connection release];
}
}
}
- (NSArray*) connections
{
NSArray *a;
[_lock lock];
a = [_connections allObjects];
[_lock unlock];
return a;
}
- (void) dealloc
{
[self setAddress: nil port: nil secure: nil];
[self setIOThreads: 0 andPool: 0];
DESTROY(_authFailureLog);
DESTROY(_nc);
DESTROY(_defs);
DESTROY(_root);