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 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 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 961 962 963 964 965 966 967 968 969 970 971
|
/* Implementation for NSHTTPCookie for GNUstep
Copyright (C) 2006 Software Foundation, Inc.
Written by: Richard Frith-Macdonald <rfm@gnu.org>
Date: 2006
This file is part of the GNUstep Base Library.
This library 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 of the License, or (at your option) any later version.
This library 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 this library; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110 USA.
*/
/*
Try to handle cookies via the original Netscape specification
(http://web.archive.org/web/20070805052634/http://wp.netscape.com/newsref/std/cookie_spec.html)
and the official RFC2965 (http://tools.ietf.org/html/rfc2965).
Header fields named "Set-Cookie" are processed using either the original
spec or RFC2965. "Set-Cookie2" fields use the RFC spec. There are some
crazy things to be aware of though. Multiple cookies can be specified in the
same header and are separated by a comma. However, cookies themselves can
also contain commas, most notably in the Expires field (which is not quoted
and can contain spaces as well). The last key/value does not have to have a
semi-colon, so this can be tricky to parse if another cookie occurs
after this (See GSCookieStrings).
*/
#import "common.h"
#define EXPOSE_NSHTTPCookie_IVARS 1
#import "GSURLPrivate.h"
#import "Foundation/NSSet.h"
#import "Foundation/NSValue.h"
#import "Foundation/NSString.h"
#import "Foundation/NSCalendarDate.h"
#import "GNUstepBase/Unicode.h"
static NSString * const HTTPCookieHTTPOnly = @"HTTPOnly";
// Internal data storage
typedef struct {
NSDictionary *_properties;
} Internal;
#define this ((Internal*)(self->_NSHTTPCookieInternal))
#define inst ((Internal*)(o->_NSHTTPCookieInternal))
/* Bitmap of characters considered white space if in an old style property
* list. This is the same as the set given by the isspace() function in the
* POSIX locale, but (for cross-locale portability of property list files)
* is fixed, rather than locale dependent.
*/
static const unsigned char whitespace[32] = {
'\x00',
'\x3f',
'\x00',
'\x00',
'\x01',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
'\x00',
};
#define IS_BIT_SET(a,i) ((((a) & (1<<(i)))) > 0)
#define GS_IS_WHITESPACE(X) IS_BIT_SET(whitespace[(X)/8], (X) % 8)
static id GSPropertyListFromCookieFormat(NSString *string, int version);
static NSMutableArray *GSCookieStrings(NSString *string);
@implementation NSHTTPCookie
+ (id) allocWithZone: (NSZone*)z
{
NSHTTPCookie *o = [super allocWithZone: z];
if (o != nil)
{
o->_NSHTTPCookieInternal = NSZoneCalloc(z, 1, sizeof(Internal));
}
return o;
}
+ (id) cookieWithProperties: (NSDictionary *)properties
{
NSHTTPCookie *o;
o = [[self alloc] initWithProperties: properties];
return AUTORELEASE(o);
}
+ (NSMutableArray *) _parseField: (NSString *)field
forHeader: (NSString *)header
andURL: (NSURL *)url
{
int version;
NSString *defaultPath;
NSString *defaultDomain;
NSMutableArray *cookies;
NSUInteger count;
if ([header isEqual: @"Set-Cookie"])
{
version = 0;
}
else if ([header isEqual: @"Set-Cookie2"])
{
version = 1;
}
else
{
return nil;
}
defaultDomain = [url host];
defaultPath = [url path];
if ([[url absoluteString] hasSuffix: @"/"] == NO)
{
defaultPath = [defaultPath stringByDeletingLastPathComponent];
}
cookies = GSCookieStrings(field);
count = [cookies count];
/* We could use an NSScanner here, but this string could contain all
sorts of odd stuff. It's not quite a property list either - it has
dates and also could have tokens without values. */
while (count-- > 0)
{
NSHTTPCookie *cookie;
NSMutableDictionary *dict;
NSString *onecookie = [cookies objectAtIndex: count];
NS_DURING
dict = GSPropertyListFromCookieFormat(onecookie, version);
NS_HANDLER
dict = nil;
NS_ENDHANDLER
if ([dict count])
{
if ([dict objectForKey: NSHTTPCookiePath] == nil)
{
[dict setObject: defaultPath forKey: NSHTTPCookiePath];
}
if ([dict objectForKey: NSHTTPCookieDomain] == nil)
{
[dict setObject: defaultDomain forKey: NSHTTPCookieDomain];
}
cookie = [NSHTTPCookie cookieWithProperties: dict];
if (cookie)
{
[cookies replaceObjectAtIndex: count withObject: cookie];
}
else
{
[cookies removeObjectAtIndex: count];
}
}
}
return cookies;
}
+ (NSArray *) cookiesWithResponseHeaderFields: (NSDictionary *)headerFields
forURL: (NSURL *)URL
{
NSEnumerator *henum = [headerFields keyEnumerator];
NSMutableArray *a = [NSMutableArray array];
NSString *header;
while ((header = [henum nextObject]))
{
NSMutableArray *suba
= [self _parseField: [headerFields objectForKey: header]
forHeader: header andURL: URL];
if (suba)
[a addObjectsFromArray: suba];
}
return a;
}
+ (NSDictionary *) requestHeaderFieldsWithCookies: (NSArray *)cookies
{
int version;
NSString *field;
NSHTTPCookie *ck;
NSEnumerator *ckenum = [cookies objectEnumerator];
if ([cookies count] == 0)
{
NSLog(@"NSHTTPCookie requestHeaderFieldWithCookies: empty array");
return nil;
}
/* Assume these cookies all came from the same URL so we format based
on the version of the first. */
field = nil;
version = [(NSHTTPCookie *)[cookies objectAtIndex: 0] version];
if (version)
field = @"$Version=\"1\"";
while ((ck = [ckenum nextObject]))
{
NSString *str;
str = [NSString stringWithFormat: @"%@=%@", [ck name], [ck value]];
if (field)
field = [field stringByAppendingFormat: @"; %@", str];
else
field = str;
if (version && [ck path])
field = [field stringByAppendingFormat: @"; $Path=\"%@\"", [ck path]];
}
return [NSDictionary dictionaryWithObject: field forKey: @"Cookie"];
}
- (NSString *) comment
{
return [this->_properties objectForKey: NSHTTPCookieComment];
}
- (NSURL *) commentURL
{
return [this->_properties objectForKey: NSHTTPCookieCommentURL];
}
- (void) dealloc
{
if (this != 0)
{
RELEASE(this->_properties);
NSZoneFree([self zone], this);
}
[super dealloc];
}
- (NSString *) domain
{
return [this->_properties objectForKey: NSHTTPCookieDomain];
}
- (NSDate *) expiresDate
{
return [this->_properties objectForKey: NSHTTPCookieExpires];
}
- (BOOL) _isValidProperty: (NSString *)prop
{
return ([prop length]
&& [prop rangeOfString: @"\n"].location == NSNotFound);
}
- (id) initWithProperties: (NSDictionary *)properties
{
NSMutableDictionary *rawProps;
if ((self = [super init]) == nil)
return nil;
/* Check a few values. Based on Mac OS X tests. */
if (![self _isValidProperty: [properties objectForKey: NSHTTPCookiePath]]
|| ![self _isValidProperty: [properties objectForKey: NSHTTPCookieDomain]]
|| ![self _isValidProperty: [properties objectForKey: NSHTTPCookieName]]
|| ![self _isValidProperty: [properties objectForKey: NSHTTPCookieValue]]
)
{
[self release];
return nil;
}
rawProps = [[properties mutableCopy] autorelease];
if ([rawProps objectForKey: @"Created"] == nil)
{
NSInteger seconds;
NSDate *now;
/* Round to whole seconds, so that a serialization/deserialisation
* cycle produces an identical object whic hcan be used to eliminate
* duplicates.
*/
seconds = [NSDate timeIntervalSinceReferenceDate];
now = [NSDate dateWithTimeIntervalSinceReferenceDate: seconds];
[rawProps setObject: now forKey: @"Created"];
}
if ([rawProps objectForKey: NSHTTPCookieExpires] == nil
|| [[rawProps objectForKey: NSHTTPCookieExpires]
isKindOfClass: [NSDate class]] == NO)
{
[rawProps setObject: [NSNumber numberWithBool: YES]
forKey: NSHTTPCookieDiscard];
}
this->_properties = [rawProps copy];
return self;
}
- (BOOL) isSecure
{
return [[this->_properties objectForKey: NSHTTPCookieSecure] boolValue];
}
- (BOOL) isHTTPOnly
{
return [[this->_properties objectForKey: HTTPCookieHTTPOnly] boolValue];
}
- (BOOL) isSessionOnly
{
return [[this->_properties objectForKey: NSHTTPCookieDiscard] boolValue];
}
- (NSString *) name
{
return [this->_properties objectForKey: NSHTTPCookieName];
}
- (NSString *) path
{
return [this->_properties objectForKey: NSHTTPCookiePath];
}
- (NSArray *) portList
{
return [[this->_properties objectForKey: NSHTTPCookiePort]
componentsSeparatedByString: @","];
}
- (NSDictionary *) properties
{
return this->_properties;
}
- (NSString *) value
{
return [this->_properties objectForKey: NSHTTPCookieValue];
}
- (NSUInteger) version
{
return [[this->_properties objectForKey: NSHTTPCookieVersion] integerValue];
}
- (NSString *) description
{
return [NSString stringWithFormat: @"<NSHTTPCookie %p: %@=%@>", self,
[self name], [self value]];
}
- (NSUInteger) hash
{
return [[self properties] hash];
}
- (BOOL) isEqual: (id)other
{
return [[other properties] isEqual: [self properties]];
}
@end
#define inrange(ch,min,max) ((ch)>=(min) && (ch)<=(max))
#define char2num(ch) \
inrange(ch,'0','9') \
? ((ch)-0x30) \
: (inrange(ch,'a','f') \
? ((ch)-0x57) : ((ch)-0x37))
typedef struct {
const unsigned char *ptr;
unsigned end;
unsigned pos;
unsigned lin;
NSString *err;
int opt;
BOOL key;
BOOL old;
} pldata;
/*
* Returns YES if there is any non-whitespace text remaining.
*/
static BOOL skipSpace(pldata *pld)
{
unsigned char c;
while (pld->pos < pld->end)
{
c = pld->ptr[pld->pos];
if (GS_IS_WHITESPACE(c) == NO)
{
return YES;
}
if (c == '\n')
{
pld->lin++;
}
pld->pos++;
}
pld->err = @"reached end of string";
return NO;
}
static inline id parseQuotedString(pldata* pld)
{
unsigned start = ++pld->pos;
unsigned escaped = 0;
unsigned shrink = 0;
BOOL hex = NO;
NSString *obj;
while (pld->pos < pld->end)
{
unsigned char c = pld->ptr[pld->pos];
if (escaped)
{
if (escaped == 1 && c >= '0' && c <= '7')
{
escaped = 2;
hex = NO;
}
else if (escaped == 1 && (c == 'u' || c == 'U'))
{
escaped = 2;
hex = YES;
}
else if (escaped > 1)
{
if (hex && isxdigit(c))
{
shrink++;
escaped++;
if (escaped == 6)
{
escaped = 0;
}
}
else if (c >= '0' && c <= '7')
{
shrink++;
escaped++;
if (escaped == 4)
{
escaped = 0;
}
}
else
{
pld->pos--;
escaped = 0;
}
}
else
{
escaped = 0;
}
}
else
{
if (c == '\\')
{
escaped = 1;
shrink++;
}
else if (c == '"')
{
break;
}
}
if (c == '\n')
pld->lin++;
pld->pos++;
}
if (pld->pos >= pld->end)
{
pld->err = @"reached end of string while parsing quoted string";
return nil;
}
if (pld->pos - start - shrink == 0)
{
obj = @"";
}
else
{
unsigned length;
unichar *chars;
unichar *temp = NULL;
unsigned int temp_length = 0;
unsigned j;
unsigned k;
if (!GSToUnicode(&temp, &temp_length, &pld->ptr[start],
pld->pos - start, NSUTF8StringEncoding,
NSDefaultMallocZone(), 0))
{
pld->err = @"invalid utf8 data while parsing quoted string";
return nil;
}
length = temp_length - shrink;
chars = NSAllocateCollectable(sizeof(unichar) * length, 0);
escaped = 0;
hex = NO;
for (j = 0, k = 0; j < temp_length; j++)
{
unichar c = temp[j];
if (escaped)
{
if (escaped == 1 && c >= '0' && c <= '7')
{
chars[k] = c - '0';
hex = NO;
escaped++;
}
else if (escaped == 1 && (c == 'u' || c == 'U'))
{
chars[k] = 0;
hex = YES;
escaped++;
}
else if (escaped > 1)
{
if (hex && isxdigit(c))
{
chars[k] <<= 4;
chars[k] |= char2num(c);
escaped++;
if (escaped == 6)
{
escaped = 0;
k++;
}
}
else if (c >= '0' && c <= '7')
{
chars[k] <<= 3;
chars[k] |= (c - '0');
escaped++;
if (escaped == 4)
{
escaped = 0;
k++;
}
}
else
{
escaped = 0;
j--;
k++;
}
}
else
{
escaped = 0;
switch (c)
{
case 'a' : chars[k] = '\a'; break;
case 'b' : chars[k] = '\b'; break;
case 't' : chars[k] = '\t'; break;
case 'r' : chars[k] = '\r'; break;
case 'n' : chars[k] = '\n'; break;
case 'v' : chars[k] = '\v'; break;
case 'f' : chars[k] = '\f'; break;
default : chars[k] = c; break;
}
k++;
}
}
else
{
chars[k] = c;
if (c == '\\')
{
escaped = 1;
}
else
{
k++;
}
}
}
NSZoneFree(NSDefaultMallocZone(), temp);
length = k;
obj = [NSString alloc];
obj = [obj initWithCharactersNoCopy: chars
length: length
freeWhenDone: YES];
}
pld->pos++;
return obj;
}
/* In cookies, keys are terminated by '=' and values are terminated by ';'
or and EOL */
static inline id parseUnquotedString(pldata *pld, char endChar)
{
unsigned start = pld->pos;
unsigned i;
unsigned length;
id obj;
unichar *chars;
while (pld->pos < pld->end)
{
if ((pld->ptr[pld->pos]) == endChar)
break;
pld->pos++;
}
length = pld->pos - start;
chars = NSAllocateCollectable(sizeof(unichar) * length, 0);
for (i = 0; i < length; i++)
{
chars[i] = pld->ptr[start + i];
}
{
obj = [NSString alloc];
obj = [obj initWithCharactersNoCopy: chars
length: length
freeWhenDone: YES];
}
return obj;
}
static BOOL
_setCookieKey(NSMutableDictionary *dict, NSString *key, NSString *value)
{
if ([dict count] == 0)
{
/* This must be the name=value pair */
if ([value length] == 0)
return NO;
[dict setObject: key forKey: NSHTTPCookieName];
[dict setObject: value forKey: NSHTTPCookieValue];
return YES;
}
if ([[key lowercaseString] isEqual: @"comment"])
[dict setObject: value forKey: NSHTTPCookieComment];
else if ([[key lowercaseString] isEqual: @"commenturl"])
[dict setObject: value forKey: NSHTTPCookieCommentURL];
else if ([[key lowercaseString] isEqual: @"discard"])
[dict setObject: [NSNumber numberWithBool: YES]
forKey: NSHTTPCookieDiscard];
else if ([[key lowercaseString] isEqual: @"domain"])
[dict setObject: value forKey: NSHTTPCookieDomain];
else if ([[key lowercaseString] isEqual: @"expires"])
{
NSDate *expireDate;
expireDate = [NSCalendarDate dateWithString: value
calendarFormat: @"%a, %d-%b-%Y %I:%M:%S %Z"];
if (expireDate)
[dict setObject: expireDate forKey: NSHTTPCookieExpires];
}
else if ([[key lowercaseString] isEqual: @"max-age"])
[dict setObject: value forKey: NSHTTPCookieMaximumAge];
else if ([[key lowercaseString] isEqual: @"originurl"])
[dict setObject: value forKey: NSHTTPCookieOriginURL];
else if ([[key lowercaseString] isEqual: @"path"])
[dict setObject: value forKey: NSHTTPCookiePath];
else if ([[key lowercaseString] isEqual: @"port"])
[dict setObject: value forKey: NSHTTPCookiePort];
else if ([[key lowercaseString] isEqual: @"secure"])
[dict setObject: [NSNumber numberWithBool: YES]
forKey: NSHTTPCookieSecure];
else if ([[key lowercaseString] isEqual:@"httponly"])
[dict setObject: [NSNumber numberWithBool: YES]
forKey: HTTPCookieHTTPOnly];
else if ([[key lowercaseString] isEqual: @"version"])
[dict setObject: value forKey: NSHTTPCookieVersion];
return YES;
}
static id
GSPropertyListFromCookieFormat(NSString *string, int version)
{
NSMutableDictionary *dict;
pldata _pld;
pldata *pld = &_pld;
NSData *d;
BOOL moreCharacters;
/*
* An empty string is a nil property list.
*/
if ([string length] == 0)
{
return nil;
}
d = [string dataUsingEncoding: NSUTF8StringEncoding];
NSCAssert(d, @"Couldn't get utf8 data from string.");
_pld.ptr = (unsigned char*)[d bytes];
_pld.pos = 0;
_pld.end = [d length];
_pld.err = nil;
_pld.lin = 0;
_pld.opt = 0;
_pld.key = NO;
_pld.old = YES; // OpenStep style
dict = [[NSMutableDictionary allocWithZone: NSDefaultMallocZone()]
initWithCapacity: 0];
while (skipSpace(pld) == YES)
{
id key;
id val;
if (pld->ptr[pld->pos] == '"')
{
key = parseQuotedString(pld);
}
else
{
unsigned int oldpos = pld->pos;
unsigned int keyvalpos = 0;
id keyval = parseUnquotedString(pld, ';');
keyvalpos = pld->pos;
pld->pos = oldpos;
key = parseUnquotedString(pld, '=');
// Detect value-less cookies like HTTPOnly; and Secure;
if ([keyval length] < [key length])
{
pld->pos = keyvalpos;
key = keyval;
}
}
if (key == nil)
{
DESTROY(dict);
break;
}
moreCharacters = skipSpace(pld);
if (moreCharacters == NO || pld->ptr[pld->pos] == ';')
{
pld->pos++;
if (_setCookieKey(dict, key, @"") == NO)
{
pld->err = @"invalid cookie pair";
DESTROY(dict);
}
RELEASE(key);
}
else if (pld->ptr[pld->pos] == '=')
{
pld->pos++;
if (skipSpace(pld) == NO)
{
RELEASE(key);
DESTROY(dict);
break;
}
if (pld->ptr[pld->pos] == '"')
{
val = parseQuotedString(pld);
}
else
{
val = parseUnquotedString(pld, ';');
}
if (val == nil)
{
RELEASE(key);
DESTROY(dict);
break;
}
skipSpace(pld);
if (_setCookieKey(dict, key, val) == NO)
{
pld->err = @"invalid cookie pair";
DESTROY(dict);
}
RELEASE(key);
RELEASE(val);
if (pld->ptr[pld->pos] == ';')
{
pld->pos++;
}
else
{
break;
}
}
else
{
pld->err = @"unexpected character (wanted '=' or ';')";
RELEASE(key);
DESTROY(dict);
break;
}
}
if (dict == nil && _pld.err != nil)
{
RELEASE(dict);
[NSException raise: NSGenericException
format: @"Parse failed at line %d (char %d) - %@",
_pld.lin + 1, _pld.pos + 1, _pld.err];
}
return AUTORELEASE(dict);
}
/* Split a string containing comma seprated cookeie settings into an array
* of individual cookie specifications.
* Look for the comma that separates cookies. Commas can also occur in
* date strings, like "expires", but perhaps it can occur other places.
* For instance, the key/value pair key=value1,value2 is not really
* valid, but should we handle it anyway? Definitely we should handle the
* perfectly normal case of:
*
* Set-Cookie: domain=test.com; expires=Thu, 12-Sep-2109 14:58:04 GMT;
* session=foo
* Set-Cookie: bar=baz
*
* which gets concatenated into something like:
*
* Set-Cookie: domain=test.com; expires=Thu, 12-Sep-2109 14:58:04 GMT;
* session=foo,bar=baz
*/
static NSMutableArray*
GSCookieStrings(NSString *string)
{
unsigned char *ptr;
unsigned pos;
unsigned end;
NSData *d;
NSMutableArray *cookies;
unsigned start = 0;
unsigned saved = 0;
if ([string length] == 0)
{
return nil;
}
d = [string dataUsingEncoding: NSUTF8StringEncoding];
NSCAssert(d, @"Couldn't get utf8 data from string.");
ptr = (unsigned char*)[d bytes];
pos = 0;
end = [d length];
cookies = [NSMutableArray arrayWithCapacity: 4];
while (pos < end)
{
while (pos < end && isspace(ptr[pos]))
{
pos++;
}
start = pos;
while (pos < end)
{
if (ptr[pos] == ',')
{
/* Look ahead for something that will tell us if this is a
* separate cookie or not. We look for something of the form
* ' token =' where a space represents any optional whitespace.
*/
saved = pos++;
while (pos < end && isspace(ptr[pos]))
{
pos++;
}
if (pos < end)
{
const char *bad = "()<>@,;:\\\"/[]?={}";
int c = ptr[pos];
/* skip past token characters.
*/
while (c > 32 && c < 128 && strchr(bad, c) == 0)
{
pos++;
if (pos < end)
{
c = ptr[pos];
}
}
while (pos < end && isspace(ptr[pos]))
{
pos++;
}
if (pos < end && '=' == ptr[pos])
{
pos = saved + 1;
/* We found a comma separator: so make the text before
* the comma a cooke string as long as it is not empty.
*/
while (saved > start
&& isspace(ptr[saved - 1]))
{
saved--;
}
if (saved > start)
{
NSString *str = [NSString alloc];
str = [str initWithBytes: ptr + start
length: saved - start
encoding: NSUTF8StringEncoding];
[cookies addObject: str];
RELEASE(str);
}
start = saved = pos;
}
}
pos = saved;
}
pos++;
}
}
if (pos > start)
{
/* There was data after the last comma; make it into a cookie string
* as long as it's not empty after removing spaces
*/
saved = pos;
while (saved > start
&& isspace(ptr[saved - 1]))
{
saved--;
}
if (saved > start)
{
NSString *str = [NSString alloc];
/* There may not be room to add a nul terminator, so we use an
* initialiser which doesn't need one.
*/
str = [str initWithBytes: ptr + start
length: saved - start
encoding: NSUTF8StringEncoding];
[cookies addObject: str];
RELEASE(str);
}
}
return cookies; // The individual cookies
}
|