ObjFW  Check-in [bdf9c4d96b]

Overview
Comment:Make OFHTTPRequestReply a stream.

This also implements chunked transfer encoding for OFHTTPServer and adds
a property for the protocol version to OFHTTPRequest(Reply).

Additionally, this makes it possible to add an async version of
OFHTTPClient.

Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: bdf9c4d96b0c915d89deb2baeb55b5443ab1ebe36ee8eb9dbd53f0c0b8bbb12b
User & Date: js on 2013-01-26 00:13:56
Other Links: manifest | tags
Context
2013-01-28
14:29
TableGenerator: Process files on-the-fly. check-in: 4f8251772c user: js tags: trunk
2013-01-26
00:13
Make OFHTTPRequestReply a stream. check-in: bdf9c4d96b user: js tags: trunk
2013-01-25
22:39
Make -[OFStream setBlocking:] more robust. check-in: 436f274d65 user: js tags: trunk
Changes

Modified src/OFDataArray.m from [df33921628] to [993787fe25].

23
24
25
26
27
28
29

30
31
32
33
34
35
36
37

38
39
40
41
42
43
44
#import "OFDataArray.h"
#import "OFString.h"
#import "OFFile.h"
#import "OFURL.h"
#import "OFHTTPClient.h"
#import "OFHTTPRequest.h"
#import "OFHTTPRequestReply.h"

#import "OFXMLElement.h"
#import "OFSystemInfo.h"

#import "OFHTTPRequestFailedException.h"
#import "OFInvalidArgumentException.h"
#import "OFInvalidFormatException.h"
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"


#import "autorelease.h"
#import "base64.h"
#import "macros.h"

/* References for static linking */
void _references_to_categories_of_OFDataArray(void)







>








>







23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#import "OFDataArray.h"
#import "OFString.h"
#import "OFFile.h"
#import "OFURL.h"
#import "OFHTTPClient.h"
#import "OFHTTPRequest.h"
#import "OFHTTPRequestReply.h"
#import "OFDictionary.h"
#import "OFXMLElement.h"
#import "OFSystemInfo.h"

#import "OFHTTPRequestFailedException.h"
#import "OFInvalidArgumentException.h"
#import "OFInvalidFormatException.h"
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"
#import "OFTruncatedDataException.h"

#import "autorelease.h"
#import "base64.h"
#import "macros.h"

/* References for static linking */
void _references_to_categories_of_OFDataArray(void)
140
141
142
143
144
145
146


147
148
149
150
151
152
153

- initWithContentsOfURL: (OFURL*)URL
{
	void *pool;
	OFHTTPClient *client;
	OFHTTPRequest *request;
	OFHTTPRequestReply *reply;


	Class c;

	c = [self class];
	[self release];

	pool = objc_autoreleasePoolPush();








>
>







142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157

- initWithContentsOfURL: (OFURL*)URL
{
	void *pool;
	OFHTTPClient *client;
	OFHTTPRequest *request;
	OFHTTPRequestReply *reply;
	OFDictionary *headers;
	OFString *contentLength;
	Class c;

	c = [self class];
	[self release];

	pool = objc_autoreleasePoolPush();

163
164
165
166
167
168
169
170







171

172
173
174
175
176
177
178

	if ([reply statusCode] != 200)
		@throw [OFHTTPRequestFailedException
		    exceptionWithClass: [request class]
			       request: request
				 reply: reply];

	self = [[reply data] retain];







	objc_autoreleasePoolPop(pool);

	return self;
}

- initWithStringRepresentation: (OFString*)string
{
	self = [super init];








|
>
>
>
>
>
>
>

>







167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190

	if ([reply statusCode] != 200)
		@throw [OFHTTPRequestFailedException
		    exceptionWithClass: [request class]
			       request: request
				 reply: reply];

	self = [[reply readDataArrayTillEndOfStream] retain];

	headers = [reply headers];
	if ((contentLength = [headers objectForKey: @"Content-Length"]) != nil)
		if ([self count] != (size_t)[contentLength decimalValue])
			@throw [OFTruncatedDataException
			    exceptionWithClass: [self class]];

	objc_autoreleasePoolPop(pool);

	return self;
}

- initWithStringRepresentation: (OFString*)string
{
	self = [super init];

Modified src/OFHTTPClient.h from [aa40337e14] to [19781d2abd].

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
 *		  received
 */
-      (void)client: (OFHTTPClient*)client
  didReceiveHeaders: (OFDictionary*)headers
	 statusCode: (int)statusCode
	    request: (OFHTTPRequest*)request;

/*!
 * @brief A callback which is called when an OFHTTPClient received data.
 *
 * This is useful for example if you want to update a status display.
 *
 * @param client The OFHTTPClient which received data
 * @param data The data the OFHTTPClient received
 * @param length The length of the data received, in bytes
 * @param request The request for which data has been received
 */
-   (void)client: (OFHTTPClient*)client
  didReceiveData: (const char*)data
	  length: (size_t)length
	 request: (OFHTTPRequest*)request;

/*!
 * @brief A callback which is called when an OFHTTPClient will follow a
 *	  redirect.
 *
 * If you want to get the headers and data for each redirect, set the number of
 * redirects to 0 and perform a new OFHTTPClient for each redirect. However,
 * this callback will not be called then and you have to look at the status code







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







57
58
59
60
61
62
63















64
65
66
67
68
69
70
 *		  received
 */
-      (void)client: (OFHTTPClient*)client
  didReceiveHeaders: (OFDictionary*)headers
	 statusCode: (int)statusCode
	    request: (OFHTTPRequest*)request;
















/*!
 * @brief A callback which is called when an OFHTTPClient will follow a
 *	  redirect.
 *
 * If you want to get the headers and data for each redirect, set the number of
 * redirects to 0 and perform a new OFHTTPClient for each redirect. However,
 * this callback will not be called then and you have to look at the status code
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

/*!
 * @brief A class for performing HTTP requests.
 */
@interface OFHTTPClient: OFObject
{
	id <OFHTTPClientDelegate> delegate;
	BOOL storesData;
	BOOL insecureRedirectsAllowed;
}

#ifdef OF_HAVE_PROPERTIES
@property (assign) id <OFHTTPClientDelegate> delegate;
@property BOOL storesData;
@property BOOL insecureRedirectsAllowed;
#endif

/*!
 * @brief Creates a new OFHTTPClient.
 *
 * @return A new, autoreleased OFHTTPClient







<





<







86
87
88
89
90
91
92

93
94
95
96
97

98
99
100
101
102
103
104

/*!
 * @brief A class for performing HTTP requests.
 */
@interface OFHTTPClient: OFObject
{
	id <OFHTTPClientDelegate> delegate;

	BOOL insecureRedirectsAllowed;
}

#ifdef OF_HAVE_PROPERTIES
@property (assign) id <OFHTTPClientDelegate> delegate;

@property BOOL insecureRedirectsAllowed;
#endif

/*!
 * @brief Creates a new OFHTTPClient.
 *
 * @return A new, autoreleased OFHTTPClient
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
/*!
 * @brief Returns whether redirects from HTTPS to HTTP will be allowed
 *
 * @return Whether redirects from HTTPS to HTTP will be allowed
 */
- (BOOL)insecureRedirectsAllowed;

/*!
 * @brief Sets whether an OFDataArray with the data should be created.
 *
 * Setting this to NO is only useful if you are using the delegate to handle the
 * data.
 *
 * @param enabled Whether to store the data in an OFDataArray
 */
- (void)setStoresData: (BOOL)enabled;

/*!
 * @brief Returns whether an OFDataArray with the date should be created.
 *
 * @return Whether an OFDataArray with the data should be created
 */
- (BOOL)storesData;

/*!
 * @brief Performs the specified HTTP request
 */
- (OFHTTPRequestReply*)performRequest: (OFHTTPRequest*)request;

/*!
 * @brief Performs the HTTP request and returns an OFHTTPRequestReply.







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







129
130
131
132
133
134
135

















136
137
138
139
140
141
142
/*!
 * @brief Returns whether redirects from HTTPS to HTTP will be allowed
 *
 * @return Whether redirects from HTTPS to HTTP will be allowed
 */
- (BOOL)insecureRedirectsAllowed;


















/*!
 * @brief Performs the specified HTTP request
 */
- (OFHTTPRequestReply*)performRequest: (OFHTTPRequest*)request;

/*!
 * @brief Performs the HTTP request and returns an OFHTTPRequestReply.

Modified src/OFHTTPClient.m from [07b706d2dd] to [9a386c8c54].

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#import "OFHTTPRequest.h"
#import "OFHTTPRequestReply.h"
#import "OFString.h"
#import "OFURL.h"
#import "OFTCPSocket.h"
#import "OFDictionary.h"
#import "OFDataArray.h"
#import "OFSystemInfo.h"

#import "OFHTTPRequestFailedException.h"
#import "OFInvalidEncodingException.h"
#import "OFInvalidFormatException.h"
#import "OFInvalidServerReplyException.h"
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"







<







23
24
25
26
27
28
29

30
31
32
33
34
35
36
#import "OFHTTPRequest.h"
#import "OFHTTPRequestReply.h"
#import "OFString.h"
#import "OFURL.h"
#import "OFTCPSocket.h"
#import "OFDictionary.h"
#import "OFDataArray.h"


#import "OFHTTPRequestFailedException.h"
#import "OFInvalidEncodingException.h"
#import "OFInvalidFormatException.h"
#import "OFInvalidServerReplyException.h"
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"
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

		*str = (firstLetter ? toupper(*str) : tolower(*str));

		firstLetter = NO;
		str++;
	}
}






















































































































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

- init
{
	self = [super init];

	storesData = YES;

	return self;
}

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

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

- (void)setInsecureRedirectsAllowed: (BOOL)allowed
{
	insecureRedirectsAllowed = allowed;
}

- (BOOL)insecureRedirectsAllowed
{
	return insecureRedirectsAllowed;
}

- (void)setStoresData: (BOOL)storesData_
{
	storesData = storesData_;
}

- (BOOL)storesData
{
	return storesData;
}

- (OFHTTPRequestReply*)performRequest: (OFHTTPRequest*)request
{
	return [self performRequest: request
			  redirects: 10];
}

- (OFHTTPRequestReply*)performRequest: (OFHTTPRequest*)request
			    redirects: (size_t)redirects
{
	void *pool = objc_autoreleasePoolPush();
	OFURL *URL = [request URL];
	OFString *scheme = [URL scheme];
	of_http_request_type_t requestType = [request requestType];
	OFDictionary *headers = [request headers];
	OFDataArray *POSTData = [request POSTData];
	OFTCPSocket *sock;
	OFHTTPRequestReply *reply;
	OFString *line, *path, *version;
	OFMutableDictionary *serverHeaders;
	OFDataArray *data;
	OFEnumerator *keyEnumerator, *objectEnumerator;
	OFString *key, *object, *contentLengthHeader;
	int status;
	const char *type = NULL;
	size_t contentLength = 0;
	BOOL chunked;
	size_t pageSize;
	char *buffer;
	size_t bytesReceived;

	if (![scheme isEqual: @"http"] && ![scheme isEqual: @"https"])
		@throw [OFUnsupportedProtocolException
		    exceptionWithClass: [self class]
				   URL: URL];

	if ([scheme isEqual: @"http"])







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







<
<
<
<
<
<
<
<
<




















<
<
<
<
<
<
<
<
<
<
















|


<

|


<
<
<
<
<







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

		*str = (firstLetter ? toupper(*str) : tolower(*str));

		firstLetter = NO;
		str++;
	}
}

@interface OFHTTPClientReply: OFHTTPRequestReply
{
	OFTCPSocket *sock;
	BOOL chunked, atEndOfStream;
	size_t toRead;
}

- initWithSocket: (OFTCPSocket*)sock;
@end

@implementation OFHTTPClientReply
- initWithSocket: (OFTCPSocket*)sock_
{
	self = [super init];

	sock = [sock_ retain];

	return self;
}

- (void)dealloc
{
	[sock release];

	[super dealloc];
}

- (void)setHeaders: (OFDictionary*)headers_
{
	[super setHeaders: headers_];

	chunked = [[headers_ objectForKey: @"Transfer-Encoding"]
	    isEqual: @"chunked"];
}

- (size_t)lowlevelReadIntoBuffer: (void*)buffer
			  length: (size_t)length
{
	if (!chunked)
		return [sock readIntoBuffer: buffer
				     length: length];

	if (toRead > 0) {
		if (length > toRead)
			length = toRead;

		length = [sock readIntoBuffer: buffer
				       length: length];

		toRead -= length;

		if (toRead == 0)
			if ([[sock readLine] length] > 0)
				@throw [OFInvalidServerReplyException
				    exceptionWithClass: [self class]];

		return length;
	} else {
		void *pool = objc_autoreleasePoolPush();
		OFString *line;
		of_range_t range;

		@try {
			line = [sock readLine];
		} @catch (OFInvalidEncodingException *e) {
			@throw [OFInvalidServerReplyException
			    exceptionWithClass: [self class]];
		}

		range = [line rangeOfString: @";"];
		if (range.location != OF_NOT_FOUND)
			line = [line substringWithRange:
			    of_range(0, range.location)];

		@try {
			toRead =
			    (size_t)[line hexadecimalValue];
		} @catch (OFInvalidFormatException *e) {
			@throw [OFInvalidServerReplyException
			    exceptionWithClass: [self class]];
		}

		if (toRead == 0) {
			[sock close];
			atEndOfStream = YES;
		}

		objc_autoreleasePoolPop(pool);

		return 0;
	}
}

- (BOOL)lowlevelIsAtEndOfStream
{
	if (!chunked)
		return [sock isAtEndOfStream];

	return atEndOfStream;
}

- (int)fileDescriptorForReading
{
	return [sock fileDescriptorForReading];
}

- (size_t)pendingBytes
{
	return [super pendingBytes] + [sock pendingBytes];
}

- (void)close
{
	[sock close];
}
@end

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










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

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

- (void)setInsecureRedirectsAllowed: (BOOL)allowed
{
	insecureRedirectsAllowed = allowed;
}

- (BOOL)insecureRedirectsAllowed
{
	return insecureRedirectsAllowed;
}











- (OFHTTPRequestReply*)performRequest: (OFHTTPRequest*)request
{
	return [self performRequest: request
			  redirects: 10];
}

- (OFHTTPRequestReply*)performRequest: (OFHTTPRequest*)request
			    redirects: (size_t)redirects
{
	void *pool = objc_autoreleasePoolPush();
	OFURL *URL = [request URL];
	OFString *scheme = [URL scheme];
	of_http_request_type_t requestType = [request requestType];
	OFDictionary *headers = [request headers];
	OFDataArray *POSTData = [request POSTData];
	OFTCPSocket *sock;
	OFHTTPClientReply *reply;
	OFString *line, *path, *version;
	OFMutableDictionary *serverHeaders;

	OFEnumerator *keyEnumerator, *objectEnumerator;
	OFString *key, *object;
	int status;
	const char *type = NULL;






	if (![scheme isEqual: @"http"] && ![scheme isEqual: @"https"])
		@throw [OFUnsupportedProtocolException
		    exceptionWithClass: [self class]
				   URL: URL];

	if ([scheme isEqual: @"http"])
175
176
177
178
179
180
181
182
183
184
185

186
187
188
189
190
191
192
	if (requestType == OF_HTTP_REQUEST_TYPE_POST)
		type = "POST";

	if ([(path = [URL path]) length] == 0)
		path = @"/";

	if ([URL query] != nil)
		[sock writeFormat: @"%s %@?%@ HTTP/1.1\r\n",
		    type, path, [URL query]];
	else
		[sock writeFormat: @"%s %@ HTTP/1.1\r\n", type, path];


	if ([URL port] == 80)
		[sock writeFormat: @"Host: %@\r\n", [URL host]];
	else
		[sock writeFormat: @"Host: %@:%d\r\n", [URL host],
		    [URL port]];








|
|

|
>







266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
	if (requestType == OF_HTTP_REQUEST_TYPE_POST)
		type = "POST";

	if ([(path = [URL path]) length] == 0)
		path = @"/";

	if ([URL query] != nil)
		[sock writeFormat: @"%s %@?%@ HTTP/%@\r\n",
		    type, path, [URL query], [request protocolVersionString]];
	else
		[sock writeFormat: @"%s %@ HTTP/%@\r\n",
		    type, path, [request protocolVersionString]];

	if ([URL port] == 80)
		[sock writeFormat: @"Host: %@\r\n", [URL host]];
	else
		[sock writeFormat: @"Host: %@:%d\r\n", [URL host],
		    [URL port]];

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
			return [self performRequest: newRequest
					  redirects: redirects - 1];
		}

		[serverHeaders setObject: value
				  forKey: key];
	}



	if ([delegate respondsToSelector:
	    @selector(client:didReceiveHeaders:statusCode:request:)])
		[delegate      client: self
		    didReceiveHeaders: serverHeaders
			   statusCode: status
			      request: request];

	data = (storesData ? [OFDataArray dataArray] : nil);
	chunked = [[serverHeaders objectForKey: @"Transfer-Encoding"]
	    isEqual: @"chunked"];

	contentLengthHeader = [serverHeaders objectForKey: @"Content-Length"];

	if (contentLengthHeader != nil) {
		contentLength = (size_t)[contentLengthHeader decimalValue];

		if (contentLength > SIZE_MAX)
			@throw [OFOutOfRangeException
			    exceptionWithClass: [self class]];
	}

	pageSize = [OFSystemInfo pageSize];
	buffer = [self allocMemoryWithSize: pageSize];
	bytesReceived = 0;
	@try {
		if (chunked) {
			for (;;) {
				void *pool2 = objc_autoreleasePoolPush();
				size_t toRead;
				of_range_t range;

				@try {
					line = [sock readLine];
				} @catch (OFInvalidEncodingException *e) {
					@throw [OFInvalidServerReplyException
					    exceptionWithClass: [self class]];
				}

				range = [line rangeOfString: @";"];
				if (range.location != OF_NOT_FOUND)
					line = [line substringWithRange:
					    of_range(0, range.location)];

				@try {
					toRead =
					    (size_t)[line hexadecimalValue];
				} @catch (OFInvalidFormatException *e) {
					@throw [OFInvalidServerReplyException
					    exceptionWithClass: [self class]];
				}

				if (toRead == 0 ||
				    (contentLengthHeader != nil &&
				    contentLength >= bytesReceived))
					break;

				while (toRead > 0) {
					size_t length = (toRead < pageSize
					    ? toRead : pageSize);

					length = [sock readIntoBuffer: buffer
							       length: length];

					if ([delegate respondsToSelector:
					    @selector(client:didReceiveData:
					    length:request:)])
						[delegate client: self
						  didReceiveData: buffer
							  length: length
							 request: request];

					objc_autoreleasePoolPop(pool2);
					pool2 = objc_autoreleasePoolPush();

					bytesReceived += length;
					[data addItems: buffer
						 count: length];

					toRead -= length;
				}

				@try {
					line = [sock readLine];
				} @catch (OFInvalidEncodingException *e) {
					@throw [OFInvalidServerReplyException
					    exceptionWithClass: [self class]];
				}

				if ([line length] > 0)
					@throw [OFInvalidServerReplyException
					    exceptionWithClass: [self class]];

				objc_autoreleasePoolPop(pool2);
			}
		} else {
			size_t length;

			while (![sock isAtEndOfStream]) {
				void *pool2;

				length = [sock readIntoBuffer: buffer
						       length: pageSize];

				pool2 = objc_autoreleasePoolPush();

				if ([delegate respondsToSelector:
				    @selector(client:didReceiveData:length:
				    request:)])
					[delegate client: self
					  didReceiveData: buffer
						  length: length
						 request: request];

				objc_autoreleasePoolPop(pool2);

				bytesReceived += length;
				[data addItems: buffer
					 count: length];

				if (contentLengthHeader != nil &&
				    bytesReceived >= contentLength)
					break;
			}
		}
	} @finally {
		[self freeMemory: buffer];
	}

	[sock close];

	/*
	 * We only want to throw on status code 200 as we will throw an
	 * OFHTTPRequestFailedException for all other status codes later.
	 */
	if (status == 200 && contentLengthHeader != nil &&
	    contentLength != bytesReceived)
		@throw [OFTruncatedDataException
		    exceptionWithClass: [self class]];

	[serverHeaders makeImmutable];

	reply = [[OFHTTPRequestReply alloc] initWithStatusCode: status
						       headers: serverHeaders
							  data: data];

	objc_autoreleasePoolPop(pool);

	[reply autorelease];

	if (status != 200)
		@throw [OFHTTPRequestFailedException
		    exceptionWithClass: [self class]
			       request: request
				 reply: reply];

	return reply;
}
@end







>
>








<
<
<
|
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<





|








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
			return [self performRequest: newRequest
					  redirects: redirects - 1];
		}

		[serverHeaders setObject: value
				  forKey: key];
	}

	[serverHeaders makeImmutable];

	if ([delegate respondsToSelector:
	    @selector(client:didReceiveHeaders:statusCode:request:)])
		[delegate      client: self
		    didReceiveHeaders: serverHeaders
			   statusCode: status
			      request: request];




	reply = [[OFHTTPClientReply alloc] initWithSocket: sock];

	[reply setProtocolVersionFromString: version];
































































































































	[reply setStatusCode: status];
	[reply setHeaders: serverHeaders];


	objc_autoreleasePoolPop(pool);

	[reply autorelease];

	if (status / 100 != 2)
		@throw [OFHTTPRequestFailedException
		    exceptionWithClass: [self class]
			       request: request
				 reply: reply];

	return reply;
}
@end

Modified src/OFHTTPRequest.h from [ffcaf67e5f] to [eeab32f289].

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
	OF_HTTP_REQUEST_TYPE_GET,
	/*! POST */
	OF_HTTP_REQUEST_TYPE_POST,
	/*! HEAD */
	OF_HTTP_REQUEST_TYPE_HEAD
} of_http_request_type_t;











/*!
 * @brief A class for storing HTTP requests.
 */
@interface OFHTTPRequest: OFObject
{
	OFURL *URL;
	of_http_request_type_t requestType;

	OFDictionary *headers;
	OFDataArray *POSTData;
	OFString *MIMEType;
	OFString *remoteAddress;
}

#ifdef OF_HAVE_PROPERTIES
@property (copy) OFURL *URL;
@property of_http_request_type_t requestType;

@property (copy) OFDictionary *headers;
@property (retain) OFDataArray *POSTData;
@property (copy) OFString *MIMEType;
@property (copy) OFString *remoteAddress;
#endif

/*!







>
>
>
>
>
>
>
>
>
>







>









>







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
	OF_HTTP_REQUEST_TYPE_GET,
	/*! POST */
	OF_HTTP_REQUEST_TYPE_POST,
	/*! HEAD */
	OF_HTTP_REQUEST_TYPE_HEAD
} of_http_request_type_t;

/*!
 * @brief The HTTP version of the HTTP request.
 */
typedef struct of_http_request_protocol_version_t {
	/*! The major of the HTTP version */
	uint8_t major;
	/*! The minor of the HTTP version */
	uint8_t minor;
} of_http_request_protocol_version_t;

/*!
 * @brief A class for storing HTTP requests.
 */
@interface OFHTTPRequest: OFObject
{
	OFURL *URL;
	of_http_request_type_t requestType;
	of_http_request_protocol_version_t protocolVersion;
	OFDictionary *headers;
	OFDataArray *POSTData;
	OFString *MIMEType;
	OFString *remoteAddress;
}

#ifdef OF_HAVE_PROPERTIES
@property (copy) OFURL *URL;
@property of_http_request_type_t requestType;
@property of_http_request_protocol_version_t protocolVersion;
@property (copy) OFDictionary *headers;
@property (retain) OFDataArray *POSTData;
@property (copy) OFString *MIMEType;
@property (copy) OFString *remoteAddress;
#endif

/*!
104
105
106
107
108
109
110





























111
112
113
114
115
116
117
/*!
 * @brief Returns the request type of the HTTP request.
 *
 * @return The request type of the HTTP request
 */
- (of_http_request_type_t)requestType;






























/*!
 * @brief Sets a dictionary with headers for the HTTP request.
 *
 * @param headers A dictionary with headers for the HTTP request
 */
- (void)setHeaders: (OFDictionary*)headers;








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
/*!
 * @brief Returns the request type of the HTTP request.
 *
 * @return The request type of the HTTP request
 */
- (of_http_request_type_t)requestType;

/*!
 * @brief Sets the protocol version of the HTTP request.
 *
 * @param protocolVersion The protocol version of the HTTP request
 */
- (void)setProtocolVersion: (of_http_request_protocol_version_t)protocolVersion;

/*!
 * @brief Returns the protocol version of the HTTP request.
 *
 * @return The protocol version of the HTTP request
 */
- (of_http_request_protocol_version_t)protocolVersion;

/*!
 * @brief Sets the protocol version of the HTTP request to the version
 *	  described by the specified string.
 *
 * @param string A string describing an HTTP version
 */
- (void)setProtocolVersionFromString: (OFString*)string;

/*!
 * @brief Returns the protocol version of the HTTP request as a string.
 *
 * @return The protocol version of the HTTP request as a string
 */
- (OFString*)protocolVersionString;

/*!
 * @brief Sets a dictionary with headers for the HTTP request.
 *
 * @param headers A dictionary with headers for the HTTP request
 */
- (void)setHeaders: (OFDictionary*)headers;

Modified src/OFHTTPRequest.m from [ca52e82353] to [69b973a377].

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
#include "config.h"

#import "OFHTTPRequest.h"
#import "OFString.h"
#import "OFURL.h"
#import "OFDictionary.h"
#import "OFDataArray.h"


#import "autorelease.h"
#import "macros.h"





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

+ (instancetype)requestWithURL: (OFURL*)URL
{
	return [[[self alloc] initWithURL: URL] autorelease];
}

- init
{
	self = [super init];

	requestType = OF_HTTP_REQUEST_TYPE_GET;



	return self;
}

- initWithURL: (OFURL*)URL_
{
	self = [self init];







>




>
>
>
>
















>
>







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
#include "config.h"

#import "OFHTTPRequest.h"
#import "OFString.h"
#import "OFURL.h"
#import "OFDictionary.h"
#import "OFDataArray.h"
#import "OFArray.h"

#import "autorelease.h"
#import "macros.h"

#import "OFInvalidFormatException.h"
#import "OFOutOfRangeException.h"
#import "OFUnsupportedVersionException.h"

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

+ (instancetype)requestWithURL: (OFURL*)URL
{
	return [[[self alloc] initWithURL: URL] autorelease];
}

- init
{
	self = [super init];

	requestType = OF_HTTP_REQUEST_TYPE_GET;
	protocolVersion.major = 1;
	protocolVersion.minor = 1;

	return self;
}

- initWithURL: (OFURL*)URL_
{
	self = [self init];
85
86
87
88
89
90
91
















































92
93
94
95
96
97
98
	requestType = requestType_;
}

- (of_http_request_type_t)requestType
{
	return requestType;
}

















































- (void)setHeaders: (OFDictionary*)headers_
{
	OF_SETTER(headers, headers_, YES, 1)
}

- (OFDictionary*)headers







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
	requestType = requestType_;
}

- (of_http_request_type_t)requestType
{
	return requestType;
}

- (void)setProtocolVersion: (of_http_request_protocol_version_t)protocolVersion_
{
	if (protocolVersion_.major != 1 || protocolVersion.minor > 1)
		@throw [OFUnsupportedVersionException
		    exceptionWithClass: [self class]
			       version: [OFString stringWithFormat: @"%u.%u",
					    protocolVersion_.major,
					    protocolVersion_.minor]];

	protocolVersion = protocolVersion_;
}

- (of_http_request_protocol_version_t)protocolVersion
{
	return protocolVersion;
}

- (void)setProtocolVersionFromString: (OFString*)string
{
	void *pool = objc_autoreleasePoolPush();
	OFArray *components = [string componentsSeparatedByString: @"."];
	intmax_t major, minor;
	of_http_request_protocol_version_t protocolVersion_;

	if ([components count] != 2)
		@throw [OFInvalidFormatException
		    exceptionWithClass: [self class]];

	major = [[components firstObject] decimalValue];
	minor = [[components lastObject] decimalValue];

	if (major < 0 || major > UINT8_MAX || minor < 0 || minor > UINT8_MAX)
		@throw [OFOutOfRangeException exceptionWithClass: [self class]];

	protocolVersion_.major = (uint8_t)major;
	protocolVersion_.minor = (uint8_t)minor;

	[self setProtocolVersion: protocolVersion_];

	objc_autoreleasePoolPop(pool);
}

- (OFString*)protocolVersionString
{
	return [OFString stringWithFormat: @"%u.%u", protocolVersion.major,
					   protocolVersion.minor];
}

- (void)setHeaders: (OFDictionary*)headers_
{
	OF_SETTER(headers, headers_, YES, 1)
}

- (OFDictionary*)headers

Modified src/OFHTTPRequestReply.h from [ddd39acc1c] to [7576232cb8].

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
 *
 * Alternatively, it may be distributed under the terms of the GNU General
 * Public License, either version 2 or 3, which can be found in the file
 * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
 * file.
 */

#import "OFObject.h"


@class OFDataArray;
@class OFDictionary;

/*!
 * @brief A class for storing a reply to an HTTP request.
 */
@interface OFHTTPRequestReply: OFObject
{

	short statusCode;
	OFDataArray *data;
	OFDictionary *headers;
}

#ifdef OF_HAVE_PROPERTIES

@property (readonly) short statusCode;
@property (readonly, copy) OFDictionary *headers;
@property (readonly, retain) OFDataArray *data;
#endif

/*!
 * @brief Creates a new OFHTTPRequestReply.
 *
 * @param status The HTTP status code replied to the request
 * @param headers The headers replied to the request

 * @param data The data replied to the request



 * @return A new OFHTTPRequestReply
 */
+ replyWithStatusCode: (short)status
	      headers: (OFDictionary*)headers
		 data: (OFDataArray*)data;


/*!
 * @brief Initializes an already allocated OFHTTPRequestReply.

 *
 * @param status The HTTP status code replied to the request


 * @param headers The headers replied to the request
 * @param data The data replied to the request



 * @return An initialized OFHTTPRequestReply
 */
- initWithStatusCode: (short)status
	     headers: (OFDictionary*)headers
		data: (OFDataArray*)data;

/*!
 * @brief Returns the state code of the reply of the HTTP request.
 *
 * @return The status code of the reply of the HTTP request
 */
- (short)statusCode;

/*!







 * @brief Returns the headers of the reply of the HTTP request.
 *
 * @return The headers of the reply of the HTTP request
 */
- (OFDictionary*)headers;

/*!
 * @brief Returns the data received for the HTTP request.
 *
 * @return The data received for the HTTP request
 */
- (OFDataArray*)data;
@end







|
>

<



|

|

>

<




>
|
|
<



|

|
|
>
|
>
>
>
|

<
<
<
>


|
>

|
>
>
|
<
>
>
>
|

<
<
|


|

|




>
>
>
>
>
>
>
|

|




|

|

|

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
 *
 * Alternatively, it may be distributed under the terms of the GNU General
 * Public License, either version 2 or 3, which can be found in the file
 * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
 * file.
 */

#import "OFStream.h"
#import "OFHTTPRequest.h"


@class OFDictionary;

/*!
 * @brief A class for representing an HTTP request reply as a stream.
 */
@interface OFHTTPRequestReply: OFStream
{
	of_http_request_protocol_version_t protocolVersion;
	short statusCode;

	OFDictionary *headers;
}

#ifdef OF_HAVE_PROPERTIES
@property of_http_request_protocol_version_t protocolVersion;
@property short statusCode;
@property (copy) OFDictionary *headers;

#endif

/*!
 * @brief Sets the protocol version of the HTTP request reply.
 *
 * @param protocolVersion The protocol version of the HTTP request reply
 */
- (void)setProtocolVersion: (of_http_request_protocol_version_t)protocolVersion;

/*!
 * @brief Returns the protocol version of the HTTP request reply.
 *
 * @return The protocol version of the HTTP request reply
 */



- (of_http_request_protocol_version_t)protocolVersion;

/*!
 * @brief Sets the protocol version of the HTTP request reply to the version
 *	  described by the specified string.
 *
 * @param string A string describing an HTTP version
 */
- (void)setProtocolVersionFromString: (OFString*)string;


/*!
 * @brief Returns the protocol version of the HTTP request reply as a string.
 *
 * @return The protocol version of the HTTP request reply as a string
 */


- (OFString*)protocolVersionString;

/*!
 * @brief Returns the status code of the reply to the HTTP request.
 *
 * @return The status code of the reply to the HTTP request
 */
- (short)statusCode;

/*!
 * @brief Sets the status code of the reply to the HTTP request.
 *
 * @param statusCode The status code of the reply to the HTTP request
 */
- (void)setStatusCode: (short)statusCode;

/*!
 * @brief Returns the headers of the reply to the HTTP request.
 *
 * @return The headers of the reply to the HTTP request
 */
- (OFDictionary*)headers;

/*!
 * @brief Returns the headers of the reply to the HTTP request.
 *
 * @param headers The headers of the reply to the HTTP request
 */
- (void)setHeaders: (OFDictionary*)headers;
@end

Modified src/OFHTTPRequestReply.m from [5a4bde7403] to [eadf4aca10].

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
 * file.
 */

#include "config.h"

#import "OFHTTPRequestReply.h"
#import "OFString.h"
#import "OFDataArray.h"
#import "OFDictionary.h"

#import "autorelease.h"
#import "macros.h"

@implementation OFHTTPRequestReply
+ replyWithStatusCode: (short)status
	      headers: (OFDictionary*)headers
		 data: (OFDataArray*)data
{
	return [[[self alloc] initWithStatusCode: status
					 headers: headers
					    data: data] autorelease];
}

- initWithStatusCode: (short)status
	     headers: (OFDictionary*)headers_
		data: (OFDataArray*)data_
{
	self = [super init];

	@try {
		statusCode = status;
		headers = [headers_ copy];
		data = [data_ retain];
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}

- (void)dealloc
{
	[headers release];
	[data release];

	[super dealloc];
}

















































- (short)statusCode
{
	return statusCode;
}






- (OFDictionary*)headers
{
	OF_GETTER(headers, YES)
}

- (OFDataArray*)data
{
	OF_GETTER(data, YES)
}

- (OFString*)description
{
	void *pool = objc_autoreleasePoolPush();
	OFString *indentedHeaders, *indentedData, *ret;

	indentedHeaders = [[headers description]
	    stringByReplacingOccurrencesOfString: @"\n"
				      withString: @"\n\t"];
	indentedData = [[data description]
	    stringByReplacingOccurrencesOfString: @"\n"
				      withString: @"\n\t"];

	ret = [[OFString alloc] initWithFormat:
	    @"<%@:\n"
	    @"\tStatus code = %d\n"
	    @"\tHeaders = %@\n"
	    @"\tData = %@\n"
	    @">",
	    [self class], statusCode, indentedHeaders, indentedData];

	objc_autoreleasePoolPop(pool);

	return [ret autorelease];
}
@end







|
|




|
|
<
<
<
<
|
<
|
|
|
<
<



<
|
<
|
<
<
<
<







<




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




>
>
>
>
>






|

|





|


<
<
<







<

|






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
 * file.
 */

#include "config.h"

#import "OFHTTPRequestReply.h"
#import "OFString.h"
#import "OFDictionary.h"
#import "OFArray.h"

#import "autorelease.h"
#import "macros.h"

#import "OFInvalidFormatException.h"
#import "OFOutOfRangeException.h"




#import "OFUnsupportedVersionException.h"


@implementation OFHTTPRequestReply
- init


{
	self = [super init];


	protocolVersion.major = 1;

	protocolVersion.minor = 1;





	return self;
}

- (void)dealloc
{
	[headers release];


	[super dealloc];
}

- (void)setProtocolVersion: (of_http_request_protocol_version_t)protocolVersion_
{
	if (protocolVersion_.major != 1 || protocolVersion.minor > 1)
		@throw [OFUnsupportedVersionException
		    exceptionWithClass: [self class]
			       version: [OFString stringWithFormat: @"%u.%u",
					    protocolVersion_.major,
					    protocolVersion_.minor]];

	protocolVersion = protocolVersion_;
}

- (of_http_request_protocol_version_t)protocolVersion
{
	return protocolVersion;
}

- (void)setProtocolVersionFromString: (OFString*)string
{
	void *pool = objc_autoreleasePoolPush();
	OFArray *components = [string componentsSeparatedByString: @"."];
	intmax_t major, minor;
	of_http_request_protocol_version_t protocolVersion_;

	if ([components count] != 2)
		@throw [OFInvalidFormatException
		    exceptionWithClass: [self class]];

	major = [[components firstObject] decimalValue];
	minor = [[components lastObject] decimalValue];

	if (major < 0 || major > UINT8_MAX || minor < 0 || minor > UINT8_MAX)
		@throw [OFOutOfRangeException exceptionWithClass: [self class]];

	protocolVersion_.major = (uint8_t)major;
	protocolVersion_.minor = (uint8_t)minor;

	[self setProtocolVersion: protocolVersion_];

	objc_autoreleasePoolPop(pool);
}

- (OFString*)protocolVersionString
{
	return [OFString stringWithFormat: @"%u.%u", protocolVersion.major,
					   protocolVersion.minor];
}

- (short)statusCode
{
	return statusCode;
}

- (void)setStatusCode: (short)statusCode_
{
	statusCode = statusCode_;
}

- (OFDictionary*)headers
{
	OF_GETTER(headers, YES)
}

- (void)setHeaders: (OFDictionary*)headers_
{
	OF_SETTER(headers, headers_, YES, YES)
}

- (OFString*)description
{
	void *pool = objc_autoreleasePoolPush();
	OFString *indentedHeaders, *ret;

	indentedHeaders = [[headers description]



	    stringByReplacingOccurrencesOfString: @"\n"
				      withString: @"\n\t"];

	ret = [[OFString alloc] initWithFormat:
	    @"<%@:\n"
	    @"\tStatus code = %d\n"
	    @"\tHeaders = %@\n"

	    @">",
	    [self class], statusCode, indentedHeaders];

	objc_autoreleasePoolPop(pool);

	return [ret autorelease];
}
@end

Modified src/OFHTTPServer.h from [4cb8dc3eba] to [3553c698ef].

28
29
30
31
32
33
34
35
36
37
38

39
40
41
42
43
44
45
@protocol OFHTTPServerDelegate <OFObject>
/*!
 * @brief This method is called when the HTTP server received a request from a
 *	  client.
 *
 * @param server The HTTP server which received the request
 * @param request The request the HTTP server received
 * @return The reply the HTTP server should send to the client
 */
- (OFHTTPRequestReply*)server: (OFHTTPServer*)server
	    didReceiveRequest: (OFHTTPRequest*)request;


#ifdef OF_HAVE_OPTIONAL_PROTOCOLS
@optional
#endif
/*!
 * @brief This method is called when the HTTP server's listening socket
 *	  encountered an exception.







|

|
|
>







28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@protocol OFHTTPServerDelegate <OFObject>
/*!
 * @brief This method is called when the HTTP server received a request from a
 *	  client.
 *
 * @param server The HTTP server which received the request
 * @param request The request the HTTP server received
 * @param reply The reply the server wants to send to the client
 */
-      (void)server: (OFHTTPServer*)server
  didReceiveRequest: (OFHTTPRequest*)request
	      reply: (OFHTTPRequestReply*)reply;

#ifdef OF_HAVE_OPTIONAL_PROTOCOLS
@optional
#endif
/*!
 * @brief This method is called when the HTTP server's listening socket
 *	  encountered an exception.

Modified src/OFHTTPServer.m from [34f30ba48f] to [3a7faef063].

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#import "OFWriteFailedException.h"

#import "macros.h"

#define BUFFER_SIZE 1024

/*
 * TODO: Add support for chunked transfer encoding.
 * FIXME: Key normalization replaces headers like "DNT" with "Dnt".
 * FIXME: Errors are not reported to the user.
 */

static const char*
status_code_to_string(short code)
{







<







37
38
39
40
41
42
43

44
45
46
47
48
49
50
#import "OFWriteFailedException.h"

#import "macros.h"

#define BUFFER_SIZE 1024

/*

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

static const char*
status_code_to_string(short code)
{
159
160
161
162
163
164
165














































































































166
167
168
169
170
171
172
		firstLetter = NO;
		tmp++;
	}

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















































































































@interface OFHTTPServer_Connection: OFObject
{
	OFTCPSocket *sock;
	OFHTTPServer *server;
	OFTimer *timer;
	enum {







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
		firstLetter = NO;
		tmp++;
	}

	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 {
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
- (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)sendReply;
@end

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







|







300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
- (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];
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
		case AWAITING_PROLOG:
			return [self parseProlog: line];
		case PARSING_HEADERS:
			if (![self parseHeaders: line])
				return NO;

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

			return YES;
		default:
			return NO;
		}







|







359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
		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;
		}
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
		return NO;

	[POSTData addItems: buffer
		     count: length];

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

		return NO;
	}








|







528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
		return NO;

	[POSTData addItems: buffer
		     count: length];

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

		return NO;
	}

448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
			   statusCode, status_code_to_string(statusCode), date,
			   [server name]];
	[sock close];

	return NO;
}

- (void)sendReply
{
	OFURL *URL;
	OFHTTPRequest *request;
	OFHTTPRequestReply *reply;
	OFDictionary *replyHeaders;
	OFDataArray *replyData;
	OFString *date;
	OFEnumerator *keyEnumerator, *valueEnumerator;
	OFString *key, *value;
	size_t pos;

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

	if (host == nil || port == 0) {







|



|
<
<
<
<
<







557
558
559
560
561
562
563
564
565
566
567
568





569
570
571
572
573
574
575
			   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) {
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
		[URL setPath: path_];
		[URL setQuery: query];
	} else
		[URL setPath: path];

	request = [OFHTTPRequest requestWithURL: URL];
	[request setRequestType: requestType];


	[request setHeaders: headers];
	[request setPOSTData: POSTData];
	[request setRemoteAddress: [sock remoteAddress]];

	reply = [[server delegate] server: server
			didReceiveRequest: request];

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

	if (reply == nil) {
		[self sendErrorAndClose: 500];
		@throw [OFInvalidArgumentException
		    exceptionWithClass: [(id)[server delegate] class]
			      selector: @selector(server:didReceiveRequest:)];
	}

	replyHeaders = [reply headers];
	replyData = [reply data];

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

	if (requestType != OF_HTTP_REQUEST_TYPE_HEAD)
		[sock writeFormat: @"Content-Length: %zu\r\n",
				   [replyData count] * [replyData itemSize]];

	keyEnumerator = [replyHeaders keyEnumerator];
	valueEnumerator = [replyHeaders 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"];

	if (requestType != OF_HTTP_REQUEST_TYPE_HEAD)
		[sock writeBuffer: [replyData items]
			   length: [replyData count] * [replyData itemSize]];
}
@end

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







>
>




<
<
|
<
<
|
<
<
<
<
<
<
|
<
<

<
<
<
<
<
<
|
<
<
<
|
<
<
<
<
<
<
|
<
<
<
<
<







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

Modified src/OFString.m from [7077269c5c] to [537b9ea7bb].

39
40
41
42
43
44
45

46
47
48
49
50
51
52
#import "OFInvalidArgumentException.h"
#import "OFInvalidEncodingException.h"
#import "OFInvalidFormatException.h"
#import "OFNotImplementedException.h"
#import "OFOpenFileFailedException.h"
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"


#import "autorelease.h"
#import "macros.h"
#import "of_asprintf.h"
#import "unicode.h"

/*







>







39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#import "OFInvalidArgumentException.h"
#import "OFInvalidEncodingException.h"
#import "OFInvalidFormatException.h"
#import "OFNotImplementedException.h"
#import "OFOpenFileFailedException.h"
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"
#import "OFTruncatedDataException.h"

#import "autorelease.h"
#import "macros.h"
#import "of_asprintf.h"
#import "unicode.h"

/*
897
898
899
900
901
902
903

904

905
906
907
908
909
910
911
- initWithContentsOfURL: (OFURL*)URL
	       encoding: (of_string_encoding_t)encoding
{
	void *pool;
	OFHTTPClient *client;
	OFHTTPRequest *request;
	OFHTTPRequestReply *reply;

	OFString *contentType;

	Class c;

	c = [self class];
	[self release];

	pool = objc_autoreleasePoolPush();








>
|
>







898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
- initWithContentsOfURL: (OFURL*)URL
	       encoding: (of_string_encoding_t)encoding
{
	void *pool;
	OFHTTPClient *client;
	OFHTTPRequest *request;
	OFHTTPRequestReply *reply;
	OFDictionary *headers;
	OFString *contentType, *contentLength;
	OFDataArray *data;
	Class c;

	c = [self class];
	[self release];

	pool = objc_autoreleasePoolPush();

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
	reply = [client performRequest: request];

	if ([reply statusCode] != 200)
		@throw [OFHTTPRequestFailedException
		    exceptionWithClass: [request class]
			       request: request
				 reply: reply];



	if (encoding == OF_STRING_ENCODING_AUTODETECT &&
	    (contentType = [[reply headers] objectForKey: @"Content-Type"])) {
		contentType = [contentType lowercaseString];

		if ([contentType hasSuffix: @"charset=utf-8"])
			encoding = OF_STRING_ENCODING_UTF_8;
		if ([contentType hasSuffix: @"charset=iso-8859-1"])
			encoding = OF_STRING_ENCODING_ISO_8859_1;
		if ([contentType hasSuffix: @"charset=iso-8859-15"])
			encoding = OF_STRING_ENCODING_ISO_8859_15;
		if ([contentType hasSuffix: @"charset=windows-1252"])
			encoding = OF_STRING_ENCODING_WINDOWS_1252;
	}

	if (encoding == OF_STRING_ENCODING_AUTODETECT)
		encoding = OF_STRING_ENCODING_UTF_8;








	self = [[c alloc] initWithCString: (char*)[[reply data] items]
				 encoding: encoding
				   length: [[reply data] count]];

	objc_autoreleasePoolPop(pool);

	return self;
}

- initWithSerialization: (OFXMLElement*)element
{
	@try {
		void *pool = objc_autoreleasePoolPush();








>
>

|















>
>
>
>
>
>
>
|

|


>







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
	reply = [client performRequest: request];

	if ([reply statusCode] != 200)
		@throw [OFHTTPRequestFailedException
		    exceptionWithClass: [request class]
			       request: request
				 reply: reply];

	headers = [reply headers];

	if (encoding == OF_STRING_ENCODING_AUTODETECT &&
	    (contentType = [headers objectForKey: @"Content-Type"]) != nil) {
		contentType = [contentType lowercaseString];

		if ([contentType hasSuffix: @"charset=utf-8"])
			encoding = OF_STRING_ENCODING_UTF_8;
		if ([contentType hasSuffix: @"charset=iso-8859-1"])
			encoding = OF_STRING_ENCODING_ISO_8859_1;
		if ([contentType hasSuffix: @"charset=iso-8859-15"])
			encoding = OF_STRING_ENCODING_ISO_8859_15;
		if ([contentType hasSuffix: @"charset=windows-1252"])
			encoding = OF_STRING_ENCODING_WINDOWS_1252;
	}

	if (encoding == OF_STRING_ENCODING_AUTODETECT)
		encoding = OF_STRING_ENCODING_UTF_8;

	data = [reply readDataArrayTillEndOfStream];

	if ((contentLength = [headers objectForKey: @"Content-Length"]) != nil)
		if ([data count] != (size_t)[contentLength decimalValue])
			@throw [OFTruncatedDataException
			    exceptionWithClass: [self class]];

	self = [[c alloc] initWithCString: (char*)[data items]
				 encoding: encoding
				   length: [data count]];

	objc_autoreleasePoolPop(pool);

	return self;
}

- initWithSerialization: (OFXMLElement*)element
{
	@try {
		void *pool = objc_autoreleasePoolPush();

Modified tests/OFHTTPClientTests.m from [1c3e517f32] to [70f5e875cd].

27
28
29
30
31
32
33

34
35
36
37
38
39
40
#import "OFHTTPRequestReply.h"
#import "OFString.h"
#import "OFTCPSocket.h"
#import "OFThread.h"
#import "OFCondition.h"
#import "OFURL.h"
#import "OFDictionary.h"

#import "OFAutoreleasePool.h"

#import "TestsAppDelegate.h"

static OFString *module = @"OFHTTPClient";
static OFCondition *cond;








>







27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#import "OFHTTPRequestReply.h"
#import "OFString.h"
#import "OFTCPSocket.h"
#import "OFThread.h"
#import "OFCondition.h"
#import "OFURL.h"
#import "OFDictionary.h"
#import "OFDataArray.h"
#import "OFAutoreleasePool.h"

#import "TestsAppDelegate.h"

static OFString *module = @"OFHTTPClient";
static OFCondition *cond;

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
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
	OFHTTPClientTestsServer *server;
	OFURL *url;
	OFHTTPClient *client;
	OFHTTPRequest *request;
	OFHTTPRequestReply *reply;


	cond = [OFCondition condition];
	[cond lock];

	server = [[[OFHTTPClientTestsServer alloc] init] autorelease];
	[server start];

	[cond wait];
	[cond unlock];

	url = [OFURL URLWithString:
	    [OFString stringWithFormat: @"http://127.0.0.1:%" @PRIu16 "/foo",
					server->port]];

	TEST(@"-[performRequest:]",
	    R(client = [OFHTTPClient client]) &&
	    R(request = [OFHTTPRequest requestWithURL: url]) &&
	    R(reply = [client performRequest: request]))

	TEST(@"Normalization of server header keys",
	     ([[reply headers] objectForKey: @"Content-Length"] != nil))





	[server join];

	[pool drain];
}
@end







>




















|
>
>
>
>






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
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
	OFHTTPClientTestsServer *server;
	OFURL *url;
	OFHTTPClient *client;
	OFHTTPRequest *request;
	OFHTTPRequestReply *reply;
	OFDataArray *data;

	cond = [OFCondition condition];
	[cond lock];

	server = [[[OFHTTPClientTestsServer alloc] init] autorelease];
	[server start];

	[cond wait];
	[cond unlock];

	url = [OFURL URLWithString:
	    [OFString stringWithFormat: @"http://127.0.0.1:%" @PRIu16 "/foo",
					server->port]];

	TEST(@"-[performRequest:]",
	    R(client = [OFHTTPClient client]) &&
	    R(request = [OFHTTPRequest requestWithURL: url]) &&
	    R(reply = [client performRequest: request]))

	TEST(@"Normalization of server header keys",
	    ([[reply headers] objectForKey: @"Content-Length"] != nil))

	TEST(@"Correct parsing of data",
	    (data = [reply readDataArrayTillEndOfStream]) &&
	    [data count] == 7 && !memcmp([data items], "foo\nbar", 7))

	[server join];

	[pool drain];
}
@end