File: StatusServer.m

package info (click to toggle)
gnustep-base 1.31.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,580 kB
  • sloc: objc: 239,446; ansic: 36,519; cpp: 122; sh: 112; makefile: 100; xml: 32
file content (379 lines) | stat: -rw-r--r-- 9,384 bytes parent folder | download | duplicates (2)
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
#import <Foundation/Foundation.h>

#if     GNUSTEP

#define PORT_LISTEN 1234
#define LOCATION200 @"http://localhost:1234/200"

@interface StatusServer : NSObject
{
  NSInputStream *ip;
  NSOutputStream *op;
  NSDictionary *responses;
  NSDictionary *headers;
  NSDictionary *commonHeaders;
  NSString *body;
  NSMutableData *request;
}

- (int) runTest;

@end

@implementation StatusServer

- (id)init
{
  if ((self = [super init]))
    {
      body = @"Hello\r\n";
      unsigned bodyLength = [body length];
      NSString *bl = [[NSNumber numberWithInt: bodyLength]
			    stringValue];
      NSString *date = [[NSCalendarDate date] description];
      // set up the dictionaries of responses and headers

      commonHeaders = [NSDictionary dictionaryWithObjectsAndKeys:
				    @"close",                @"Connection",
				    @"GNUstep test harness", @"Server",
				    @"text/plain",           @"Content-Type",
				    date,                    @"Date",
				    nil];
      [commonHeaders retain];
      
      responses = [NSDictionary dictionaryWithObjectsAndKeys:
				@"HTTP/1.1 200 OK", @"200",
				@"HTTP/1.1 201 Created", @"201",
				@"HTTP/1.1 204 No Content", @"204",
				@"HTTP/1.1 301 Moved Permanently", @"301",
				@"HTTP/1.1 302 Found", @"302",
				@"HTTP/1.1 303 See Other", @"303",
				@"HTTP/1.1 307 Temporary Redirect", @"307",
				@"HTTP/1.1 400 Bad Request", @"400",
				@"HTTP/1.1 401 Unauthorized", @"401",
				@"HTTP/1.1 403 Forbidden", @"403",
				@"HTTP/1.1 404 Not Found", @"404",
				@"HTTP/1.1 416 Requested Range Not Satisfiable",
				@"416",
				@"HTTP/1.1 500 Internal Server Error", @"500",
				@"HTTP/1.1 501 Not Implemented", @"501",
				nil];
      [responses retain];

      NSDictionary *header200 = [NSDictionary dictionaryWithObjectsAndKeys:
					      bl, @"Content-Length",
					      nil];
      //we can use this Location: header in header201 for the 30x, too
      NSDictionary *header201 = [NSDictionary dictionaryWithObjectsAndKeys:
					      LOCATION200, @"Location",
					      nil];
      NSDictionary *header401 = [NSDictionary dictionaryWithObjectsAndKeys:
					      @"Basic realm=\"GNUstep\"", 
					      @"WWW-Authenticate",
					      nil];

      headers = [NSDictionary dictionaryWithObjectsAndKeys:
			      header200, @"200",
			      header201, @"201",
			      header201, @"301",
			      header201, @"302",
			      header201, @"303",
			      header201, @"307",
			      header401, @"401",
			      nil];
      [headers retain];

      ip = nil;
      op = nil;
      request = nil;
    }
  return self;
}

- (void)dealloc
{
  [headers release];
  [commonHeaders release];
  [responses release];
  if (nil != ip)
    {
      [ip release];
    }
  if (nil != op)
    {
      [op release];
    }
  if (nil != request)
    {
      [request release];
    }

  [super dealloc];
}

- (int)runTest
{
  NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
  NSRunLoop      *rl = [NSRunLoop currentRunLoop];
  NSHost         *host = [NSHost hostWithName: @"localhost"];
  NSStream       *serverStream;
  unsigned       port = [[defs stringForKey: @"Port"] intValue];

  if (0 == port) port = PORT_LISTEN;

  serverStream = [GSServerStream serverStreamToAddr: [host address]
				 port: port];

  if (nil == serverStream)
    {
      NSLog(@"Failed to create server stream");
      return 1;
    }

  [serverStream setDelegate: self];
  [serverStream scheduleInRunLoop: rl forMode: NSDefaultRunLoopMode];
  [serverStream open];

  /* Tell main test program we are ready to handle a request
   */
  [[NSFileHandle fileHandleWithStandardOutput] writeData:
    [@"Ready" dataUsingEncoding: NSASCIIStringEncoding]];

  // run for one minute, then quit
  [rl runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 60]];
  return 0;
}

- (void) stream: (NSStream *)theStream handleEvent: (NSStreamEvent) streamEvent
{
  NSRunLoop *rl = [NSRunLoop currentRunLoop];

  switch (streamEvent)
    {
    case NSStreamEventHasBytesAvailable:
      {
	if (theStream != ip)
	  {
	    if (ip != nil)
	      {
		[ip close];
		[ip removeFromRunLoop: rl forMode: NSDefaultRunLoopMode];
		ip = nil;
	      }
	    if (op != nil)
	      {
		[op close];
		[op removeFromRunLoop: rl forMode: NSDefaultRunLoopMode];
		op = nil;
	      }
	    [(GSServerStream *)theStream acceptWithInputStream: &ip
			       outputStream: &op];

	    if (ip)
	      {
		RETAIN(ip);
		RETAIN(op);
		[ip scheduleInRunLoop: rl forMode: NSDefaultRunLoopMode];
		[ip setDelegate: self];
		[op setDelegate: self];
		[ip open];
	      }
	    else
	      {
		NSLog(@"Received nothing from accept");
	      }
	  }
	else if (theStream == ip)
	  {
	    uint8_t	buf[1024];
	    unsigned	len;
	    BOOL	done = NO;

	    if (nil != request)
	      {
		[request release];
	      }
	    request = [[NSMutableData alloc] initWithCapacity: sizeof(buf)];
	    len = [ip read: buf maxLength: sizeof(buf)];
	    if (len > 0)
	      {
		const char	*bytes;

	        [request appendBytes: buf length: len];
	        len = [request length];
		bytes = (const char*)[request bytes];
		if (len > 3 && memcmp(bytes+len-4, "\r\n\r\n", 4) == 0)
		  {
		    done = YES;
		  }
	      }
	    else
	      {
		done = YES; 	// EOF or error
	      }
	    if (done == YES)
	      {
		[op open];
		[op scheduleInRunLoop: rl forMode: NSDefaultRunLoopMode];
		[ip close];
		[ip removeFromRunLoop: rl forMode: NSDefaultRunLoopMode];
		ip = nil;
	      }
	  }
	break;
      }

    case NSStreamEventHasSpaceAvailable:
      {
	NSString *wholeReq, *req, *retCode, *hdr;
	NSMutableData *response;
	NSArray *components;
	NSDictionary *specificHeaders;
	NSEnumerator *en;

	int statusCode;

	NSAssert(op == theStream, NSInternalInconsistencyException);
	if (nil == request)
	  {
	    NSLog(@"Attempt to send response without a request");
	    return;
	  }
	wholeReq = [[[NSString alloc] initWithData: request 
				      encoding: NSASCIIStringEncoding]
				      autorelease];
	response = [[[NSMutableData alloc] init] autorelease];
	components = [wholeReq componentsSeparatedByString: @"\r\n"];
	// the actual request is the first line
	req = [components objectAtIndex: 0];

	if ([req rangeOfString: @"GET"].location == NSNotFound
	  && [req rangeOfString: @"HEAD"].location == NSNotFound)
	  {
	    retCode = @"501"; // HTTP 501: Not Implemented
	  }
	else
	  {
	    retCode = [[req componentsSeparatedByString: @" "]
			objectAtIndex: 1];
	    // trim the leading slash
	    retCode = [[retCode pathComponents] objectAtIndex: 1];
	  }
	if ([responses objectForKey: retCode] == nil)
	  {
	    retCode = @"404"; // HTTP 404: Not Found
	  }
	// build the response
	[response appendBytes: [[responses objectForKey: retCode] cString]
		  length: [[responses objectForKey: retCode] length]];
	[response appendBytes: "\r\n" length: 2];

	en = [commonHeaders keyEnumerator];
	while ((hdr = [en nextObject]) != nil)
	  {
	    [response appendBytes: [hdr cString] length: [hdr length]];
	    [response appendBytes: ": " length: 2];
	    hdr = [commonHeaders objectForKey: hdr];
	    [response appendBytes: [hdr cString] length: [hdr length]];
	    [response appendBytes: "\r\n" length: 2];
	  }

	specificHeaders = [headers objectForKey: retCode];
	if (specificHeaders != nil)
	  {
	    en = [specificHeaders keyEnumerator];
	    while ((hdr = [en nextObject]) != nil)
	      {
		[response appendBytes: [hdr cString] length: [hdr length]];
		[response appendBytes: ": " length: 2];
		hdr = [specificHeaders objectForKey: hdr];
		[response appendBytes: [hdr cString] length: [hdr length]];
		[response appendBytes: "\r\n" length: 2];
	      }
	  }
	[response appendBytes: "\r\n" length: 2];
	//do we need to add the body part?

	if([req rangeOfString: @"HEAD"].location == NSNotFound)
	  {
	    statusCode = [retCode intValue];
	
	    switch (statusCode)
	      {
	      case 200:
	      case 400:
	      case 401:
	      case 403:
	      case 404:
	      case 500:
	      case 501:
		[response appendBytes: [body cString] length: [body length]];
		break;
	      default:
		break;
	      }
	  }
	// send this response and close the stream
	[op write: [response bytes] maxLength: [response length]];
	[op close];
	[op removeFromRunLoop: rl forMode: NSDefaultRunLoopMode];
	op = nil;
	break;
      }

    case NSStreamEventEndEncountered:
      {
	[theStream close];
	[theStream removeFromRunLoop: rl forMode: NSDefaultRunLoopMode];
	if (theStream == ip) ip = nil;
	if (theStream == op) op = nil;
	break;
      }

    case NSStreamEventErrorOccurred:
      {
	int code = [[theStream streamError] code];

	NSLog(@"Error %d on stream %p", code, theStream);
	[theStream close];
	[theStream removeFromRunLoop: rl forMode: NSDefaultRunLoopMode];
	if (theStream == ip) ip = nil;
	if (theStream == op) op = nil;
	break;
      }

    case NSStreamEventOpenCompleted:
      break;

    default:
      NSLog (@"Event %d on stream %p unknown", streamEvent, theStream);
      break;
    }
}

@end

int main (int argc, char **argv)
{
  int result;
  NSAutoreleasePool   *arp = [NSAutoreleasePool new];
  
  result = [[[[StatusServer alloc] init] autorelease] runTest];

  [arp release]; arp = nil;
  return result;
}

#else

int main (int argc, char **argv)
{
  NSAutoreleasePool   *arp = [NSAutoreleasePool new];
  
  NSLog(@"StatesServer not implemented on non-GNUstep systems");

  [arp release]; arp = nil;
  return 0;
}

#endif