File: WOHTTPConnection.m

package info (click to toggle)
sope 5.12.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 16,588 kB
  • sloc: objc: 169,223; sh: 3,823; ansic: 3,409; javascript: 446; python: 318; makefile: 185
file content (831 lines) | stat: -rw-r--r-- 21,826 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
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
/*
  Copyright (C) 2000-2005 SKYRIX Software AG

  This file is part of SOPE.

  SOPE is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the
  Free Software Foundation; either version 2, or (at your option) any
  later version.

  SOPE is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
  License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with SOPE; see the file COPYING.  If not, write to the
  Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  02111-1307, USA.
*/

#include <NGObjWeb/WOHTTPConnection.h>
#include <NGObjWeb/WOCookie.h>
#include <NGObjWeb/WORequest.h>
#include <NGObjWeb/WOResponse.h>
#include <NGObjWeb/WOCookie.h>
#include <NGObjWeb/WORunLoop.h>
#include <NGStreams/NGActiveSSLSocket.h>
#include <NGStreams/NGStreams.h>
#include <NGStreams/NGCTextStream.h>
#include <NGStreams/NGBufferedStream.h>
#include <NGStreams/NGNet.h>
#include <NGHttp/NGHttp.h>
#include <NGMime/NGMime.h>
#import <Foundation/Foundation.h>
#include "WOSimpleHTTPParser.h"
#include "WOHttpAdaptor/WORecordRequestStream.h"

@interface WOHTTPConnection(Privates)
- (BOOL)_connect;
- (void)_disconnect;
@end

@interface WOCookie(Privates)
+ (id)cookieWithString:(NSString *)_string;
@end

NSString *WOHTTPConnectionCanReadResponse = @"WOHTTPConnectionCanReadResponse";

@interface NSURL(SocketAddress)
- (id)socketAddressForURL;
- (BOOL)shouldUseWOProxyServer;
@end

@interface WOHTTPConnection(Privates2)
+ (NSString *)proxyServer;
+ (NSURL *)proxyServerURL;
+ (NSArray *)noProxySuffixes;
@end

@implementation WOHTTPConnection

static Class SSLSocketClass  = Nil;
static BOOL  useSimpleParser = YES;
static NSString *proxyServer = nil;
static NSArray  *noProxy     = nil;
static BOOL doDebug   = NO;
static BOOL logStream = NO;

+ (void)initialize {
  NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
  static BOOL didInit = NO;
  if (didInit) return;
  didInit = YES;

  useSimpleParser = [ud boolForKey:@"WOHTTPConnectionUseSimpleParser"];
  proxyServer     = [ud stringForKey:@"WOProxyServer"];
  noProxy         = [ud arrayForKey:@"WONoProxySuffixes"];
  doDebug         = [ud boolForKey:@"WODebugHTTPConnection"];
  logStream       = [ud boolForKey:@"WODebugHTTPConnectionLogStream"];
}

+ (NSString *)proxyServer {
  return proxyServer;
}
+ (NSURL *)proxyServerURL {
  NSString *ps;

  ps = [self proxyServer];
  if ([ps length] == 0)
    return nil;

  return [NSURL URLWithString:ps];
}
+ (NSArray *)noProxySuffixes {
  return noProxy;
}

- (id)initWithNSURL:(NSURL *)_url {
  if ((self = [super init])) {
    self->url      = [_url retain];
    self->useSSL   = [[_url scheme] isEqualToString:@"https"];
    self->useProxy = [_url shouldUseWOProxyServer];

    if (self->useSSL) {
      static BOOL didCheck = NO;
      if (!didCheck) {
	didCheck = YES;
	SSLSocketClass = NSClassFromString(@"NGActiveSSLSocket");
      }
    }
  }
  return self;
}

- (id)initWithURL:(id)_url {
  NSURL *lurl;

  /* create an NSURL object if necessary */
  lurl = [_url isKindOfClass:[NSURL class]]
    ? _url
    : [NSURL URLWithString:[_url stringValue]];
  if (lurl == nil) {
    if (doDebug)
      [self logWithFormat:@"could not construct URL from object '%@' !", _url];
    [self release];
    return nil;
  }
  if (doDebug)
    [self logWithFormat:@"init with URL: %@", lurl];
  return [self initWithNSURL:lurl];
}

- (id)initWithHost:(NSString *)_hostName onPort:(unsigned int)_port
  secure:(BOOL)_flag
{
  NSString *s;

  s = [NSString stringWithFormat:@"http%s://%@:%i/",
		  _flag ? "s" : "", _hostName,
		  _port == 0 ? (_flag?443:80) : _port];
  return [self initWithURL:s];
}
- (id)initWithHost:(NSString *)_hostName onPort:(unsigned int)_port {
  return [self initWithHost:_hostName onPort:_port secure:NO];
}
- (id)init {
  return [self initWithHost:@"localhost" onPort:80 secure:NO];
}

- (void)dealloc {
  [self->lastException release];
  [self->log      release];
  [self->io       release];
  [self->socket   release];
  [self->url      release];
  [super dealloc];
}

/* error handling */

- (NSException *)lastException {
  return self->lastException;
}

- (BOOL)isDebuggingEnabled {
  return doDebug ? YES : NO;
}
- (NSString *)loggingPrefix {
  /* improve perf ... */
  if (self->url) {
    return [NSString stringWithFormat:@"WOHTTP[0x%p]<%@>",
		       self, [self->url absoluteString]];
  }
  else
    return [NSString stringWithFormat:@"WOHTTP[0x%p]", self];
}

/* accessors */

- (NSString *)hostName {
  NSString* ret;

  ret = [self->url host];
  if([self->url port])
    ret = [ret stringByAppendingFormat: @":%@", [self->url port]];
  return ret;
}

/* IO */

- (BOOL)_connect {
  id<NGSocketAddress> address;

  [self _disconnect];

#if DEBUG
  NSAssert(self->socket == nil, @"socket still available after disconnect");
  NSAssert(self->io == nil,     @"IO stream still available after disconnect");
#endif

  if (self->useSSL) {
    if (SSLSocketClass == Nil) {
      /* no SSL support is available */
      static BOOL didLog = NO;
      if (!didLog) {
	didLog = YES;
	NSLog(@"NOTE: SSL support is not available !");
      }
      return NO;
    }
  }

  if (self->useProxy) {
    NSURL *purl;

    purl = [[self class] proxyServerURL];
    address = [purl socketAddressForURL];
  }
  else {
    address = [self->url socketAddressForURL];
  }
  if (address == nil) {
    [self debugWithFormat:@"got no address for connect .."];
    return NO;
  }

  NS_DURING {
    self->socket = self->useSSL
      ? [SSLSocketClass socketConnectedToAddress:address
                                  withVerifyMode: TLSVerifyDefault]
      : [NGActiveSocket socketConnectedToAddress:address];
  }
  NS_HANDLER {
#if 0
    fprintf(stderr, "couldn't create socket: %s\n",
            [[localException description] cString]);
#endif
    ASSIGN(self->lastException, localException);
    self->socket = nil;
  }
  NS_ENDHANDLER;

  if (self->socket == nil) {
    [self debugWithFormat:@"socket is not setup: %@", [self lastException]];
    return NO;
  }

  if (![self->socket isConnected]) {
    self->socket = nil;
    [self debugWithFormat:@"socket is not connected .."];
    return NO;
  }

  self->socket = [self->socket retain];

  [(NGActiveSocket *)self->socket setSendTimeout:[self sendTimeout]];
  [(NGActiveSocket *)self->socket setReceiveTimeout:[self receiveTimeout]];

  if (self->socket != nil) {
    NGBufferedStream *bStr;

    bStr = [NGBufferedStream alloc]; // keep gcc happy
    bStr = [bStr initWithSource:self->socket];
    if (logStream) {
      self->log = [WORecordRequestStream alloc]; // keep gcc happy
      self->log = [(WORecordRequestStream *)self->log initWithSource:bStr];
    }
    else
      self->log = nil;

    self->io = [NGCTextStream alloc]; // keep gcc happy
    self->io = [self->io initWithSource:
		      (id)(self->log != nil ? self->log : (id)bStr)];
    [bStr release]; bStr = nil;
  }

  return YES;
}
- (void)_disconnect {
  [self->log release]; self->log = nil;
  [self->io  release]; self->io  = nil;

  NS_DURING
    (void)[self->socket shutdown];
  NS_HANDLER {}
  NS_ENDHANDLER;

  [self->socket release]; self->socket = nil;
}

/* logging IO */

- (void)logRequest:(WORequest *)_response data:(NSData *)_data {
  if (_data == nil) return;

#if 1
  NSLog(@"request is\n");
  fflush(stderr);
  fwrite([_data bytes], 1, [_data length], stderr);
  fflush(stderr);
  fprintf(stderr,"\n");
  fflush(stderr);
#endif
}
- (void)logResponse:(WOResponse *)_response data:(NSData *)_data {
  if (_data == nil) return;

#if 1
  NSLog(@"response is\n");
  fflush(stderr);
  fwrite([_data bytes], 1, [_data length], stderr);
  fflush(stderr);
  fprintf(stderr,"\n");
  fflush(stderr);
#endif
}

/* sending/receiving HTTP */

- (BOOL)sendRequest:(WORequest *)_request {
  NSData *content;
  BOOL isok = YES;

  if (doDebug)
    [self debugWithFormat:@"send request: %@", _request];

  if (![self->socket isConnected]) {
    if (![self _connect]) {
      /* could not connect */
      if (doDebug)
        [self debugWithFormat:@"  could not connect socket"];
      return NO;
    }
    /* now connected */
  }

  content = [_request content];

  /* write request line (eg 'GET / HTTP/1.0') */
  if (doDebug)
    [self debugWithFormat:@"  method: %@", [_request method]];

  if (isok) isok = [self->io writeString:[_request method]];
  if (isok) isok = [self->io writeString:@" "];

  if (self->useProxy) {
    if (isok)
      // TODO: check whether this produces a '//' (may need to strip uri)
      isok = [self->io writeString:[self->url absoluteString]];
    [self debugWithFormat:@"  wrote proxy start ..."];
  }
  if (isok) isok = [self->io writeString:[_request uri]];

  if (isok) isok = [self->io writeString:@" "];
  if (isok) isok = [self->io writeString:[_request httpVersion]];
  if (isok) isok = [self->io writeString:@"\r\n"];

  /* set content-length header */

  if ([content length] > 0) {
    [_request setHeader:[NSString stringWithFormat:@"%d", (int)[content length]]
              forKey:@"content-length"];
  }

  if ([[self->url scheme] hasPrefix:@"http"]) {
    /* host header */

    if (isok) isok = [self->io writeString:@"Host: "];
    if (isok) isok = [self->io writeString:[self hostName]];
    if (isok) isok = [self->io writeString:@"\r\n"];
    [self debugWithFormat:@"  wrote host header: %@", [self hostName]];
  }

  /* write request headers */

  if (isok) {
    NSEnumerator *fields;
    NSString *fieldName;
    int cnt;

    fields = [[_request headerKeys] objectEnumerator];
    cnt = 0;
    while (isok && (fieldName = [fields nextObject])) {
      NSEnumerator *values;
      id value;

      if ([fieldName length] == 4) {
	if ([fieldName isEqualToString:@"host"])
	  /* did already write host ... */
	  continue;
	if ([fieldName isEqualToString:@"Host"])
	  /* did already write host ... */
	  continue;
      }

      values = [[_request headersForKey:fieldName] objectEnumerator];

      while ((value = [values nextObject]) && isok) {
        if (isok) isok = [self->io writeString:fieldName];
        if (isok) isok = [self->io writeString:@": "];
        if (isok) isok = [self->io writeString:value];
        if (isok) isok = [self->io writeString:@"\r\n"];
        cnt++;
      }
    }
    [self debugWithFormat:@"  wrote %i request headers ...", cnt];
  }

  /* write some required headers */

  if ([_request headerForKey:@"accept"] == nil) {
    if (isok) isok = [self->io writeString:@"Accept: */*\r\n"];
    [self debugWithFormat:@"  wrote accept header ..."];
  }
  if ([_request headerForKey:@"user-agent"] == nil) {
    if (isok) {
      static NSString *s = nil;
      if (s == nil) {
	s = [[NSString alloc] initWithFormat:@"User-Agent: SOPE/%i.%i.%i\r\n",
			      SOPE_MAJOR_VERSION, SOPE_MINOR_VERSION,
			      SOPE_SUBMINOR_VERSION];
      }
      isok = [self->io writeString:s];
    }
    [self debugWithFormat:@"  wrote user-agent header ..."];
  }

  /* write cookie headers */

  if ([[_request cookies] count] > 0 && isok) {
    NSEnumerator *cookies;
    WOCookie     *cookie;
    BOOL         isFirst;
    int cnt;

    [self->io writeString:@"set-cookie: "];
    cnt = 0;
    cookies = [[_request cookies] objectEnumerator];
    isFirst = YES;
    while (isok && (cookie = [cookies nextObject])) {
      if (isFirst) isFirst = NO;
      else if (isok) isok = [self->io writeString:@"; "];

      if (isok) isok = [self->io writeString:[cookie stringValue]];
      cnt ++;
    }
    if (isok) isok = [self->io writeString:@"\r\n"];
    [self debugWithFormat:@"  wrote %i cookies ...", cnt];
  }

  /* flush request header on socket */

  if (isok) isok = [self->io writeString:@"\r\n"];
  if (isok) isok = [self->io flush];
  [self debugWithFormat:@"  flushed HTTP header."];

  /* write content */

  if ([content length] > 0) {
    [self debugWithFormat:@"  writing HTTP entity (length=%i).",
            [content length]];

    if ([content isKindOfClass:[NSString class]]) {
      if (isok) isok = [self->io writeString:(NSString *)content];
    }
    else if ([content isKindOfClass:[NSData class]]) {
      if (isok) isok = [[self->io source]
                         safeWriteBytes:[content bytes]
                         count:[content length]];
    }
    else {
      if (isok) isok = [self->io writeString:[content description]];
    }
    if (isok) isok = [self->io flush];
  }
  else if (doDebug) {
    [self debugWithFormat:@"  no HTTP entity to write ..."];
  }

  if (logStream)
    [self logRequest:_request data:[self->log writeLog]];
  [self->log resetWriteLog];

  [self debugWithFormat:@"=> finished:\n  url:  %@\n  sock: %@",
          self->url, self->socket];
  if (!isok) {
    ASSIGN(self->lastException, [self->socket lastException]);
    [self->socket shutdown];
    return NO;
  }

  if (![self->socket isConnected])
    return NO;

  return YES;
}

- (NSException *)handleResponseParsingError:(NSException *)_exception {
    fprintf(stderr, "%s: caught: %s\n",
            __PRETTY_FUNCTION__,
            [[_exception description] cString]);
    return nil;
}

- (WOResponse *)readResponse {
  /* TODO: split up method */
  WOResponse *response;

  *(&response) = nil;

  if (self->socket == nil) {
    [self debugWithFormat:@"no socket available for reading response ..."];
    return nil;
  }

  [self debugWithFormat:@"parsing response from socket: %@", self->socket];

  if (useSimpleParser) {
    WOSimpleHTTPParser *parser;

    [self debugWithFormat:@"  using simple HTTP parser ..."];

    parser = [[WOSimpleHTTPParser alloc] initWithStream:[self->io source]];
    if (parser == nil)
      return nil;
    parser = [parser autorelease];

    if ((response = [parser parseResponse]) == nil) {
      if (doDebug)
        [self debugWithFormat:@"parsing failed: %@", [parser lastException]];
    }
  }
  else {
    NGHttpMessageParser *parser;
    NGHttpResponse *mresponse;
    NGMimeType     *ctype;
    id body;

    *(&mresponse) = nil;

    if ((parser = [[[NGHttpMessageParser alloc] init] autorelease]) == nil)
      return nil;

    [self debugWithFormat:@"  using MIME HTTP parser (complex parser) ..."];

    NS_DURING {
      [parser setDelegate:self];
      mresponse = [parser parseResponseFromStream:self->socket];
    }
    NS_HANDLER
      [[self handleResponseParsingError:localException] raise];
    NS_ENDHANDLER;

    [self debugWithFormat:@"finished parsing response: %@", mresponse];

    /* transform parsed MIME response to WOResponse */

    body = [mresponse body];
    if (body == nil) body = [NSData data];

    response = [[[WOResponse alloc] init] autorelease];
    [response setHTTPVersion:[mresponse httpVersion]];
    [response setStatus:[mresponse statusCode]];
    [response setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:
                                          self,      @"NGHTTPConnection",
                                          mresponse, @"NGMimeResponse",
                                          body,      @"NGMimeBody",
                                          nil]];

    { /* check content-type */
      id value;

      value = [[mresponse valuesOfHeaderFieldWithName:@"content-type"]
  	                nextObject];
      if (value) {
        NSString *charset;

        ctype = [NGMimeType mimeType:[value stringValue]];
        charset = [[ctype valueOfParameter:@"charset"] lowercaseString];

        if ([charset length] == 0) {
          /* autodetect charset ... */

          if ([[ctype type] isEqualToString:@"text"]) {
            if ([[ctype subType] isEqualToString:@"xml"]) {
              /* default XML encoding is UTF-8 */
              [response setContentEncoding:NSUTF8StringEncoding];
            }
          }
        }
        else {
          NSStringEncoding enc;

          enc = [NGMimeType stringEncodingForCharset:charset];
          [response setContentEncoding:enc];
        }

        [response setHeader:[ctype stringValue] forKey:@"content-type"];

      }
      else {
        ctype = [NGMimeType mimeType:@"application/octet-stream"];
      }
    }

    /* check content */

    if ([body isKindOfClass:[NSData class]]) {
      [response setContent:body];
    }
    else if ([body isKindOfClass:[NSString class]]) {
      NSData *data;

      data = [body dataUsingEncoding:[response contentEncoding]];
      if (data)
        [response setContent:data];
    }
    else if (body) {
      /* generate data from structured body .. */
      NGMimeBodyGenerator *gen;
      NSData *data;

      gen = [[[NGMimeBodyGenerator alloc] init] autorelease];
      data = [gen generateBodyOfPart:body
                  additionalHeaders:nil
                  delegate:self];
      [response setContent:data];
    }

    { /* transfer headers */
      NSEnumerator *names;
      NSString     *name;

      names = [mresponse headerFieldNames];
      while ((name = [names nextObject])) {
        NSEnumerator *values;
        id           value;

        if ([name isEqualToString:@"content-type"])
          continue;
        if ([name isEqualToString:@"set-cookie"])
          continue;

        values = [mresponse valuesOfHeaderFieldWithName:name];
        while ((value = [values nextObject])) {
          value = [value stringValue];
          [response appendHeader:value forKey:name];
        }
      }
    }

    { /* transfer cookies */
      NSEnumerator *cookies;
      NGHttpCookie *mcookie;

      cookies = [mresponse valuesOfHeaderFieldWithName:@"set-cookie"];

      while ((mcookie = [cookies nextObject])) {
        WOCookie *woCookie;

        if (![mcookie isKindOfClass:[NGHttpCookie class]]) {
          /* parse cookie */
          woCookie = [WOCookie cookieWithString:[mcookie stringValue]];
        }
        else {
          woCookie = [WOCookie cookieWithName:[mcookie cookieName]
                               value:[mcookie value]
                               path:[mcookie path]
                               domain:[mcookie domainName]
                               expires:[mcookie expireDate]
                               isSecure:[mcookie needsSecureChannel]];
        }
        if (woCookie == nil) {
          [self logWithFormat:
		  @"Couldn't create WOCookie from NGHttp cookie: %@",
                  mcookie];
          // could not create cookie
          continue;
        }

        [self debugWithFormat:@"adding cookie: %@", woCookie];

        [response addCookie:woCookie];
      }
    }
  }

  if (logStream)
    [self logResponse:response data:[self->log readLog]];
  [self->log resetReadLog];

  if (doDebug)
    [self debugWithFormat:@"processed response: %@", response];

  /* check keep-alive */
  {
    NSString *conn;

    conn = [response headerForKey:@"connection"];
    conn = [conn lowercaseString];

    if ([conn isEqualToString:@"close"]) {
      [self setKeepAliveEnabled:NO];
      [self _disconnect];
    }
    else if ([conn isEqualToString:@"keep-alive"]) {
      [self setKeepAliveEnabled:YES];
    }
    else {
      [self setKeepAliveEnabled:NO];
      [self _disconnect];
    }
  }

  return response;
}

- (void)setKeepAliveEnabled:(BOOL)_flag {
  self->keepAlive = _flag;
}
- (BOOL)keepAliveEnabled {
  return self->keepAlive;
}

/* timeouts */

- (void)setConnectTimeout:(int)_seconds {
  self->connectTimeout = _seconds;
}
- (int)connectTimeout {
  return self->connectTimeout;
}

- (void)setReceiveTimeout:(int)_seconds {
  self->receiveTimeout = _seconds;
}
- (int)receiveTimeout {
  return self->receiveTimeout;
}

- (void)setSendTimeout:(int)_seconds {
  self->sendTimeout = _seconds;
}
- (int)sendTimeout {
  return self->sendTimeout;
}

/* description */

- (NSString *)description {
  NSMutableString *str;

  str = [NSMutableString stringWithCapacity:128];
  [str appendFormat:@"<%@[0x%p]:", NSStringFromClass([self class]), self];

  if (self->url)      [str appendFormat:@" url=%@", self->url];
  if (self->useProxy) [str appendString:@" proxy"];
  if (self->useSSL)   [str appendString:@" SSL"];

  if (self->socket) [str appendFormat:@" socket=%@", self->socket];

  [str appendString:@">"];
  return str;
}

@end /* WOHTTPConnection */

@implementation NSURL(SocketAddress)

- (id)socketAddressForURL {
  NSString *s;

  s = [self scheme];

  if ([s isEqualToString:@"http"]) {
    int p;

    s = [self host];
    if ([s length] == 0) s = @"localhost";
    p = [[self port] intValue];

    return [NGInternetSocketAddress addressWithPort:p == 0 ? 80 : p onHost:s];
  }
  else if ([s isEqualToString:@"https"]) {
    int p;

    s = [self host];
    if ([s length] == 0) s = @"localhost";
    p = [[self port] intValue];

    return [NGInternetSocketAddress addressWithPort:p == 0 ? 443 : p onHost:s];
  }
  else if ([s isEqualToString:@"unix"] || [s isEqualToString:@"file"]) {
    return [NGLocalSocketAddress addressWithPath:[self path]];
  }
  return nil;
}

- (BOOL)shouldUseWOProxyServer {
  if ([[self scheme] hasPrefix:@"http"]) {
    NSString *h;

    if ((h = [self host]) == nil)
      return NO;

    if ([h isEqualToString:@"127.0.0.1"])
      return NO;
    if ([h isEqualToString:@"localhost"])
      return NO;

    if ([[WOHTTPConnection proxyServer] length] > 0) {
      NSEnumerator *e;
      NSString *suffix;
      BOOL     useProxy;

      useProxy = YES;
      e = [[WOHTTPConnection noProxySuffixes] objectEnumerator];
      while ((suffix = [e nextObject])) {
        if ([h hasSuffix:suffix]) {
          useProxy = NO;
          break;
        }
      }
      return useProxy;
    }
  }
  return NO;
}

@end /* NSURL(SocketAddress) */