ObjFW  Diff

Differences From Artifact [503afee9ba]:

To Artifact [3cdaff788f]:


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
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







-
+





-
+







-
+
















-
+









-
+




-
+







 */

@interface OFHTTPServer () <OFTCPSocketDelegate>
@end

@interface OFHTTPServerResponse: OFHTTPResponse <OFReadyForWritingObserving>
{
	OF_KINDOF(OFTCPSocket *) _socket;
	OFTCPSocket *_socket;
	OFHTTPServer *_server;
	OFHTTPRequest *_request;
	bool _chunked, _headersSent;
}

- (instancetype)initWithSocket: (OF_KINDOF(OFTCPSocket *))sock
- (instancetype)initWithSocket: (OFTCPSocket *)sock
			server: (OFHTTPServer *)server
		       request: (OFHTTPRequest *)request;
@end

@interface OFHTTPServer_Connection: OFObject <OFTCPSocketDelegate>
{
@public
	OF_KINDOF(OFTCPSocket *) _socket;
	OFTCPSocket *_socket;
	OFHTTPServer *_server;
	OFTimer *_timer;
	enum {
		AWAITING_PROLOG,
		PARSING_HEADERS,
		SEND_RESPONSE
	} _state;
	uint8_t _HTTPMinorVersion;
	of_http_request_method_t _method;
	OFString *_host, *_path;
	uint16_t _port;
	OFMutableDictionary *_headers;
	size_t _contentLength;
	OFStream *_requestBody;
}

- (instancetype)initWithSocket: (OF_KINDOF(OFTCPSocket *))sock
- (instancetype)initWithSocket: (OFTCPSocket *)sock
			server: (OFHTTPServer *)server;
- (bool)parseProlog: (OFString *)line;
- (bool)parseHeaders: (OFString *)line;
- (bool)sendErrorAndClose: (short)statusCode;
- (void)createResponse;
@end

@interface OFHTTPServerRequestBodyStream: OFStream <OFReadyForReadingObserving>
{
	OF_KINDOF(OFTCPSocket *) _socket;
	OFTCPSocket *_socket;
	uintmax_t _toRead;
	bool _atEndOfStream;
}

- (instancetype)initWithSocket: (OF_KINDOF(OFTCPSocket *))sock
- (instancetype)initWithSocket: (OFTCPSocket *)sock
		 contentLength: (uintmax_t)contentLength;
@end

#ifdef OF_HAVE_THREADS
@interface OFHTTPServerThread: OFThread
- (void)stop;
@end
201
202
203
204
205
206
207
208

209
210
211
212
213
214

215
216
217
218
219
220
221
201
202
203
204
205
206
207

208
209
210
211
212
213

214
215
216
217
218
219
220
221







-
+





-
+







		return NULL;
	}
}

static OF_INLINE OFString *
normalizedKey(OFString *key)
{
	char *cString = of_strdup([key UTF8String]);
	char *cString = of_strdup(key.UTF8String);
	unsigned char *tmp = (unsigned char *)cString;
	bool firstLetter = true;

	if (cString == NULL)
		@throw [OFOutOfMemoryException
		    exceptionWithRequestedSize: strlen([key UTF8String])];
		    exceptionWithRequestedSize: strlen(key.UTF8String)];

	while (*tmp != '\0') {
		if (!of_ascii_isalpha(*tmp)) {
			firstLetter = true;
			tmp++;
			continue;
		}
229
230
231
232
233
234
235
236

237
238
239
240
241
242
243
229
230
231
232
233
234
235

236
237
238
239
240
241
242
243







-
+







	}

	return [OFString stringWithUTF8StringNoCopy: cString
				       freeWhenDone: true];
}

@implementation OFHTTPServerResponse
- (instancetype)initWithSocket: (OF_KINDOF(OFTCPSocket *))sock
- (instancetype)initWithSocket: (OFTCPSocket *)sock
			server: (OFHTTPServer *)server
		       request: (OFHTTPRequest *)request
{
	self = [super init];

	_statusCode = 500;
	_socket = [sock retain];
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
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







-
+













-
+







{
	void *pool = objc_autoreleasePoolPush();
	OFMutableDictionary OF_GENERIC(OFString *, OFString *) *headers;
	OFEnumerator *keyEnumerator, *valueEnumerator;
	OFString *key, *value;

	[_socket writeFormat: @"HTTP/%@ %d %s\r\n",
			      [self protocolVersionString], _statusCode,
			      self.protocolVersionString, _statusCode,
			      statusCodeToString(_statusCode)];

	headers = [[_headers mutableCopy] autorelease];

	if ([headers objectForKey: @"Date"] == nil) {
		OFString *date = [[OFDate date]
		    dateStringWithFormat: @"%a, %d %b %Y %H:%M:%S GMT"];

		[headers setObject: date
			    forKey: @"Date"];
	}

	if ([headers objectForKey: @"Server"] == nil) {
		OFString *name = [_server name];
		OFString *name = _server.name;

		if (name != nil)
			[headers setObject: name
				    forKey: @"Server"];
	}

	keyEnumerator = [headers keyEnumerator];
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
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







-
+




















-
+




-
+







		if (!_headersSent)
			[self of_sendHeaders];

		if (_chunked)
			[_socket writeBuffer: "0\r\n\r\n"
				      length: 5];
	} @catch (OFWriteFailedException *e) {
		id <OFHTTPServerDelegate> delegate = [_server delegate];
		id <OFHTTPServerDelegate> delegate = _server.delegate;

		if ([delegate respondsToSelector: @selector(server:
		  didReceiveExceptionForResponse:request:exception:)])
			[delegate		    server: _server
			    didReceiveExceptionForResponse: self
						   request: _request
						 exception: e];
	}

	[_socket release];
	_socket = nil;

	[super close];
}

- (int)fileDescriptorForWriting
{
	if (_socket == nil)
		return -1;

	return [_socket fileDescriptorForWriting];
	return _socket.fileDescriptorForWriting;
}
@end

@implementation OFHTTPServer_Connection
- (instancetype)initWithSocket: (OF_KINDOF(OFTCPSocket *))sock
- (instancetype)initWithSocket: (OFTCPSocket *)sock
			server: (OFHTTPServer *)server
{
	self = [super init];

	@try {
		_socket = [sock retain];
		_server = [server retain];
405
406
407
408
409
410
411
412

413
414
415
416
417
418
419
405
406
407
408
409
410
411

412
413
414
415
416
417
418
419







-
+







	[_path release];
	[_headers release];
	[_requestBody release];

	[super dealloc];
}

- (bool)stream: (OF_KINDOF(OFStream *))sock
- (bool)stream: (OFStream *)sock
   didReadLine: (OFString *)line
     exception: (id)exception
{
	if (line == nil || exception != nil)
		return false;

	@try {
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
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







-
+




















-
+
-





-
+







{
	OFString *method;
	OFMutableString *path;
	size_t pos;

	@try {
		OFString *version = [line
		    substringWithRange: of_range([line length] - 9, 9)];
		    substringWithRange: of_range(line.length - 9, 9)];
		of_unichar_t tmp;

		if (![version hasPrefix: @" HTTP/1."])
			return [self sendErrorAndClose: 505];

		tmp = [version characterAtIndex: 8];
		if (tmp < '0' || tmp > '9')
			return [self sendErrorAndClose: 400];

		_HTTPMinorVersion = (uint8_t)(tmp - '0');
	} @catch (OFOutOfRangeException *e) {
		return [self sendErrorAndClose: 400];
	}

	pos = [line rangeOfString: @" "].location;
	if (pos == OF_NOT_FOUND)
		return [self sendErrorAndClose: 400];

	method = [line substringWithRange: of_range(0, pos)];
	@try {
		_method = of_http_request_method_from_string(
		_method = of_http_request_method_from_string(method.UTF8String);
		    [method UTF8String]);
	} @catch (OFInvalidFormatException *e) {
		return [self sendErrorAndClose: 405];
	}

	@try {
		of_range_t range = of_range(pos + 1, [line length] - pos - 10);
		of_range_t range = of_range(pos + 1, line.length - pos - 10);

		path = [[[line substringWithRange:
		    range] mutableCopy] autorelease];
	} @catch (OFOutOfRangeException *e) {
		return [self sendErrorAndClose: 400];
	}

490
491
492
493
494
495
496
497

498
499
500
501
502
503
504
505
506

507
508
509
510
511
512
513
489
490
491
492
493
494
495

496
497
498
499
500
501
502
503
504

505
506
507
508
509
510
511
512







-
+








-
+







}

- (bool)parseHeaders: (OFString *)line
{
	OFString *key, *value, *old;
	size_t pos;

	if ([line length] == 0) {
	if (line.length == 0) {
		OFString *contentLengthString;

		if ((contentLengthString =
		    [_headers objectForKey: @"Content-Length"]) != nil) {
			intmax_t contentLength;

			@try {
				contentLength =
				    [contentLengthString decimalValue];
				    contentLengthString.decimalValue;

			} @catch (OFInvalidFormatException *e) {
				return [self sendErrorAndClose: 400];
			}

			if (contentLength < 0)
				return [self sendErrorAndClose: 400];
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
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







-
+

-
-
+
+




















-
-
-
+
+
+








	pos = [line rangeOfString: @":"].location;
	if (pos == OF_NOT_FOUND)
		return [self sendErrorAndClose: 400];

	key = [line substringWithRange: of_range(0, pos)];
	value = [line substringWithRange:
	    of_range(pos + 1, [line length] - pos - 1)];
	    of_range(pos + 1, line.length - pos - 1)];

	key = normalizedKey([key stringByDeletingTrailingWhitespaces]);
	value = [value stringByDeletingLeadingWhitespaces];
	key = normalizedKey(key.stringByDeletingTrailingWhitespaces);
	value = value.stringByDeletingLeadingWhitespaces;

	old = [_headers objectForKey: key];
	if (old != nil)
		value = [old stringByAppendingFormat: @",%@", value];

	[_headers setObject: value
		     forKey: key];

	if ([key isEqual: @"Host"]) {
		pos = [value
		    rangeOfString: @":"
			  options: OF_STRING_SEARCH_BACKWARDS].location;

		if (pos != OF_NOT_FOUND) {
			[_host release];
			_host = [[value substringWithRange:
			    of_range(0, pos)] retain];

			@try {
				of_range_t range =
				    of_range(pos + 1, [value length] - pos - 1);
				intmax_t portTmp = [[value
				    substringWithRange: range] decimalValue];
				    of_range(pos + 1, value.length - pos - 1);
				intmax_t portTmp = [value
				    substringWithRange: range].decimalValue;

				if (portTmp < 1 || portTmp > UINT16_MAX)
					return [self sendErrorAndClose: 400];

				_port = (uint16_t)portTmp;
			} @catch (OFInvalidFormatException *e) {
				return [self sendErrorAndClose: 400];
586
587
588
589
590
591
592
593

594
595
596
597
598
599
600
585
586
587
588
589
590
591

592
593
594
595
596
597
598
599







-
+







	    dateStringWithFormat: @"%a, %d %b %Y %H:%M:%S GMT"];

	[_socket writeFormat: @"HTTP/1.1 %d %s\r\n"
			      @"Date: %@\r\n"
			      @"Server: %@\r\n"
			      @"\r\n",
			      statusCode, statusCodeToString(statusCode),
			      date, [_server name]];
			      date, _server.name];

	return false;
}

- (void)createResponse
{
	void *pool = objc_autoreleasePoolPush();
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
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







-
+




-
-
+
+

-
+






-
+

-
-
+
+

-
+




-
-
-
-
-
+
+
+
+
+






-
-
-
-
+
+
+
+






-
+







	if (_host == nil || _port == 0) {
		if (_HTTPMinorVersion > 0) {
			[self sendErrorAndClose: 400];
			return;
		}

		[_host release];
		_host = [[_server host] retain];
		_host = [_server.host copy];
		_port = [_server port];
	}

	URL = [OFMutableURL URL];
	[URL setScheme: @"http"];
	[URL setHost: _host];
	URL.scheme = @"http";
	URL.host = _host;
	if (_port != 80)
		[URL setPort: [OFNumber numberWithUInt16: _port]];
		URL.port = [OFNumber numberWithUInt16: _port];

	if ((pos = [_path rangeOfString: @"?"].location) != OF_NOT_FOUND) {
		OFString *path, *query;

		path = [_path substringWithRange: of_range(0, pos)];
		query = [_path substringWithRange:
		    of_range(pos + 1, [_path length] - pos - 1)];
		    of_range(pos + 1, _path.length - pos - 1)];

		[URL setURLEncodedPath: path];
		[URL setURLEncodedQuery: query];
		URL.URLEncodedPath = path;
		URL.URLEncodedQuery = query;
	} else
		[URL setURLEncodedPath: _path];
		URL.URLEncodedPath = _path;

	[URL makeImmutable];

	request = [OFHTTPRequest requestWithURL: URL];
	[request setMethod: _method];
	[request setProtocolVersion:
	    (of_http_request_protocol_version_t){ 1, _HTTPMinorVersion }];
	[request setHeaders: _headers];
	[request setRemoteAddress: [_socket remoteAddress]];
	request.method = _method;
	request.protocolVersion =
	    (of_http_request_protocol_version_t){ 1, _HTTPMinorVersion };
	request.headers = _headers;
	request.remoteAddress = _socket.remoteAddress;

	response = [[[OFHTTPServerResponse alloc]
	    initWithSocket: _socket
		    server: _server
		   request: request] autorelease];

	[[_server delegate] server: _server
		 didReceiveRequest: request
		       requestBody: _requestBody
			  response: response];
	[_server.delegate server: _server
	       didReceiveRequest: request
		     requestBody: _requestBody
			response: response];

	objc_autoreleasePoolPop(pool);
}
@end

@implementation OFHTTPServerRequestBodyStream
- (instancetype)initWithSocket: (OF_KINDOF(OFTCPSocket *))sock
- (instancetype)initWithSocket: (OFTCPSocket *)sock
		 contentLength: (uintmax_t)contentLength
{
	self = [super init];

	@try {
		_socket = [sock retain];
		_toRead = contentLength;
707
708
709
710
711
712
713
714

715
716
717
718
719

720
721
722
723
724
725
726
706
707
708
709
710
711
712

713
714
715
716
717

718
719
720
721
722
723
724
725







-
+




-
+







	_toRead -= ret;

	return ret;
}

- (bool)hasDataInReadBuffer
{
	return ([super hasDataInReadBuffer] || [_socket hasDataInReadBuffer]);
	return (super.hasDataInReadBuffer || _socket.hasDataInReadBuffer);
}

- (int)fileDescriptorForReading
{
	return [_socket fileDescriptorForReading];
	return _socket.fileDescriptorForReading;
}

- (void)close
{
	[_socket release];
	_socket = nil;
}
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
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







-
+

-
+





-
+



















-
+




-
+
+

-
-
-
+
+
-
-
+








- (const char *)privateKeyPassphrase
{
	return _privateKeyPassphrase;
}

#ifdef OF_HAVE_THREADS
- (void)setNumberOfThreads: (size_t)numberOfThreadas
- (void)setNumberOfThreads: (size_t)numberOfThreads
{
	if (numberOfThreadas == 0)
	if (numberOfThreads == 0)
		@throw [OFInvalidArgumentException exception];

	if (_listeningSocket != nil)
		@throw [OFAlreadyConnectedException exception];

	_numberOfThreads = numberOfThreadas;
	_numberOfThreads = numberOfThreads;
}

- (size_t)numberOfThreads
{
	return _numberOfThreads;
}
#endif

- (void)start
{
	void *pool = objc_autoreleasePoolPush();

	if (_host == nil)
		@throw [OFInvalidArgumentException exception];

	if (_listeningSocket != nil)
		@throw [OFAlreadyConnectedException exception];

	if (_usesTLS) {
		id <OFTLSSocket> listeningSocket;
		OFTCPSocket <OFTLSSocket> *TLSSocket;

		if (of_tls_socket_class == Nil)
			@throw [OFUnsupportedProtocolException exception];

		_listeningSocket = [[of_tls_socket_class alloc] init];
		TLSSocket = [[of_tls_socket_class alloc] init];
		_listeningSocket = TLSSocket;

		listeningSocket = _listeningSocket;
		[listeningSocket setCertificateFile: _certificateFile];
		[listeningSocket setPrivateKeyFile: _privateKeyFile];
		TLSSocket.certificateFile = _certificateFile;
		TLSSocket.privateKeyFile = _privateKeyFile;
		[listeningSocket
		    setPrivateKeyPassphrase: _privateKeyPassphrase];
		TLSSocket.privateKeyPassphrase = _privateKeyPassphrase;
	} else
		_listeningSocket = [[OFTCPSocket alloc] init];

	_port = [_listeningSocket bindToHost: _host
					port: _port];
	[_listeningSocket listen];

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
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







-
+




















-
+





-
+



-
-
+
+







		}

		[threads makeImmutable];
		_threadPool = [threads copy];
	}
#endif

	[(OFTCPSocket *)_listeningSocket setDelegate: self];
	((OFTCPSocket *)_listeningSocket).delegate = self;
	[_listeningSocket asyncAccept];

	objc_autoreleasePoolPop(pool);
}

- (void)stop
{
	[_listeningSocket cancelAsyncRequests];
	[_listeningSocket release];
	_listeningSocket = nil;

#ifdef OF_HAVE_THREADS
	for (OFHTTPServerThread *thread in _threadPool)
		[thread stop];

	[_threadPool release];
	_threadPool = nil;
#endif
}

- (void)of_handleAcceptedSocket: (OF_KINDOF(OFTCPSocket *))acceptedSocket
- (void)of_handleAcceptedSocket: (OFTCPSocket *)acceptedSocket
{
	OFHTTPServer_Connection *connection = [[[OFHTTPServer_Connection alloc]
	    initWithSocket: acceptedSocket
		    server: self] autorelease];

	[(OFTCPSocket *)acceptedSocket setDelegate: connection];
	acceptedSocket.delegate = connection;
	[acceptedSocket asyncReadLine];
}

-    (bool)socket: (OF_KINDOF(OFTCPSocket *))sock
  didAcceptSocket: (OF_KINDOF(OFTCPSocket *))acceptedSocket
-    (bool)socket: (OFTCPSocket *)sock
  didAcceptSocket: (OFTCPSocket *)acceptedSocket
	exception: (id)exception
{
	if (exception != nil) {
		if (![_delegate respondsToSelector:
		    @selector(server:didReceiveExceptionOnListeningSocket:)])
			return false;