ObjFW  Diff

Differences From Artifact [bf72062f11]:

To Artifact [77f28b39f4]:


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







+

















-
-
-
-







#import "OFArray.h"
#import "OFData.h"
#import "OFDate.h"
#import "OFDictionary.h"
#import "OFHTTPRequest.h"
#import "OFHTTPResponse.h"
#import "OFNumber.h"
#import "OFSocket+Private.h"
#import "OFTCPSocket.h"
#import "OFTLSSocket.h"
#import "OFThread.h"
#import "OFTimer.h"
#import "OFURL.h"

#import "OFAlreadyConnectedException.h"
#import "OFInvalidArgumentException.h"
#import "OFInvalidEncodingException.h"
#import "OFInvalidFormatException.h"
#import "OFNotOpenException.h"
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"
#import "OFTruncatedDataException.h"
#import "OFUnsupportedProtocolException.h"
#import "OFWriteFailedException.h"

#import "socket_helpers.h"

#define BUFFER_SIZE 1024

/*
 * FIXME: Key normalization replaces headers like "DNT" with "Dnt".
 * FIXME: Errors are not reported to the user.
 */

@interface OFHTTPServer () <OFTCPSocketDelegate>
@end
73
74
75
76
77
78
79
80
81
82



83
84
85

86
87
88
89
90
91
92
70
71
72
73
74
75
76



77
78
79
80
81

82
83
84
85
86
87
88
89







-
-
-
+
+
+


-
+







@interface OFHTTPServerConnection: OFObject <OFTCPSocketDelegate>
{
@public
	OFStreamSocket *_socket;
	OFHTTPServer *_server;
	OFTimer *_timer;
	enum {
		AWAITING_PROLOG,
		PARSING_HEADERS,
		SEND_RESPONSE
		StateAwaitingProlog,
		StateParsingHeaders,
		StateSendResponse
	} _state;
	uint8_t _HTTPMinorVersion;
	of_http_request_method_t _method;
	OFHTTPRequestMethod _method;
	OFString *_host, *_path;
	uint16_t _port;
	OFMutableDictionary *_headers;
	size_t _contentLength;
	OFStream *_requestBody;
}

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







-
+








-
+






-
-
+









-
+







- (void)stop;
@end
#endif

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

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

	while (*tmp != '\0') {
		if (!of_ascii_isalpha(*tmp)) {
		if (!OFASCIIIsAlpha(*tmp)) {
			firstLetter = true;
			tmp++;
			continue;
		}

		*tmp = (firstLetter
		    ? of_ascii_toupper(*tmp)
		    : of_ascii_tolower(*tmp));
		    ? OFASCIIToUpper(*tmp) : OFASCIIToLower(*tmp));

		firstLetter = false;
		tmp++;
	}

	@try {
		return [OFString stringWithUTF8StringNoCopy: cString
					       freeWhenDone: true];
	} @catch (id e) {
		free(cString);
		OFFreeMemory(cString);
		@throw e;
	}
}

@implementation OFHTTPServerResponse
- (instancetype)initWithSocket: (OFStreamSocket *)sock
			server: (OFHTTPServer *)server
185
186
187
188
189
190
191
192

193
194
195
196
197
198
199
181
182
183
184
185
186
187

188
189
190
191
192
193
194
195







-
+







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

	[_socket writeFormat: @"HTTP/%@ %hd %@\r\n",
			      self.protocolVersionString, _statusCode,
			      of_http_status_code_to_string(_statusCode)];
			      OFHTTPStatusCodeString(_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"];
294
295
296
297
298
299
300
301

302
303
304
305
306
307
308
290
291
292
293
294
295
296

297
298
299
300
301
302
303
304







-
+







		_server = [server retain];
		_timer = [[OFTimer
		    scheduledTimerWithTimeInterval: 10
					    target: _socket
					  selector: @selector(
							cancelAsyncRequests)
					   repeats: false] retain];
		_state = AWAITING_PROLOG;
		_state = StateAwaitingProlog;
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}
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
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







-
+

-
+








-
+










-
-
+
+














-
+




-
+





-
+















-
+







     exception: (id)exception
{
	if (line == nil || exception != nil)
		return false;

	@try {
		switch (_state) {
		case AWAITING_PROLOG:
		case StateAwaitingProlog:
			return [self parseProlog: line];
		case PARSING_HEADERS:
		case StateParsingHeaders:
			return [self parseHeaders: line];
		default:
			return false;
		}
	} @catch (OFWriteFailedException *e) {
		return false;
	}

	OF_ENSURE(0);
	OFEnsure(0);
}

- (bool)parseProlog: (OFString *)line
{
	OFString *method;
	OFMutableString *path;
	size_t pos;

	@try {
		OFString *version = [line
		    substringWithRange: of_range(line.length - 9, 9)];
		of_unichar_t tmp;
		    substringWithRange: OFRangeMake(line.length - 9, 9)];
		OFUnichar 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)
	if (pos == OFNotFound)
		return [self sendErrorAndClose: 400];

	method = [line substringToIndex: pos];
	@try {
		_method = of_http_request_method_from_string(method);
		_method = OFHTTPRequestMethodParseName(method);
	} @catch (OFInvalidArgumentException *e) {
		return [self sendErrorAndClose: 405];
	}

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

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

	[path deleteEnclosingWhitespaces];
	[path makeImmutable];

	if (![path hasPrefix: @"/"])
		return [self sendErrorAndClose: 400];

	_headers = [[OFMutableDictionary alloc] init];
	_path = [path copy];
	_state = PARSING_HEADERS;
	_state = StateParsingHeaders;

	return true;
}

- (bool)parseHeaders: (OFString *)line
{
	OFString *key, *value, *old;
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
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







-
+






-
+















-
+
-
-
+

-
+







			     contentLength: contentLength];

			[_timer invalidate];
			[_timer release];
			_timer = nil;
		}

		_state = SEND_RESPONSE;
		_state = StateSendResponse;
		[self createResponse];

		return false;
	}

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

	key = [line substringToIndex: pos];
	value = [line substringFromIndex: pos + 1];

	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
		pos = [value rangeOfString: @":"
		    rangeOfString: @":"
			  options: OF_STRING_SEARCH_BACKWARDS].location;
				   options: OFStringSearchBackwards].location;

		if (pos != OF_NOT_FOUND) {
		if (pos != OFNotFound) {
			[_host release];
			_host = [[value substringToIndex: pos] retain];

			@try {
				unsigned long long portTmp =
				    [value substringFromIndex: pos + 1]
				    .unsignedLongLongValue;
496
497
498
499
500
501
502
503

504
505
506
507
508
509
510
511
491
492
493
494
495
496
497

498

499
500
501
502
503
504
505







-
+
-







{
	OFString *date = [[OFDate date]
	    dateStringWithFormat: @"%a, %d %b %Y %H:%M:%S GMT"];
	[_socket writeFormat: @"HTTP/1.1 %hd %@\r\n"
			      @"Date: %@\r\n"
			      @"Server: %@\r\n"
			      @"\r\n",
			      statusCode,
			      statusCode, OFHTTPStatusCodeString(statusCode),
			      of_http_status_code_to_string(statusCode),
			      date, _server.name];
	return false;
}

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







-
+















-
+








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

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

		path = [_path substringToIndex: pos];
		query = [_path substringFromIndex: pos + 1];

		URL.URLEncodedPath = path;
		URL.URLEncodedQuery = query;
	} else
		URL.URLEncodedPath = _path;

	[URL makeImmutable];

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

	response = [[[OFHTTPServerResponse alloc]
	    initWithSocket: _socket
		    server: _server
		   request: request] autorelease];
690
691
692
693
694
695
696
697

698
699
700
701
702
703
704
705

706
707
708
709
710
711
712
684
685
686
687
688
689
690

691
692
693
694
695
696
697
698

699
700
701
702
703
704
705
706







-
+







-
+







			@throw [OFInvalidFormatException exception];
		}

		if (line == nil)
			return 0;

		pos = [line rangeOfString: @";"].location;
		if (pos != OF_NOT_FOUND)
		if (pos != OFNotFound)
			line = [line substringToIndex: pos];

		if (line.length < 1) {
			/*
			 * We have read the empty string because the socket is
			 * at end of stream.
			 */
			if (_socket.atEndOfStream && pos == OF_NOT_FOUND)
			if (_socket.atEndOfStream && pos == OFNotFound)
				@throw [OFTruncatedDataException exception];
			else
				@throw [OFInvalidFormatException exception];
		}

		toRead = [line unsignedLongLongValueWithBase: 16];
		if (toRead > LLONG_MAX)
905
906
907
908
909
910
911
912

913
914
915

916
917
918
919
920
921
922
899
900
901
902
903
904
905

906
907
908

909
910
911
912
913
914
915
916







-
+


-
+








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

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

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

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

		TLSSocket.certificateFile = _certificateFile;
		TLSSocket.privateKeyFile = _privateKeyFile;
		TLSSocket.privateKeyPassphrase = _privateKeyPassphrase;
	} else
		_listeningSocket = [[OFTCPSocket alloc] init];