ObjFW  Diff

Differences From Artifact [4524bb5e96]:

To Artifact [7e47217e14]:


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

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

@interface OFHTTPServerReply: OFHTTPRequestReply
{
	OFTCPSocket *sock;
	OFHTTPServer *server;
	BOOL chunked, headersSent, closed;
}

- initWithSocket: (OFTCPSocket*)sock
	  server: (OFHTTPServer*)server;
@end

@implementation OFHTTPServerReply
- initWithSocket: (OFTCPSocket*)sock_
	  server: (OFHTTPServer*)server_
{
	self = [super init];

	statusCode = 500;
	sock = [sock_ retain];
	server = [server_ retain];

	return self;
}

- (void)dealloc
{
	if (!closed)
		[self close];

	[sock release];
	[server release];

	[super dealloc];
}

- (void)sendHeaders
{
	void *pool = objc_autoreleasePoolPush();
	OFString *date = [[OFDate date]
	    dateStringWithFormat: @"%a, %d %b %Y %H:%M:%S GMT"];
	OFEnumerator *keyEnumerator, *valueEnumerator;
	OFString *key, *value;

	[sock writeFormat: @"HTTP/%@ %d %s\r\n"
			   @"Server: %@\r\n"
			   @"Date: %@\r\n",
			   [self protocolVersionString], statusCode,
			   status_code_to_string(statusCode),
			   [server name], date];

	keyEnumerator = [headers keyEnumerator];
	valueEnumerator = [headers objectEnumerator];
	while ((key = [keyEnumerator nextObject]) != nil &&
	    (value = [valueEnumerator nextObject]) != nil)
		if (![key isEqual: @"Server"] && ![key isEqual: @"Date"])
			[sock writeFormat: @"%@: %@\r\n", key, value];

	[sock writeString: @"\r\n"];

	headersSent = YES;
	chunked = [[headers objectForKey: @"Transfer-Encoding"]
	    isEqual: @"chunked"];

	objc_autoreleasePoolPop(pool);
}

- (void)lowlevelWriteBuffer: (const void*)buffer
		     length: (size_t)length
{
	void *pool;

	if (!headersSent)
		[self sendHeaders];

	if (!chunked) {
		[sock writeBuffer: buffer
			   length: length];
		return;
	}

	pool = objc_autoreleasePoolPush();
	[sock writeString: [OFString stringWithFormat: @"%zx\r\n", length]];
	objc_autoreleasePoolPop(pool);

	[sock writeBuffer: buffer
		   length: length];
	[sock writeBuffer: "\r\n"
		   length: 2];
}

- (void)close
{
	if (!headersSent)
		[self sendHeaders];

	if (chunked)
		[sock writeBuffer: "0\r\n\r\n"
			   length: 5];

	[sock close];

	closed = YES;
}

- (int)fileDescriptorForWriting
{
	return [sock fileDescriptorForWriting];
}
@end

@interface OFHTTPServer_Connection: OFObject
{
	OFTCPSocket *sock;
	OFHTTPServer *server;
	OFTimer *timer;
	enum {
		AWAITING_PROLOG,
		PARSING_HEADERS,
		SEND_REPLY
	} state;
	uint8_t HTTPMinorVersion;
	of_http_request_type_t requestType;
	OFString *host, *path;
	uint16_t port;
	OFMutableDictionary *headers;
	size_t contentLength;
	OFDataArray *POSTData;
}

- initWithSocket: (OFTCPSocket*)socket
	  server: (OFHTTPServer*)server;
- (BOOL)socket: (OFTCPSocket*)sock
   didReadLine: (OFString*)line
     exception: (OFException*)exception;
- (BOOL)parseProlog: (OFString*)line;
- (BOOL)parseHeaders: (OFString*)line;
-      (BOOL)socket: (OFTCPSocket*)sock
  didReadIntoBuffer: (const char*)buffer
	     length: (size_t)length
	  exception: (OFException*)exception;
- (BOOL)sendErrorAndClose: (short)statusCode;
- (void)createReply;
@end

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

	@try {
		sock = [sock_ retain];
		server = [server_ retain];
		timer = [[OFTimer
		    scheduledTimerWithTimeInterval: 10
					    target: sock
					  selector: @selector(
							cancelAsyncRequests)
					   repeats: NO] retain];
		state = AWAITING_PROLOG;
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}

- (void)dealloc
{
	[sock release];
	[server release];

	[timer invalidate];
	[timer release];

	[host release];
	[path release];
	[headers release];
	[POSTData release];

	[super dealloc];
}

- (BOOL)socket: (OFTCPSocket*)sock_
   didReadLine: (OFString*)line
     exception: (OFException*)exception
{
	if (line == nil || exception != nil)
		return NO;

	@try {
		switch (state) {
		case AWAITING_PROLOG:
			return [self parseProlog: line];
		case PARSING_HEADERS:
			if (![self parseHeaders: line])
				return NO;

			if (state == SEND_REPLY) {
				[self createReply];
				return NO;
			}

			return YES;
		default:
			return NO;







|
|
|


|




|
|



|
|
|






|


|
|












|
|
|
|
|
|

|
|



|

|

|
|










|


|
|
|




|


|
|
|
|




|


|
|
|

|

|




|





|
|
|




|
|
|
|
|
|
|
|




|




|








|
|




|
|
|

|



|










|
|

|
|

|
|
|
|




|







|






|







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

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

@interface OFHTTPServerReply: OFHTTPRequestReply
{
	OFTCPSocket *_socket;
	OFHTTPServer *_server;
	BOOL _chunked, _headersSent, _closed;
}

- initWithSocket: (OFTCPSocket*)socket
	  server: (OFHTTPServer*)server;
@end

@implementation OFHTTPServerReply
- initWithSocket: (OFTCPSocket*)socket
	  server: (OFHTTPServer*)server
{
	self = [super init];

	_statusCode = 500;
	_socket = [socket retain];
	_server = [server retain];

	return self;
}

- (void)dealloc
{
	if (!_closed)
		[self close];

	[_socket release];
	[_server release];

	[super dealloc];
}

- (void)sendHeaders
{
	void *pool = objc_autoreleasePoolPush();
	OFString *date = [[OFDate date]
	    dateStringWithFormat: @"%a, %d %b %Y %H:%M:%S GMT"];
	OFEnumerator *keyEnumerator, *valueEnumerator;
	OFString *key, *value;

	[_socket writeFormat: @"HTTP/%@ %d %s\r\n"
			      @"Server: %@\r\n"
			      @"Date: %@\r\n",
			      [self protocolVersionString], _statusCode,
			      status_code_to_string(_statusCode),
			      [_server name], date];

	keyEnumerator = [_headers keyEnumerator];
	valueEnumerator = [_headers objectEnumerator];
	while ((key = [keyEnumerator nextObject]) != nil &&
	    (value = [valueEnumerator nextObject]) != nil)
		if (![key isEqual: @"Server"] && ![key isEqual: @"Date"])
			[_socket writeFormat: @"%@: %@\r\n", key, value];

	[_socket writeString: @"\r\n"];

	_headersSent = YES;
	_chunked = [[_headers objectForKey: @"Transfer-Encoding"]
	    isEqual: @"chunked"];

	objc_autoreleasePoolPop(pool);
}

- (void)lowlevelWriteBuffer: (const void*)buffer
		     length: (size_t)length
{
	void *pool;

	if (!_headersSent)
		[self sendHeaders];

	if (!_chunked) {
		[_socket writeBuffer: buffer
			      length: length];
		return;
	}

	pool = objc_autoreleasePoolPush();
	[_socket writeString: [OFString stringWithFormat: @"%zx\r\n", length]];
	objc_autoreleasePoolPop(pool);

	[_socket writeBuffer: buffer
		      length: length];
	[_socket writeBuffer: "\r\n"
		      length: 2];
}

- (void)close
{
	if (!_headersSent)
		[self sendHeaders];

	if (_chunked)
		[_socket writeBuffer: "0\r\n\r\n"
			      length: 5];

	[_socket close];

	_closed = YES;
}

- (int)fileDescriptorForWriting
{
	return [_socket fileDescriptorForWriting];
}
@end

@interface OFHTTPServer_Connection: OFObject
{
	OFTCPSocket *_socket;
	OFHTTPServer *_server;
	OFTimer *_timer;
	enum {
		AWAITING_PROLOG,
		PARSING_HEADERS,
		SEND_REPLY
	} _state;
	uint8_t _HTTPMinorVersion;
	of_http_request_type_t _requestType;
	OFString *_host, *_path;
	uint16_t _port;
	OFMutableDictionary *_headers;
	size_t _contentLength;
	OFDataArray *_POSTData;
}

- initWithSocket: (OFTCPSocket*)socket
	  server: (OFHTTPServer*)server;
- (BOOL)socket: (OFTCPSocket*)socket
   didReadLine: (OFString*)line
     exception: (OFException*)exception;
- (BOOL)parseProlog: (OFString*)line;
- (BOOL)parseHeaders: (OFString*)line;
-      (BOOL)socket: (OFTCPSocket*)socket
  didReadIntoBuffer: (const char*)buffer
	     length: (size_t)length
	  exception: (OFException*)exception;
- (BOOL)sendErrorAndClose: (short)statusCode;
- (void)createReply;
@end

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

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

	return self;
}

- (void)dealloc
{
	[_socket release];
	[_server release];

	[_timer invalidate];
	[_timer release];

	[_host release];
	[_path release];
	[_headers release];
	[_POSTData release];

	[super dealloc];
}

- (BOOL)socket: (OFTCPSocket*)socket
   didReadLine: (OFString*)line
     exception: (OFException*)exception
{
	if (line == nil || exception != nil)
		return NO;

	@try {
		switch (_state) {
		case AWAITING_PROLOG:
			return [self parseProlog: line];
		case PARSING_HEADERS:
			if (![self parseHeaders: line])
				return NO;

			if (_state == SEND_REPLY) {
				[self createReply];
				return NO;
			}

			return YES;
		default:
			return NO;
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
		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];

	type = [line substringWithRange: of_range(0, pos)];
	if ([type isEqual: @"GET"])
		requestType = OF_HTTP_REQUEST_TYPE_GET;
	else if ([type isEqual: @"POST"])
		requestType = OF_HTTP_REQUEST_TYPE_POST;
	else if ([type isEqual: @"HEAD"])
		requestType = OF_HTTP_REQUEST_TYPE_HEAD;
	else
		return [self sendErrorAndClose: 501];

	@try {
		path = [line substringWithRange:
		    of_range(pos + 1, [line length] - pos - 10)];
	} @catch (OFOutOfRangeException *e) {
		return [self sendErrorAndClose: 400];
	}
	path = [[path stringByDeletingEnclosingWhitespaces] retain];

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

	headers = [[OFMutableDictionary alloc] init];
	state = PARSING_HEADERS;

	return YES;
}

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

	if ([line length] == 0) {
		switch (requestType) {
		case OF_HTTP_REQUEST_TYPE_GET:
		case OF_HTTP_REQUEST_TYPE_HEAD:
			state = SEND_REPLY;
			break;
		case OF_HTTP_REQUEST_TYPE_POST:;
			OFString *tmp;
			char *buffer;

			tmp = [headers objectForKey: @"Content-Length"];
			if (tmp == nil)
				return [self sendErrorAndClose: 411];

			@try {
				contentLength = (size_t)[tmp decimalValue];
			} @catch (OFInvalidFormatException *e) {
				return [self sendErrorAndClose: 400];
			}

			buffer = [self allocMemoryWithSize: BUFFER_SIZE];
			POSTData = [[OFDataArray alloc] init];

			[sock asyncReadIntoBuffer: buffer
					   length: BUFFER_SIZE
					   target: self
					 selector: @selector(socket:
						       didReadIntoBuffer:
						       length:exception:)];
			[timer setFireDate:
			    [OFDate dateWithTimeIntervalSinceNow: 5]];

			return NO;
		}

		return YES;
	}

	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)];

	key = normalized_key([key stringByDeletingTrailingWhitespaces]);
	value = [value stringByDeletingLeadingWhitespaces];

	[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];

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

				port = (uint16_t)portTmp;
			} @catch (OFInvalidFormatException *e) {
				return [self sendErrorAndClose: 400];
			}
		} else {
			[host release];
			host = [value retain];
			port = 80;
		}
	}

	return YES;
}

-      (BOOL)socket: (OFTCPSocket*)sock_
  didReadIntoBuffer: (const char*)buffer
	     length: (size_t)length
	  exception: (OFException*)exception
{
	if ([sock_ isAtEndOfStream] || exception != nil)
		return NO;

	[POSTData addItems: buffer
		     count: length];

	if ([POSTData count] >= contentLength) {
		@try {
			[self createReply];
		} @catch (OFWriteFailedException *e) {
			return NO;
		}

		return NO;
	}

	[timer setFireDate: [OFDate dateWithTimeIntervalSinceNow: 5]];

	return YES;
}

- (BOOL)sendErrorAndClose: (short)statusCode
{
	OFString *date = [[OFDate date]
	    dateStringWithFormat: @"%a, %d %b %Y %H:%M:%S GMT"];

	[sock writeFormat: @"HTTP/1.1 %d %s\r\n"
			   @"Date: %@\r\n"
			   @"Server: %@\r\n"
			   @"\r\n",
			   statusCode, status_code_to_string(statusCode), date,
			   [server name]];
	[sock close];

	return NO;
}

- (void)createReply
{
	OFURL *URL;
	OFHTTPRequest *request;
	OFHTTPServerReply *reply;
	size_t pos;

	[timer invalidate];
	[timer release];
	timer = nil;

	if (host == nil || port == 0) {
		if (HTTPMinorVersion > 0) {
			[self sendErrorAndClose: 400];
			return;
		}


		host = [[server host] retain];
		port = [server port];
	}

	URL = [OFURL URL];
	[URL setScheme: @"http"];
	[URL setHost: host];
	[URL setPort: 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)];

		[URL setPath: path_];
		[URL setQuery: query];
	} else
		[URL setPath: path];

	request = [OFHTTPRequest requestWithURL: URL];
	[request setRequestType: requestType];
	[request setProtocolVersion:
	    (of_http_request_protocol_version_t){ 1, HTTPMinorVersion }];
	[request setHeaders: headers];
	[request setPOSTData: POSTData];
	[request setRemoteAddress: [sock remoteAddress]];

	reply = [[[OFHTTPServerReply alloc]
	    initWithSocket: sock
		    server: server] autorelease];

	[[server delegate] server: server
		didReceiveRequest: request
			    reply: reply];
}
@end

@implementation OFHTTPServer
+ (instancetype)server
{
	return [[[self alloc] init] autorelease];
}

- init
{
	self = [super init];

	name = @"OFHTTPServer (ObjFW's HTTP server class "
	    @"<https://webkeks.org/objfw/>)";

	return self;
}

- (void)dealloc
{
	[host release];
	[listeningSocket release];
	[name release];

	[super dealloc];
}

- (void)setHost: (OFString*)host_
{
	OF_SETTER(host, host_, YES, 1)
}

- (OFString*)host
{
	OF_GETTER(host, YES)
}

- (void)setPort: (uint16_t)port_
{
	port = port_;
}

- (uint16_t)port
{
	return port;
}

- (void)setDelegate: (id <OFHTTPServerDelegate>)delegate_
{
	delegate = delegate_;
}

- (id <OFHTTPServerDelegate>)delegate
{
	return delegate;
}

- (void)setName: (OFString*)name_
{
	OF_SETTER(name, name_, YES, 1)
}

- (OFString*)name
{
	OF_GETTER(name, YES)
}

- (void)start
{
	if (host == nil || port == 0)
		@throw [OFInvalidArgumentException
		    exceptionWithClass: [self class]
			      selector: _cmd];

	if (listeningSocket != nil)
		@throw [OFAlreadyConnectedException
		    exceptionWithClass: [self class]
				socket: listeningSocket];

	listeningSocket = [[OFTCPSocket alloc] init];
	[listeningSocket bindToHost: host
			       port: port];
	[listeningSocket listen];

	[listeningSocket asyncAcceptWithTarget: self
				      selector: @selector(OF_socket:
						    didAcceptSocket:
						    exception:)];
}

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

- (BOOL)OF_socket: (OFTCPSocket*)socket
  didAcceptSocket: (OFTCPSocket*)clientSocket
	exception: (OFException*)exception
{
	OFHTTPServer_Connection *connection;

	if (exception != nil) {
		if ([delegate respondsToSelector:
		    @selector(server:didReceiveExceptionOnListeningSocket:)])
			return [delegate		  server: self
			    didReceiveExceptionOnListeningSocket: exception];

		return NO;
	}

	connection = [[[OFHTTPServer_Connection alloc]
	    initWithSocket: clientSocket







|










|

|

|




|




|

|


|
|










|


|





|




|





|

|
|
|
|
|
|
|



















|
|







|
|











|




|
|
|






|




|


|
|

|









|









|
|
|
|
|
|
|











|
|
|

|
|




>
|
|




|
|

|
|

|
|


|


|


|

|
|
|
|


|
|

|
|
|













|







|
|
|




|

|




|


|

|




|


|

|




|


|

|




|




|




|


|

|
|
|
|

|
|
|
|




|
|
|









|

|







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

	type = [line substringWithRange: of_range(0, pos)];
	if ([type isEqual: @"GET"])
		_requestType = OF_HTTP_REQUEST_TYPE_GET;
	else if ([type isEqual: @"POST"])
		_requestType = OF_HTTP_REQUEST_TYPE_POST;
	else if ([type isEqual: @"HEAD"])
		_requestType = OF_HTTP_REQUEST_TYPE_HEAD;
	else
		return [self sendErrorAndClose: 501];

	@try {
		_path = [line substringWithRange:
		    of_range(pos + 1, [line length] - pos - 10)];
	} @catch (OFOutOfRangeException *e) {
		return [self sendErrorAndClose: 400];
	}
	_path = [[_path stringByDeletingEnclosingWhitespaces] retain];

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

	_headers = [[OFMutableDictionary alloc] init];
	_state = PARSING_HEADERS;

	return YES;
}

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

	if ([line length] == 0) {
		switch (_requestType) {
		case OF_HTTP_REQUEST_TYPE_GET:
		case OF_HTTP_REQUEST_TYPE_HEAD:
			_state = SEND_REPLY;
			break;
		case OF_HTTP_REQUEST_TYPE_POST:;
			OFString *tmp;
			char *buffer;

			tmp = [_headers objectForKey: @"Content-Length"];
			if (tmp == nil)
				return [self sendErrorAndClose: 411];

			@try {
				_contentLength = (size_t)[tmp decimalValue];
			} @catch (OFInvalidFormatException *e) {
				return [self sendErrorAndClose: 400];
			}

			buffer = [self allocMemoryWithSize: BUFFER_SIZE];
			_POSTData = [[OFDataArray alloc] init];

			[_socket asyncReadIntoBuffer: buffer
					      length: BUFFER_SIZE
					      target: self
					    selector: @selector(socket:
							  didReadIntoBuffer:
							  length:exception:)];
			[_timer setFireDate:
			    [OFDate dateWithTimeIntervalSinceNow: 5]];

			return NO;
		}

		return YES;
	}

	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)];

	key = normalized_key([key stringByDeletingTrailingWhitespaces]);
	value = [value stringByDeletingLeadingWhitespaces];

	[_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];

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

				_port = (uint16_t)portTmp;
			} @catch (OFInvalidFormatException *e) {
				return [self sendErrorAndClose: 400];
			}
		} else {
			[_host release];
			_host = [value retain];
			_port = 80;
		}
	}

	return YES;
}

-      (BOOL)socket: (OFTCPSocket*)socket
  didReadIntoBuffer: (const char*)buffer
	     length: (size_t)length
	  exception: (OFException*)exception
{
	if ([socket isAtEndOfStream] || exception != nil)
		return NO;

	[_POSTData addItems: buffer
		      count: length];

	if ([_POSTData count] >= _contentLength) {
		@try {
			[self createReply];
		} @catch (OFWriteFailedException *e) {
			return NO;
		}

		return NO;
	}

	[_timer setFireDate: [OFDate dateWithTimeIntervalSinceNow: 5]];

	return YES;
}

- (BOOL)sendErrorAndClose: (short)statusCode
{
	OFString *date = [[OFDate date]
	    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, status_code_to_string(statusCode),
			      date, [_server name]];
	[_socket close];

	return NO;
}

- (void)createReply
{
	OFURL *URL;
	OFHTTPRequest *request;
	OFHTTPServerReply *reply;
	size_t pos;

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

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

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

	URL = [OFURL URL];
	[URL setScheme: @"http"];
	[URL setHost: _host];
	[URL setPort: _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)];

		[URL setPath: path];
		[URL setQuery: query];
	} else
		[URL setPath: _path];

	request = [OFHTTPRequest requestWithURL: URL];
	[request setRequestType: _requestType];
	[request setProtocolVersion:
	    (of_http_request_protocol_version_t){ 1, _HTTPMinorVersion }];
	[request setHeaders: _headers];
	[request setPOSTData: _POSTData];
	[request setRemoteAddress: [_socket remoteAddress]];

	reply = [[[OFHTTPServerReply alloc]
	    initWithSocket: _socket
		    server: _server] autorelease];

	[[_server delegate] server: _server
		 didReceiveRequest: request
			     reply: reply];
}
@end

@implementation OFHTTPServer
+ (instancetype)server
{
	return [[[self alloc] init] autorelease];
}

- init
{
	self = [super init];

	_name = @"OFHTTPServer (ObjFW's HTTP server class "
	    @"<https://webkeks.org/objfw/>)";

	return self;
}

- (void)dealloc
{
	[_host release];
	[_listeningSocket release];
	[_name release];

	[super dealloc];
}

- (void)setHost: (OFString*)host
{
	OF_SETTER(_host, host, YES, 1)
}

- (OFString*)host
{
	OF_GETTER(_host, YES)
}

- (void)setPort: (uint16_t)port
{
	_port = port;
}

- (uint16_t)port
{
	return _port;
}

- (void)setDelegate: (id <OFHTTPServerDelegate>)delegate
{
	_delegate = delegate;
}

- (id <OFHTTPServerDelegate>)delegate
{
	return _delegate;
}

- (void)setName: (OFString*)name
{
	OF_SETTER(_name, name, YES, 1)
}

- (OFString*)name
{
	OF_GETTER(_name, YES)
}

- (void)start
{
	if (_host == nil || _port == 0)
		@throw [OFInvalidArgumentException
		    exceptionWithClass: [self class]
			      selector: _cmd];

	if (_listeningSocket != nil)
		@throw [OFAlreadyConnectedException
		    exceptionWithClass: [self class]
				socket: _listeningSocket];

	_listeningSocket = [[OFTCPSocket alloc] init];
	[_listeningSocket bindToHost: _host
				port: _port];
	[_listeningSocket listen];

	[_listeningSocket asyncAcceptWithTarget: self
				       selector: @selector(OF_socket:
						     didAcceptSocket:
						     exception:)];
}

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

- (BOOL)OF_socket: (OFTCPSocket*)socket
  didAcceptSocket: (OFTCPSocket*)clientSocket
	exception: (OFException*)exception
{
	OFHTTPServer_Connection *connection;

	if (exception != nil) {
		if ([_delegate respondsToSelector:
		    @selector(server:didReceiveExceptionOnListeningSocket:)])
			return [_delegate		  server: self
			    didReceiveExceptionOnListeningSocket: exception];

		return NO;
	}

	connection = [[[OFHTTPServer_Connection alloc]
	    initWithSocket: clientSocket