-
Notifications
You must be signed in to change notification settings - Fork 3
/
listing3.html
executable file
·552 lines (474 loc) · 18.1 KB
/
listing3.html
1
2
3
4
5
6
7
8
9
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
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
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
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
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<!-- BEGIN META TAG INFO -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="home" href="http://developer.apple.com/">
<link rel="find" href="http://developer.apple.com/search/">
<link rel="stylesheet" type="text/css" href="../../documentation/css/adcstyle.css" title="fonts">
<script language="JavaScript" src="../../documentation/js/adc.js" type="text/javascript"></script>
<!-- END META TAG INFO -->
<!-- BEGIN TITLE -->
<title>CocoaHTTPServer - /HTTPServer.m</title>
<!-- END TITLE -->
<script language="JavaScript">
function JumpToNewPage() {
window.location=document.scpopupmenu.gotop.value;
return true;
}
</script>
</head>
<!-- BEGIN BODY OPEN -->
<body>
<!--END BODY OPEN -->
<!-- START CENTER OPEN -->
<center>
<!-- END CENTER OPEN -->
<!-- BEGIN LOGO AND SEARCH -->
<!--#include virtual="/includes/adcnavbar"-->
<!-- END LOGO AND SEARCH -->
<!-- START BREADCRUMB -->
<div id="breadcrumb">
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td scope="row"><img width="340" height="10" src="images/1dot.gif" alt=""></td>
<td><img width="340" height="10" src="images/1dot.gif" alt=""></td>
</tr>
<tr valign="middle">
<td align="left" colspan="2">
<a href="http://developer.apple.com/">ADC Home</a> > <a href="../../referencelibrary/index.html">Reference Library</a> > <a href="../../samplecode/index.html">Sample Code</a> > <a href="../../samplecode/Cocoa/index.html">Cocoa</a> > <a href="../../samplecode/Cocoa/idxNetworking-date.html">Networking</a> > <A HREF="javascript:location.replace('index.html');">CocoaHTTPServer</A> >
</td>
</tr>
<tr>
<td colspan="2" scope="row"><img width="680" height="35" src="images/1dot.gif" alt=""></td>
</tr>
</table>
</div>
<!-- END BREADCRUMB -->
<!-- START MAIN CONTENT -->
<!-- START TITLE GRAPHIC AND INTRO-->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td><h1><div id="pagehead">CocoaHTTPServer</div></h1></td>
</tr>
</table>
<!-- END TITLE GRAPHIC AND INTRO -->
<!-- START WIDE COLUMN -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td id="scdetails">
<h2>/HTTPServer.m</h2>
<form name="scpopupmenu" onSubmit="return false;" method=post>
<p><strong>View Source Code:</strong>
<select name="gotop" onChange="JumpToNewPage();" style="width:340px"><option selected value="ingnore">Select File</option>
<option value="listing1.html">/CocoaHTTPServer.m</option>
<option value="listing2.html">/HTTPServer.h</option>
<option value="listing3.html">/HTTPServer.m</option>
<option value="listing4.html">/TCPServer.h</option>
<option value="listing5.html">/TCPServer.m</option></select>
</p>
</form>
<p><strong><a href="CocoaHTTPServer.zip">Download Sample</a></strong> (“CocoaHTTPServer.zip”, 28.3K)<BR>
<strong><a href="CocoaHTTPServer.dmg">Download Sample</a></strong> (“CocoaHTTPServer.dmg”, 84.0K)</p>
<!--
<p><strong><a href="#">Download Sample</a></strong> (“filename.sit”, 500K)</p>
-->
</td>
</tr>
<tr>
<td scope="row"><img width="680" height="10" src="images/1dot.gif" alt=""><br>
<img height="1" width="680" src="images/1dot_919699.gif" alt=""><br>
<img width="680" height="20" src="images/1dot.gif" alt=""></td>
</tr>
<tr>
<td scope="row">
<!--googleon: index -->
<pre class="sourcecodebox">#import "HTTPServer.h"
@implementation HTTPServer
- (id)init {
connClass = [HTTPConnection self];
return self;
}
- (void)dealloc {
[super dealloc];
}
- (Class)connectionClass {
return connClass;
}
- (void)setConnectionClass:(Class)value {
connClass = value;
}
- (NSURL *)documentRoot {
return docRoot;
}
- (void)setDocumentRoot:(NSURL *)value {
if (docRoot != value) {
[docRoot release];
docRoot = [value copy];
}
}
// Converts the TCPServer delegate notification into the HTTPServer delegate method.
- (void)handleNewConnectionFromAddress:(NSData *)addr inputStream:(NSInputStream *)istr outputStream:(NSOutputStream *)ostr {
HTTPConnection *connection = [[connClass alloc] initWithPeerAddress:addr inputStream:istr outputStream:ostr forServer:self];
[connection setDelegate:[self delegate]];
if ([self delegate] && [[self delegate] respondsToSelector:@selector(HTTPServer:didMakeNewConnection:)]) {
[[self delegate] HTTPServer:self didMakeNewConnection:connection];
}
// The connection at this point is turned loose to exist on its
// own, and not released or autoreleased. Alternatively, the
// HTTPServer could keep a list of connections, and HTTPConnection
// would have to tell the server to delete one at invalidation
// time. This would perhaps be more correct and ensure no
// spurious leaks get reported by the tools, but HTTPServer
// has nothing further it wants to do with the HTTPConnections,
// and would just be "owning" the connections for form.
}
@end
@implementation HTTPConnection
- (id)init {
[self dealloc];
return nil;
}
- (id)initWithPeerAddress:(NSData *)addr inputStream:(NSInputStream *)istr outputStream:(NSOutputStream *)ostr forServer:(HTTPServer *)serv {
peerAddress = [addr copy];
server = serv;
istream = [istr retain];
ostream = [ostr retain];
[istream setDelegate:self];
[ostream setDelegate:self];
[istream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:(id)kCFRunLoopCommonModes];
[ostream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:(id)kCFRunLoopCommonModes];
[istream open];
[ostream open];
isValid = YES;
return self;
}
- (void)dealloc {
[self invalidate];
[peerAddress release];
[super dealloc];
}
- (id)delegate {
return delegate;
}
- (void)setDelegate:(id)value {
delegate = value;
}
- (NSData *)peerAddress {
return peerAddress;
}
- (HTTPServer *)server {
return server;
}
- (HTTPServerRequest *)nextRequest {
unsigned idx, cnt = requests ? [requests count] : 0;
for (idx = 0; idx < cnt; idx++) {
id obj = [requests objectAtIndex:idx];
if ([obj response] == nil) {
return obj;
}
}
return nil;
}
- (BOOL)isValid {
return isValid;
}
- (void)invalidate {
if (isValid) {
isValid = NO;
[istream close];
[ostream close];
[istream release];
[ostream release];
istream = nil;
ostream = nil;
[ibuffer release];
[obuffer release];
ibuffer = nil;
obuffer = nil;
[requests release];
requests = nil;
[self release];
// This last line removes the implicit retain the HTTPConnection
// has on itself, given by the HTTPServer when it abandoned the
// new connection.
}
}
// YES return means that a complete request was parsed, and the caller
// should call again as the buffered bytes may have another complete
// request available.
- (BOOL)processIncomingBytes {
CFHTTPMessageRef working = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
CFHTTPMessageAppendBytes(working, [ibuffer bytes], [ibuffer length]);
// This "try and possibly succeed" approach is potentially expensive
// (lots of bytes being copied around), but the only API available for
// the server to use, short of doing the parsing itself.
// HTTPConnection does not handle the chunked transfer encoding
// described in the HTTP spec. And if there is no Content-Length
// header, then the request is the remainder of the stream bytes.
if (CFHTTPMessageIsHeaderComplete(working)) {
NSString *contentLengthValue = [(NSString *)CFHTTPMessageCopyHeaderFieldValue(working, (CFStringRef)@"Content-Length") autorelease];
unsigned contentLength = contentLengthValue ? [contentLengthValue intValue] : 0;
NSData *body = [(NSData *)CFHTTPMessageCopyBody(working) autorelease];
unsigned bodyLength = [body length];
if (contentLength <= bodyLength) {
NSData *newBody = [NSData dataWithBytes:[body bytes] length:contentLength];
[ibuffer setLength:0];
[ibuffer appendBytes:([body bytes] + contentLength) length:(bodyLength - contentLength)];
CFHTTPMessageSetBody(working, (CFDataRef)newBody);
} else {
CFRelease(working);
return NO;
}
} else {
return NO;
}
HTTPServerRequest *request = [[HTTPServerRequest alloc] initWithRequest:working connection:self];
if (!requests) {
requests = [[NSMutableArray alloc] init];
}
[requests addObject:request];
if (delegate && [delegate respondsToSelector:@selector(HTTPConnection:didReceiveRequest:)]) {
[delegate HTTPConnection:self didReceiveRequest:request];
} else {
[self performDefaultRequestHandling:request];
}
CFRelease(working);
return YES;
}
- (void)processOutgoingBytes {
// The HTTP headers, then the body if any, then the response stream get
// written out, in that order. The Content-Length: header is assumed to
// be properly set in the response. Outgoing responses are processed in
// the order the requests were received (required by HTTP).
// Write as many bytes as possible, from buffered bytes, response
// headers and body, and response stream.
if (![ostream hasSpaceAvailable]) {
return;
}
unsigned olen = [obuffer length];
if (0 < olen) {
int writ = [ostream write:[obuffer bytes] maxLength:olen];
// buffer any unwritten bytes for later writing
if (writ < olen) {
memmove([obuffer mutableBytes], [obuffer mutableBytes] + writ, olen - writ);
[obuffer setLength:olen - writ];
return;
}
[obuffer setLength:0];
}
unsigned cnt = requests ? [requests count] : 0;
HTTPServerRequest *req = (0 < cnt) ? [requests objectAtIndex:0] : nil;
CFHTTPMessageRef cfresp = req ? [req response] : NULL;
if (!cfresp) return;
if (!obuffer) {
obuffer = [[NSMutableData alloc] init];
}
if (!firstResponseDone) {
firstResponseDone = YES;
NSData *serialized = [(NSData *)CFHTTPMessageCopySerializedMessage(cfresp) autorelease];
unsigned olen = [serialized length];
if (0 < olen) {
int writ = [ostream write:[serialized bytes] maxLength:olen];
if (writ < olen) {
// buffer any unwritten bytes for later writing
[obuffer setLength:(olen - writ)];
memmove([obuffer mutableBytes], [serialized bytes] + writ, olen - writ);
return;
}
}
}
NSInputStream *respStream = [req responseBodyStream];
if (respStream) {
if ([respStream streamStatus] == NSStreamStatusNotOpen) {
[respStream open];
}
// read some bytes from the stream into our local buffer
[obuffer setLength:16 * 1024];
int read = [respStream read:[obuffer mutableBytes] maxLength:[obuffer length]];
[obuffer setLength:read];
}
if (0 == [obuffer length]) {
// When we get to this point with an empty buffer, then the
// processing of the response is done. If the input stream
// is closed or at EOF, then no more requests are coming in.
if (delegate && [delegate respondsToSelector:@selector(HTTPConnection:didSendResponse:)]) {
[delegate HTTPConnection:self didSendResponse:req];
}
[requests removeObjectAtIndex:0];
firstResponseDone = NO;
if ([istream streamStatus] == NSStreamStatusAtEnd && [requests count] == 0) {
[self invalidate];
}
return;
}
olen = [obuffer length];
if (0 < olen) {
int writ = [ostream write:[obuffer bytes] maxLength:olen];
// buffer any unwritten bytes for later writing
if (writ < olen) {
memmove([obuffer mutableBytes], [obuffer mutableBytes] + writ, olen - writ);
}
[obuffer setLength:olen - writ];
}
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)streamEvent {
switch(streamEvent) {
case NSStreamEventHasBytesAvailable:;
uint8_t buf[16 * 1024];
uint8_t *buffer = NULL;
unsigned int len = 0;
if (![istream getBuffer:&buffer length:&len]) {
int amount = [istream read:buf maxLength:sizeof(buf)];
buffer = buf;
len = amount;
}
if (0 < len) {
if (!ibuffer) {
ibuffer = [[NSMutableData alloc] init];
}
[ibuffer appendBytes:buffer length:len];
}
do {} while ([self processIncomingBytes]);
break;
case NSStreamEventHasSpaceAvailable:;
[self processOutgoingBytes];
break;
case NSStreamEventEndEncountered:;
[self processIncomingBytes];
if (stream == ostream) {
// When the output stream is closed, no more writing will succeed and
// will abandon the processing of any pending requests and further
// incoming bytes.
[self invalidate];
}
break;
case NSStreamEventErrorOccurred:;
NSLog(@"HTTPServer stream error: %@", [stream streamError]);
break;
default:
break;
}
}
- (void)performDefaultRequestHandling:(HTTPServerRequest *)mess {
CFHTTPMessageRef request = [mess request];
NSString *vers = [(id)CFHTTPMessageCopyVersion(request) autorelease];
if (!vers || ![vers isEqual:(id)kCFHTTPVersion1_1]) {
CFHTTPMessageRef response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, 505, NULL, (CFStringRef)vers); // Version Not Supported
[mess setResponse:response];
CFRelease(response);
return;
}
NSString *method = [(id)CFHTTPMessageCopyRequestMethod(request) autorelease];
if (!method) {
CFHTTPMessageRef response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, 400, NULL, kCFHTTPVersion1_1); // Bad Request
[mess setResponse:response];
CFRelease(response);
return;
}
if ([method isEqual:@"GET"] || [method isEqual:@"HEAD"]) {
NSURL *uri = [(NSURL *)CFHTTPMessageCopyRequestURL(request) autorelease];
NSURL *url = [NSURL URLWithString:[uri path] relativeToURL:[server documentRoot]];
NSData *data = [NSData dataWithContentsOfURL:url];
if (!data) {
CFHTTPMessageRef response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, 404, NULL, kCFHTTPVersion1_1); // Not Found
[mess setResponse:response];
CFRelease(response);
return;
}
CFHTTPMessageRef response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1); // OK
CFHTTPMessageSetHeaderFieldValue(response, (CFStringRef)@"Content-Length", (CFStringRef)[NSString stringWithFormat:@"%d", [data length]]);
if ([method isEqual:@"GET"]) {
CFHTTPMessageSetBody(response, (CFDataRef)data);
}
[mess setResponse:response];
CFRelease(response);
return;
}
CFHTTPMessageRef response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, 405, NULL, kCFHTTPVersion1_1); // Method Not Allowed
[mess setResponse:response];
CFRelease(response);
}
@end
@implementation HTTPServerRequest
- (id)init {
[self dealloc];
return nil;
}
- (id)initWithRequest:(CFHTTPMessageRef)req connection:(HTTPConnection *)conn {
connection = conn;
request = (CFHTTPMessageRef)CFRetain(req);
return self;
}
- (void)dealloc {
if (request) CFRelease(request);
if (response) CFRelease(response);
[responseStream release];
[super dealloc];
}
- (HTTPConnection *)connection {
return connection;
}
- (CFHTTPMessageRef)request {
return request;
}
- (CFHTTPMessageRef)response {
return response;
}
- (void)setResponse:(CFHTTPMessageRef)value {
if (value != response) {
if (response) CFRelease(response);
response = (CFHTTPMessageRef)CFRetain(value);
if (response) {
// check to see if the response can now be sent out
[connection processOutgoingBytes];
}
}
}
- (NSInputStream *)responseBodyStream {
return responseStream;
}
- (void)setResponseBodyStream:(NSInputStream *)value {
if (value != responseStream) {
[responseStream release];
responseStream = [value retain];
}
}
@end
</pre>
<!--googleoff: index -->
</td>
</tr>
</table>
<!-- END WIDE COLUMN -->
<!-- END MAIN CONTENT -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td><div style="width: 100%; height: 1px; background-color: #919699; margin-top: 5px; margin-bottom: 15px"></div></td>
</tr>
<tr>
<td align="center"><br/>
<table border="0" cellpadding="0" cellspacing="0" class="graybox">
<tr>
<th>Did this document help you?</th>
</tr>
<tr>
<td>
<div style="margin-bottom: 8px"><a href="http://developer.apple.com/feedback/?v=1&url=/samplecode/CocoaHTTPServer/listing3.html%3Fid%3DDTS10003604-1.0&media=dvd" target=_new>Yes</a>: Tell us what works for you.</div>
<div style="margin-bottom: 8px"><a href="http://developer.apple.com/feedback/?v=2&url=/samplecode/CocoaHTTPServer/listing3.html%3Fid%3DDTS10003604-1.0&media=dvd" target=_new>It’s good, but:</a> Report typos, inaccuracies, and so forth.</div>
<div><a href="http://developer.apple.com/feedback/?v=3&url=/samplecode/CocoaHTTPServer/listing3.html%3Fid%3DDTS10003604-1.0&media=dvd" target=_new>It wasn’t helpful</a>: Tell us what would have helped.</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- START BOTTOM APPLE NAVIGATION -->
<!--#include virtual="/includes/footer"-->
<!-- END BOTTOM APPLE NAVIGATION -->
<!-- START CENTER CLOSE -->
</center>
<!-- END CENTER CLOSE -->
</body>
</html>