ObjFW  Check-in [7f52d7f931]

Overview
Comment:OFHTTPRequest: Normalize server header keys.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: 7f52d7f931288591f4e81fbfd67f67318e1154e146db5b3f083d955103b64729
User & Date: js on 2011-04-22 14:56:53
Other Links: manifest | tags
Context
2011-04-22
15:00
OFHTTPRequest: Fix missing release of delegate. check-in: 838246b066 user: js tags: trunk
14:56
OFHTTPRequest: Normalize server header keys. check-in: 7f52d7f931 user: js tags: trunk
14:35
OFHTTPRequest: Make it possible to not store the data in an OFDataArray. check-in: 1cc6f3659f user: js tags: trunk
Changes

Modified src/OFHTTPRequest.m from [0e781dce42] to [b21eb615c3].

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

#include "config.h"

#define OF_HTTP_REQUEST_M

#include <string.h>


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

#import "OFHTTPRequestFailedException.h"
#import "OFInvalidServerReplyException.h"
#import "OFOutOfRangeException.h"
#import "OFTruncatedDataException.h"
#import "OFUnsupportedProtocolException.h"

#import "macros.h"

Class of_http_request_tls_socket_class = Nil;





















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








>


















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







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

#include "config.h"

#define OF_HTTP_REQUEST_M

#include <string.h>
#include <ctype.h>

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

#import "OFHTTPRequestFailedException.h"
#import "OFInvalidServerReplyException.h"
#import "OFOutOfRangeException.h"
#import "OFTruncatedDataException.h"
#import "OFUnsupportedProtocolException.h"

#import "macros.h"

Class of_http_request_tls_socket_class = Nil;

static OF_INLINE void
normalize_key(OFString *key)
{
	char *str = (char*)[key cString];
	BOOL firstLetter = YES;

	while (*str != '\0') {
		if (!isalnum(*str)) {
			firstLetter = YES;
			str++;
			continue;
		}

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

		firstLetter = NO;
		str++;
	}
}

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

182
183
184
185
186
187
188
189
190
191
192
193
194
195
196

197
198
199
200
201
202
203

		sock = [[[of_http_request_tls_socket_class alloc] init]
		    autorelease];
	}

	@try {
		OFString *line, *path;
		OFMutableDictionary *s_headers;
		OFDataArray *data;
		OFEnumerator *enumerator;
		OFString *key;
		int status;
		const char *t = NULL;
		char *buf;
		size_t bytesReceived;


		[sock connectToHost: [URL host]
			     onPort: [URL port]];

		/*
		 * Work around a bug with packet bisection in lighttpd when
		 * using HTTPS.







|







>







203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225

		sock = [[[of_http_request_tls_socket_class alloc] init]
		    autorelease];
	}

	@try {
		OFString *line, *path;
		OFMutableDictionary *serverHeaders;
		OFDataArray *data;
		OFEnumerator *enumerator;
		OFString *key;
		int status;
		const char *t = NULL;
		char *buf;
		size_t bytesReceived;
		OFString *contentLengthHeader;

		[sock connectToHost: [URL host]
			     onPort: [URL port]];

		/*
		 * Work around a bug with packet bisection in lighttpd when
		 * using HTTPS.
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
		if (status != 200 && status != 301 && status != 302 &&
		    status != 303)
			@throw [OFHTTPRequestFailedException
			    newWithClass: isa
			     HTTPRequest: self
			      statusCode: status];

		s_headers = [OFMutableDictionary dictionary];

		while ((line = [sock readLine]) != nil) {
			OFString *key, *value;
			const char *line_c = [line cString], *tmp;

			if ([line isEqual: @""])
				break;

			if ((tmp = strchr(line_c, ':')) == NULL)
				@throw [OFInvalidServerReplyException
				    newWithClass: isa];

			key = [OFString stringWithCString: line_c
						   length: tmp - line_c];


			do {
				tmp++;
			} while (*tmp == ' ');

			value = [OFString stringWithCString: tmp];

			if ((redirects > 0 && (status == 301 || status == 302 ||
			    status == 303) && [key caseInsensitiveCompare:
			    @"Location"] == OF_ORDERED_SAME) &&
			    (redirectsFromHTTPSToHTTPAllowed ||
			    [scheme isEqual: @"http"] ||
			    ![value hasPrefix: @"http://"])) {
				OFURL *new;
				BOOL follow;

				new = [OFURL URLWithString: value
					     relativeToURL: URL];

				follow = [delegate request: self
				      willFollowRedirectTo: new];

				if (!follow && delegate != nil) {
					[s_headers setObject: value
						      forKey: key];
					continue;
				}

				new = [new retain];
				[URL release];
				URL = new;

				if (status == 303) {
					requestType = OF_HTTP_REQUEST_TYPE_GET;
					[queryString release];
					queryString = nil;
				}

				[pool release];
				pool = nil;

				return [self performWithRedirects:
				    redirects - 1];
			}

			[s_headers setObject: value
				      forKey: key];
		}

		[delegate request: self
		didReceiveHeaders: s_headers
		   withStatusCode: status];

		if (storesData)
			data = [OFDataArray dataArrayWithItemSize: 1];
		else
			data = nil;








|














>








|
<













|
|




















|
|



|







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
		if (status != 200 && status != 301 && status != 302 &&
		    status != 303)
			@throw [OFHTTPRequestFailedException
			    newWithClass: isa
			     HTTPRequest: self
			      statusCode: status];

		serverHeaders = [OFMutableDictionary dictionary];

		while ((line = [sock readLine]) != nil) {
			OFString *key, *value;
			const char *line_c = [line cString], *tmp;

			if ([line isEqual: @""])
				break;

			if ((tmp = strchr(line_c, ':')) == NULL)
				@throw [OFInvalidServerReplyException
				    newWithClass: isa];

			key = [OFString stringWithCString: line_c
						   length: tmp - line_c];
			normalize_key(key);

			do {
				tmp++;
			} while (*tmp == ' ');

			value = [OFString stringWithCString: tmp];

			if ((redirects > 0 && (status == 301 || status == 302 ||
			    status == 303) && [key isEqual: @"Location"]) &&

			    (redirectsFromHTTPSToHTTPAllowed ||
			    [scheme isEqual: @"http"] ||
			    ![value hasPrefix: @"http://"])) {
				OFURL *new;
				BOOL follow;

				new = [OFURL URLWithString: value
					     relativeToURL: URL];

				follow = [delegate request: self
				      willFollowRedirectTo: new];

				if (!follow && delegate != nil) {
					[serverHeaders setObject: value
							  forKey: key];
					continue;
				}

				new = [new retain];
				[URL release];
				URL = new;

				if (status == 303) {
					requestType = OF_HTTP_REQUEST_TYPE_GET;
					[queryString release];
					queryString = nil;
				}

				[pool release];
				pool = nil;

				return [self performWithRedirects:
				    redirects - 1];
			}

			[serverHeaders setObject: value
					  forKey: key];
		}

		[delegate request: self
		didReceiveHeaders: serverHeaders
		   withStatusCode: status];

		if (storesData)
			data = [OFDataArray dataArrayWithItemSize: 1];
		else
			data = nil;

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
				[data addNItems: len
				     fromCArray: buf];
			}
		} @finally {
			[self freeMemory: buf];
		}

		if ([s_headers objectForKey: @"Content-Length"] != nil) {
			intmax_t cl;

			cl = [[s_headers objectForKey: @"Content-Length"]
			    decimalValue];

			if (cl > SIZE_MAX)
				@throw [OFOutOfRangeException
				    newWithClass: isa];

			if (cl != bytesReceived)
				@throw [OFTruncatedDataException
				    newWithClass: isa];
		}

		/*
		 * Class swizzle the dictionary to be immutable. We pass it as
		 * OFDictionary*, so it can't be modified anyway. But not
		 * swizzling it would create a real copy each time -[copy] is
		 * called.
		 */
		s_headers->isa = [OFDictionary class];

		result = [[OFHTTPRequestResult alloc]
		    initWithStatusCode: status
			       headers: s_headers
				  data: data];
	} @finally {
		[pool release];
	}

	return [result autorelease];
}







<
<
|
|
|
















|



|







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
				[data addNItems: len
				     fromCArray: buf];
			}
		} @finally {
			[self freeMemory: buf];
		}



		if ((contentLengthHeader =
		    [serverHeaders objectForKey: @"Content-Length"]) != nil) {
			intmax_t cl = [contentLengthHeader decimalValue];

			if (cl > SIZE_MAX)
				@throw [OFOutOfRangeException
				    newWithClass: isa];

			if (cl != bytesReceived)
				@throw [OFTruncatedDataException
				    newWithClass: isa];
		}

		/*
		 * Class swizzle the dictionary to be immutable. We pass it as
		 * OFDictionary*, so it can't be modified anyway. But not
		 * swizzling it would create a real copy each time -[copy] is
		 * called.
		 */
		serverHeaders->isa = [OFDictionary class];

		result = [[OFHTTPRequestResult alloc]
		    initWithStatusCode: status
			       headers: serverHeaders
				  data: data];
	} @finally {
		[pool release];
	}

	return [result autorelease];
}

Modified tests/OFHTTPRequestTests.m from [718beda726] to [53041a12f7].

23
24
25
26
27
28
29

30
31
32
33
34
35
36
#include <assert.h>

#import "OFHTTPRequest.h"
#import "OFString.h"
#import "OFThread.h"
#import "OFTCPSocket.h"
#import "OFURL.h"

#import "OFAutoreleasePool.h"

#import "TestsAppDelegate.h"

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








>







23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <assert.h>

#import "OFHTTPRequest.h"
#import "OFString.h"
#import "OFThread.h"
#import "OFTCPSocket.h"
#import "OFURL.h"
#import "OFDictionary.h"
#import "OFAutoreleasePool.h"

#import "TestsAppDelegate.h"

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

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
	if (![[client readLine] hasPrefix: @"User-Agent:"])
		assert(0);

	if (![[client readLine] isEqual: @""])
		assert(0);

	[client writeString: @"HTTP/1.0 200 OK\r\n"
			     @"Content-Length: 7\r\n"
			     @"\r\n"
			     @"foo\n"
			     @"bar"];
	[client close];

	return nil;
}







|







69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
	if (![[client readLine] hasPrefix: @"User-Agent:"])
		assert(0);

	if (![[client readLine] isEqual: @""])
		assert(0);

	[client writeString: @"HTTP/1.0 200 OK\r\n"
			     @"cONTeNT-lENgTH: 7\r\n"
			     @"\r\n"
			     @"foo\n"
			     @"bar"];
	[client close];

	return nil;
}
104
105
106
107
108
109
110



111
112
113
114
115
	    [OFString stringWithFormat: @"http://127.0.0.1:%" @PRIu16 "/foo",
					server->port]];

	TEST(@"+[requestWithURL]", (req = [OFHTTPRequest requestWithURL: url]))

	TEST(@"-[perform]", (res = [req perform]))




	[server join];

	[pool drain];
}
@end







>
>
>





105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
	    [OFString stringWithFormat: @"http://127.0.0.1:%" @PRIu16 "/foo",
					server->port]];

	TEST(@"+[requestWithURL]", (req = [OFHTTPRequest requestWithURL: url]))

	TEST(@"-[perform]", (res = [req perform]))

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

	[server join];

	[pool drain];
}
@end