cookie.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at http://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. /***
  23. RECEIVING COOKIE INFORMATION
  24. ============================
  25. struct CookieInfo *cookie_init(char *file);
  26. Inits a cookie struct to store data in a local file. This is always
  27. called before any cookies are set.
  28. int cookies_set(struct CookieInfo *cookie, char *cookie_line);
  29. The 'cookie_line' parameter is a full "Set-cookie:" line as
  30. received from a server.
  31. The function need to replace previously stored lines that this new
  32. line superceeds.
  33. It may remove lines that are expired.
  34. It should return an indication of success/error.
  35. SENDING COOKIE INFORMATION
  36. ==========================
  37. struct Cookies *cookie_getlist(struct CookieInfo *cookie,
  38. char *host, char *path, bool secure);
  39. For a given host and path, return a linked list of cookies that
  40. the client should send to the server if used now. The secure
  41. boolean informs the cookie if a secure connection is achieved or
  42. not.
  43. It shall only return cookies that haven't expired.
  44. Example set of cookies:
  45. Set-cookie: PRODUCTINFO=webxpress; domain=.fidelity.com; path=/; secure
  46. Set-cookie: PERSONALIZE=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  47. domain=.fidelity.com; path=/ftgw; secure
  48. Set-cookie: FidHist=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  49. domain=.fidelity.com; path=/; secure
  50. Set-cookie: FidOrder=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  51. domain=.fidelity.com; path=/; secure
  52. Set-cookie: DisPend=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  53. domain=.fidelity.com; path=/; secure
  54. Set-cookie: FidDis=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  55. domain=.fidelity.com; path=/; secure
  56. Set-cookie:
  57. Session_Key@6791a9e0-901a-11d0-a1c8-9b012c88aa77=none;expires=Monday,
  58. 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure
  59. ****/
  60. #include "curl_setup.h"
  61. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
  62. #define _MPRINTF_REPLACE
  63. #include <curl/mprintf.h>
  64. #include "urldata.h"
  65. #include "cookie.h"
  66. #include "strequal.h"
  67. #include "strtok.h"
  68. #include "sendf.h"
  69. #include "slist.h"
  70. #include "curl_memory.h"
  71. #include "share.h"
  72. #include "strtoofft.h"
  73. #include "rawstr.h"
  74. #include "curl_memrchr.h"
  75. #include "inet_pton.h"
  76. /* The last #include file should be: */
  77. #include "memdebug.h"
  78. static void freecookie(struct Cookie *co)
  79. {
  80. if(co->expirestr)
  81. free(co->expirestr);
  82. if(co->domain)
  83. free(co->domain);
  84. if(co->path)
  85. free(co->path);
  86. if(co->spath)
  87. free(co->spath);
  88. if(co->name)
  89. free(co->name);
  90. if(co->value)
  91. free(co->value);
  92. if(co->maxage)
  93. free(co->maxage);
  94. if(co->version)
  95. free(co->version);
  96. free(co);
  97. }
  98. static bool tailmatch(const char *cooke_domain, const char *hostname)
  99. {
  100. size_t cookie_domain_len = strlen(cooke_domain);
  101. size_t hostname_len = strlen(hostname);
  102. if(hostname_len < cookie_domain_len)
  103. return FALSE;
  104. if(!Curl_raw_equal(cooke_domain, hostname+hostname_len-cookie_domain_len))
  105. return FALSE;
  106. /* A lead char of cookie_domain is not '.'.
  107. RFC6265 4.1.2.3. The Domain Attribute says:
  108. For example, if the value of the Domain attribute is
  109. "example.com", the user agent will include the cookie in the Cookie
  110. header when making HTTP requests to example.com, www.example.com, and
  111. www.corp.example.com.
  112. */
  113. if(hostname_len == cookie_domain_len)
  114. return TRUE;
  115. if('.' == *(hostname + hostname_len - cookie_domain_len - 1))
  116. return TRUE;
  117. return FALSE;
  118. }
  119. /*
  120. * matching cookie path and url path
  121. * RFC6265 5.1.4 Paths and Path-Match
  122. */
  123. static bool pathmatch(const char* cookie_path, const char* request_uri)
  124. {
  125. size_t cookie_path_len;
  126. size_t uri_path_len;
  127. char* uri_path = NULL;
  128. char* pos;
  129. bool ret = FALSE;
  130. /* cookie_path must not have last '/' separator. ex: /sample */
  131. cookie_path_len = strlen(cookie_path);
  132. if(1 == cookie_path_len) {
  133. /* cookie_path must be '/' */
  134. return TRUE;
  135. }
  136. uri_path = strdup(request_uri);
  137. if(!uri_path)
  138. return FALSE;
  139. pos = strchr(uri_path, '?');
  140. if(pos)
  141. *pos = 0x0;
  142. /* #-fragments are already cut off! */
  143. if(0 == strlen(uri_path) || uri_path[0] != '/') {
  144. free(uri_path);
  145. uri_path = strdup("/");
  146. if(!uri_path)
  147. return FALSE;
  148. }
  149. /* here, RFC6265 5.1.4 says
  150. 4. Output the characters of the uri-path from the first character up
  151. to, but not including, the right-most %x2F ("/").
  152. but URL path /hoge?fuga=xxx means /hoge/index.cgi?fuga=xxx in some site
  153. without redirect.
  154. Ignore this algorithm because /hoge is uri path for this case
  155. (uri path is not /).
  156. */
  157. uri_path_len = strlen(uri_path);
  158. if(uri_path_len < cookie_path_len) {
  159. ret = FALSE;
  160. goto pathmatched;
  161. }
  162. /* not using checkprefix() because matching should be case-sensitive */
  163. if(strncmp(cookie_path, uri_path, cookie_path_len)) {
  164. ret = FALSE;
  165. goto pathmatched;
  166. }
  167. /* The cookie-path and the uri-path are identical. */
  168. if(cookie_path_len == uri_path_len) {
  169. ret = TRUE;
  170. goto pathmatched;
  171. }
  172. /* here, cookie_path_len < url_path_len */
  173. if(uri_path[cookie_path_len] == '/') {
  174. ret = TRUE;
  175. goto pathmatched;
  176. }
  177. ret = FALSE;
  178. pathmatched:
  179. free(uri_path);
  180. return ret;
  181. }
  182. /*
  183. * cookie path sanitize
  184. */
  185. static char *sanitize_cookie_path(const char *cookie_path)
  186. {
  187. size_t len;
  188. char *new_path = strdup(cookie_path);
  189. if(!new_path)
  190. return NULL;
  191. /* some stupid site sends path attribute with '"'. */
  192. if(new_path[0] == '\"') {
  193. memmove((void *)new_path, (const void *)(new_path + 1), strlen(new_path));
  194. }
  195. if(new_path[strlen(new_path) - 1] == '\"') {
  196. new_path[strlen(new_path) - 1] = 0x0;
  197. }
  198. /* RFC6265 5.2.4 The Path Attribute */
  199. if(new_path[0] != '/') {
  200. /* Let cookie-path be the default-path. */
  201. free(new_path);
  202. new_path = strdup("/");
  203. return new_path;
  204. }
  205. /* convert /hoge/ to /hoge */
  206. len = strlen(new_path);
  207. if(1 < len && new_path[len - 1] == '/') {
  208. new_path[len - 1] = 0x0;
  209. }
  210. return new_path;
  211. }
  212. /*
  213. * Load cookies from all given cookie files (CURLOPT_COOKIEFILE).
  214. */
  215. void Curl_cookie_loadfiles(struct SessionHandle *data)
  216. {
  217. struct curl_slist *list = data->change.cookielist;
  218. if(list) {
  219. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  220. while(list) {
  221. data->cookies = Curl_cookie_init(data,
  222. list->data,
  223. data->cookies,
  224. data->set.cookiesession);
  225. list = list->next;
  226. }
  227. curl_slist_free_all(data->change.cookielist); /* clean up list */
  228. data->change.cookielist = NULL; /* don't do this again! */
  229. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  230. }
  231. }
  232. /*
  233. * strstore() makes a strdup() on the 'newstr' and if '*str' is non-NULL
  234. * that will be freed before the allocated string is stored there.
  235. *
  236. * It is meant to easily replace strdup()
  237. */
  238. static void strstore(char **str, const char *newstr)
  239. {
  240. if(*str)
  241. free(*str);
  242. *str = strdup(newstr);
  243. }
  244. /*
  245. * remove_expired() removes expired cookies.
  246. */
  247. static void remove_expired(struct CookieInfo *cookies)
  248. {
  249. struct Cookie *co, *nx, *pv;
  250. curl_off_t now = (curl_off_t)time(NULL);
  251. co = cookies->cookies;
  252. pv = NULL;
  253. while(co) {
  254. nx = co->next;
  255. if((co->expirestr || co->maxage) && co->expires < now) {
  256. if(co == cookies->cookies) {
  257. cookies->cookies = co->next;
  258. }
  259. else {
  260. pv->next = co->next;
  261. }
  262. cookies->numcookies--;
  263. freecookie(co);
  264. }
  265. else {
  266. pv = co;
  267. }
  268. co = nx;
  269. }
  270. }
  271. /*
  272. * Return true if the given string is an IP(v4|v6) address.
  273. */
  274. static bool isip(const char *domain)
  275. {
  276. struct in_addr addr;
  277. #ifdef ENABLE_IPV6
  278. struct in6_addr addr6;
  279. #endif
  280. if(Curl_inet_pton(AF_INET, domain, &addr)
  281. #ifdef ENABLE_IPV6
  282. || Curl_inet_pton(AF_INET6, domain, &addr6)
  283. #endif
  284. ) {
  285. /* domain name given as IP address */
  286. return TRUE;
  287. }
  288. return FALSE;
  289. }
  290. /****************************************************************************
  291. *
  292. * Curl_cookie_add()
  293. *
  294. * Add a single cookie line to the cookie keeping object.
  295. *
  296. * Be aware that sometimes we get an IP-only host name, and that might also be
  297. * a numerical IPv6 address.
  298. *
  299. ***************************************************************************/
  300. struct Cookie *
  301. Curl_cookie_add(struct SessionHandle *data,
  302. /* The 'data' pointer here may be NULL at times, and thus
  303. must only be used very carefully for things that can deal
  304. with data being NULL. Such as infof() and similar */
  305. struct CookieInfo *c,
  306. bool httpheader, /* TRUE if HTTP header-style line */
  307. char *lineptr, /* first character of the line */
  308. const char *domain, /* default domain */
  309. const char *path) /* full path used when this cookie is set,
  310. used to get default path for the cookie
  311. unless set */
  312. {
  313. struct Cookie *clist;
  314. char name[MAX_NAME];
  315. struct Cookie *co;
  316. struct Cookie *lastc=NULL;
  317. time_t now = time(NULL);
  318. bool replace_old = FALSE;
  319. bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
  320. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  321. (void)data;
  322. #endif
  323. /* First, alloc and init a new struct for it */
  324. co = calloc(1, sizeof(struct Cookie));
  325. if(!co)
  326. return NULL; /* bail out if we're this low on memory */
  327. if(httpheader) {
  328. /* This line was read off a HTTP-header */
  329. const char *ptr;
  330. const char *semiptr;
  331. char *what;
  332. what = malloc(MAX_COOKIE_LINE);
  333. if(!what) {
  334. free(co);
  335. return NULL;
  336. }
  337. semiptr=strchr(lineptr, ';'); /* first, find a semicolon */
  338. while(*lineptr && ISBLANK(*lineptr))
  339. lineptr++;
  340. ptr = lineptr;
  341. do {
  342. /* we have a <what>=<this> pair or a stand-alone word here */
  343. name[0]=what[0]=0; /* init the buffers */
  344. if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n =]=%"
  345. MAX_COOKIE_LINE_TXT "[^;\r\n]",
  346. name, what)) {
  347. /* Use strstore() below to properly deal with received cookie
  348. headers that have the same string property set more than once,
  349. and then we use the last one. */
  350. const char *whatptr;
  351. bool done = FALSE;
  352. bool sep;
  353. size_t len=strlen(what);
  354. const char *endofn = &ptr[ strlen(name) ];
  355. /* skip trailing spaces in name */
  356. while(*endofn && ISBLANK(*endofn))
  357. endofn++;
  358. /* name ends with a '=' ? */
  359. sep = (*endofn == '=')?TRUE:FALSE;
  360. /* Strip off trailing whitespace from the 'what' */
  361. while(len && ISBLANK(what[len-1])) {
  362. what[len-1]=0;
  363. len--;
  364. }
  365. /* Skip leading whitespace from the 'what' */
  366. whatptr=what;
  367. while(*whatptr && ISBLANK(*whatptr))
  368. whatptr++;
  369. if(!len) {
  370. /* this was a "<name>=" with no content, and we must allow
  371. 'secure' and 'httponly' specified this weirdly */
  372. done = TRUE;
  373. if(Curl_raw_equal("secure", name))
  374. co->secure = TRUE;
  375. else if(Curl_raw_equal("httponly", name))
  376. co->httponly = TRUE;
  377. else if(sep)
  378. /* there was a '=' so we're not done parsing this field */
  379. done = FALSE;
  380. }
  381. if(done)
  382. ;
  383. else if(Curl_raw_equal("path", name)) {
  384. strstore(&co->path, whatptr);
  385. if(!co->path) {
  386. badcookie = TRUE; /* out of memory bad */
  387. break;
  388. }
  389. co->spath = sanitize_cookie_path(co->path);
  390. if(!co->spath) {
  391. badcookie = TRUE; /* out of memory bad */
  392. break;
  393. }
  394. }
  395. else if(Curl_raw_equal("domain", name)) {
  396. bool is_ip;
  397. const char *dotp;
  398. /* Now, we make sure that our host is within the given domain,
  399. or the given domain is not valid and thus cannot be set. */
  400. if('.' == whatptr[0])
  401. whatptr++; /* ignore preceding dot */
  402. is_ip = isip(domain ? domain : whatptr);
  403. /* check for more dots */
  404. dotp = strchr(whatptr, '.');
  405. if(!dotp)
  406. domain=":";
  407. if(!domain
  408. || (is_ip && !strcmp(whatptr, domain))
  409. || (!is_ip && tailmatch(whatptr, domain))) {
  410. strstore(&co->domain, whatptr);
  411. if(!co->domain) {
  412. badcookie = TRUE;
  413. break;
  414. }
  415. if(!is_ip)
  416. co->tailmatch=TRUE; /* we always do that if the domain name was
  417. given */
  418. }
  419. else {
  420. /* we did not get a tailmatch and then the attempted set domain
  421. is not a domain to which the current host belongs. Mark as
  422. bad. */
  423. badcookie=TRUE;
  424. infof(data, "skipped cookie with bad tailmatch domain: %s\n",
  425. whatptr);
  426. }
  427. }
  428. else if(Curl_raw_equal("version", name)) {
  429. strstore(&co->version, whatptr);
  430. if(!co->version) {
  431. badcookie = TRUE;
  432. break;
  433. }
  434. }
  435. else if(Curl_raw_equal("max-age", name)) {
  436. /* Defined in RFC2109:
  437. Optional. The Max-Age attribute defines the lifetime of the
  438. cookie, in seconds. The delta-seconds value is a decimal non-
  439. negative integer. After delta-seconds seconds elapse, the
  440. client should discard the cookie. A value of zero means the
  441. cookie should be discarded immediately.
  442. */
  443. strstore(&co->maxage, whatptr);
  444. if(!co->maxage) {
  445. badcookie = TRUE;
  446. break;
  447. }
  448. }
  449. else if(Curl_raw_equal("expires", name)) {
  450. strstore(&co->expirestr, whatptr);
  451. if(!co->expirestr) {
  452. badcookie = TRUE;
  453. break;
  454. }
  455. }
  456. else if(!co->name) {
  457. co->name = strdup(name);
  458. co->value = strdup(whatptr);
  459. if(!co->name || !co->value) {
  460. badcookie = TRUE;
  461. break;
  462. }
  463. }
  464. /*
  465. else this is the second (or more) name we don't know
  466. about! */
  467. }
  468. else {
  469. /* this is an "illegal" <what>=<this> pair */
  470. }
  471. if(!semiptr || !*semiptr) {
  472. /* we already know there are no more cookies */
  473. semiptr = NULL;
  474. continue;
  475. }
  476. ptr=semiptr+1;
  477. while(*ptr && ISBLANK(*ptr))
  478. ptr++;
  479. semiptr=strchr(ptr, ';'); /* now, find the next semicolon */
  480. if(!semiptr && *ptr)
  481. /* There are no more semicolons, but there's a final name=value pair
  482. coming up */
  483. semiptr=strchr(ptr, '\0');
  484. } while(semiptr);
  485. if(co->maxage) {
  486. co->expires =
  487. curlx_strtoofft((*co->maxage=='\"')?
  488. &co->maxage[1]:&co->maxage[0], NULL, 10);
  489. if(CURL_OFF_T_MAX - now < co->expires)
  490. /* avoid overflow */
  491. co->expires = CURL_OFF_T_MAX;
  492. else
  493. co->expires += now;
  494. }
  495. else if(co->expirestr) {
  496. /* Note that if the date couldn't get parsed for whatever reason,
  497. the cookie will be treated as a session cookie */
  498. co->expires = curl_getdate(co->expirestr, NULL);
  499. /* Session cookies have expires set to 0 so if we get that back
  500. from the date parser let's add a second to make it a
  501. non-session cookie */
  502. if(co->expires == 0)
  503. co->expires = 1;
  504. else if(co->expires < 0)
  505. co->expires = 0;
  506. }
  507. if(!badcookie && !co->domain) {
  508. if(domain) {
  509. /* no domain was given in the header line, set the default */
  510. co->domain=strdup(domain);
  511. if(!co->domain)
  512. badcookie = TRUE;
  513. }
  514. }
  515. if(!badcookie && !co->path && path) {
  516. /* No path was given in the header line, set the default.
  517. Note that the passed-in path to this function MAY have a '?' and
  518. following part that MUST not be stored as part of the path. */
  519. char *queryp = strchr(path, '?');
  520. /* queryp is where the interesting part of the path ends, so now we
  521. want to the find the last */
  522. char *endslash;
  523. if(!queryp)
  524. endslash = strrchr(path, '/');
  525. else
  526. endslash = memrchr(path, '/', (size_t)(queryp - path));
  527. if(endslash) {
  528. size_t pathlen = (size_t)(endslash-path+1); /* include ending slash */
  529. co->path=malloc(pathlen+1); /* one extra for the zero byte */
  530. if(co->path) {
  531. memcpy(co->path, path, pathlen);
  532. co->path[pathlen]=0; /* zero terminate */
  533. co->spath = sanitize_cookie_path(co->path);
  534. if(!co->spath)
  535. badcookie = TRUE; /* out of memory bad */
  536. }
  537. else
  538. badcookie = TRUE;
  539. }
  540. }
  541. free(what);
  542. if(badcookie || !co->name) {
  543. /* we didn't get a cookie name or a bad one,
  544. this is an illegal line, bail out */
  545. freecookie(co);
  546. return NULL;
  547. }
  548. }
  549. else {
  550. /* This line is NOT a HTTP header style line, we do offer support for
  551. reading the odd netscape cookies-file format here */
  552. char *ptr;
  553. char *firstptr;
  554. char *tok_buf=NULL;
  555. int fields;
  556. /* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies
  557. marked with httpOnly after the domain name are not accessible
  558. from javascripts, but since curl does not operate at javascript
  559. level, we include them anyway. In Firefox's cookie files, these
  560. lines are preceded with #HttpOnly_ and then everything is
  561. as usual, so we skip 10 characters of the line..
  562. */
  563. if(strncmp(lineptr, "#HttpOnly_", 10) == 0) {
  564. lineptr += 10;
  565. co->httponly = TRUE;
  566. }
  567. if(lineptr[0]=='#') {
  568. /* don't even try the comments */
  569. free(co);
  570. return NULL;
  571. }
  572. /* strip off the possible end-of-line characters */
  573. ptr=strchr(lineptr, '\r');
  574. if(ptr)
  575. *ptr=0; /* clear it */
  576. ptr=strchr(lineptr, '\n');
  577. if(ptr)
  578. *ptr=0; /* clear it */
  579. firstptr=strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */
  580. /* Now loop through the fields and init the struct we already have
  581. allocated */
  582. for(ptr=firstptr, fields=0; ptr && !badcookie;
  583. ptr=strtok_r(NULL, "\t", &tok_buf), fields++) {
  584. switch(fields) {
  585. case 0:
  586. if(ptr[0]=='.') /* skip preceding dots */
  587. ptr++;
  588. co->domain = strdup(ptr);
  589. if(!co->domain)
  590. badcookie = TRUE;
  591. break;
  592. case 1:
  593. /* This field got its explanation on the 23rd of May 2001 by
  594. Andrés García:
  595. flag: A TRUE/FALSE value indicating if all machines within a given
  596. domain can access the variable. This value is set automatically by
  597. the browser, depending on the value you set for the domain.
  598. As far as I can see, it is set to true when the cookie says
  599. .domain.com and to false when the domain is complete www.domain.com
  600. */
  601. co->tailmatch = Curl_raw_equal(ptr, "TRUE")?TRUE:FALSE;
  602. break;
  603. case 2:
  604. /* It turns out, that sometimes the file format allows the path
  605. field to remain not filled in, we try to detect this and work
  606. around it! Andrés García made us aware of this... */
  607. if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
  608. /* only if the path doesn't look like a boolean option! */
  609. co->path = strdup(ptr);
  610. if(!co->path)
  611. badcookie = TRUE;
  612. else {
  613. co->spath = sanitize_cookie_path(co->path);
  614. if(!co->spath) {
  615. badcookie = TRUE; /* out of memory bad */
  616. }
  617. }
  618. break;
  619. }
  620. /* this doesn't look like a path, make one up! */
  621. co->path = strdup("/");
  622. if(!co->path)
  623. badcookie = TRUE;
  624. co->spath = strdup("/");
  625. if(!co->spath)
  626. badcookie = TRUE;
  627. fields++; /* add a field and fall down to secure */
  628. /* FALLTHROUGH */
  629. case 3:
  630. co->secure = Curl_raw_equal(ptr, "TRUE")?TRUE:FALSE;
  631. break;
  632. case 4:
  633. co->expires = curlx_strtoofft(ptr, NULL, 10);
  634. break;
  635. case 5:
  636. co->name = strdup(ptr);
  637. if(!co->name)
  638. badcookie = TRUE;
  639. break;
  640. case 6:
  641. co->value = strdup(ptr);
  642. if(!co->value)
  643. badcookie = TRUE;
  644. break;
  645. }
  646. }
  647. if(6 == fields) {
  648. /* we got a cookie with blank contents, fix it */
  649. co->value = strdup("");
  650. if(!co->value)
  651. badcookie = TRUE;
  652. else
  653. fields++;
  654. }
  655. if(!badcookie && (7 != fields))
  656. /* we did not find the sufficient number of fields */
  657. badcookie = TRUE;
  658. if(badcookie) {
  659. freecookie(co);
  660. return NULL;
  661. }
  662. }
  663. if(!c->running && /* read from a file */
  664. c->newsession && /* clean session cookies */
  665. !co->expires) { /* this is a session cookie since it doesn't expire! */
  666. freecookie(co);
  667. return NULL;
  668. }
  669. co->livecookie = c->running;
  670. /* now, we have parsed the incoming line, we must now check if this
  671. superceeds an already existing cookie, which it may if the previous have
  672. the same domain and path as this */
  673. /* at first, remove expired cookies */
  674. remove_expired(c);
  675. clist = c->cookies;
  676. replace_old = FALSE;
  677. while(clist) {
  678. if(Curl_raw_equal(clist->name, co->name)) {
  679. /* the names are identical */
  680. if(clist->domain && co->domain) {
  681. if(Curl_raw_equal(clist->domain, co->domain))
  682. /* The domains are identical */
  683. replace_old=TRUE;
  684. }
  685. else if(!clist->domain && !co->domain)
  686. replace_old = TRUE;
  687. if(replace_old) {
  688. /* the domains were identical */
  689. if(clist->spath && co->spath) {
  690. if(Curl_raw_equal(clist->spath, co->spath)) {
  691. replace_old = TRUE;
  692. }
  693. else
  694. replace_old = FALSE;
  695. }
  696. else if(!clist->spath && !co->spath)
  697. replace_old = TRUE;
  698. else
  699. replace_old = FALSE;
  700. }
  701. if(replace_old && !co->livecookie && clist->livecookie) {
  702. /* Both cookies matched fine, except that the already present
  703. cookie is "live", which means it was set from a header, while
  704. the new one isn't "live" and thus only read from a file. We let
  705. live cookies stay alive */
  706. /* Free the newcomer and get out of here! */
  707. freecookie(co);
  708. return NULL;
  709. }
  710. if(replace_old) {
  711. co->next = clist->next; /* get the next-pointer first */
  712. /* then free all the old pointers */
  713. free(clist->name);
  714. if(clist->value)
  715. free(clist->value);
  716. if(clist->domain)
  717. free(clist->domain);
  718. if(clist->path)
  719. free(clist->path);
  720. if(clist->spath)
  721. free(clist->spath);
  722. if(clist->expirestr)
  723. free(clist->expirestr);
  724. if(clist->version)
  725. free(clist->version);
  726. if(clist->maxage)
  727. free(clist->maxage);
  728. *clist = *co; /* then store all the new data */
  729. free(co); /* free the newly alloced memory */
  730. co = clist; /* point to the previous struct instead */
  731. /* We have replaced a cookie, now skip the rest of the list but
  732. make sure the 'lastc' pointer is properly set */
  733. do {
  734. lastc = clist;
  735. clist = clist->next;
  736. } while(clist);
  737. break;
  738. }
  739. }
  740. lastc = clist;
  741. clist = clist->next;
  742. }
  743. if(c->running)
  744. /* Only show this when NOT reading the cookies from a file */
  745. infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
  746. "expire %" CURL_FORMAT_CURL_OFF_T "\n",
  747. replace_old?"Replaced":"Added", co->name, co->value,
  748. co->domain, co->path, co->expires);
  749. if(!replace_old) {
  750. /* then make the last item point on this new one */
  751. if(lastc)
  752. lastc->next = co;
  753. else
  754. c->cookies = co;
  755. c->numcookies++; /* one more cookie in the jar */
  756. }
  757. return co;
  758. }
  759. /*****************************************************************************
  760. *
  761. * Curl_cookie_init()
  762. *
  763. * Inits a cookie struct to read data from a local file. This is always
  764. * called before any cookies are set. File may be NULL.
  765. *
  766. * If 'newsession' is TRUE, discard all "session cookies" on read from file.
  767. *
  768. ****************************************************************************/
  769. struct CookieInfo *Curl_cookie_init(struct SessionHandle *data,
  770. const char *file,
  771. struct CookieInfo *inc,
  772. bool newsession)
  773. {
  774. struct CookieInfo *c;
  775. FILE *fp;
  776. bool fromfile=TRUE;
  777. if(NULL == inc) {
  778. /* we didn't get a struct, create one */
  779. c = calloc(1, sizeof(struct CookieInfo));
  780. if(!c)
  781. return NULL; /* failed to get memory */
  782. c->filename = strdup(file?file:"none"); /* copy the name just in case */
  783. }
  784. else {
  785. /* we got an already existing one, use that */
  786. c = inc;
  787. }
  788. c->running = FALSE; /* this is not running, this is init */
  789. if(file && strequal(file, "-")) {
  790. fp = stdin;
  791. fromfile=FALSE;
  792. }
  793. else if(file && !*file) {
  794. /* points to a "" string */
  795. fp = NULL;
  796. }
  797. else
  798. fp = file?fopen(file, "r"):NULL;
  799. c->newsession = newsession; /* new session? */
  800. if(fp) {
  801. char *lineptr;
  802. bool headerline;
  803. char *line = malloc(MAX_COOKIE_LINE);
  804. if(line) {
  805. while(fgets(line, MAX_COOKIE_LINE, fp)) {
  806. if(checkprefix("Set-Cookie:", line)) {
  807. /* This is a cookie line, get it! */
  808. lineptr=&line[11];
  809. headerline=TRUE;
  810. }
  811. else {
  812. lineptr=line;
  813. headerline=FALSE;
  814. }
  815. while(*lineptr && ISBLANK(*lineptr))
  816. lineptr++;
  817. Curl_cookie_add(data, c, headerline, lineptr, NULL, NULL);
  818. }
  819. free(line); /* free the line buffer */
  820. }
  821. if(fromfile)
  822. fclose(fp);
  823. }
  824. c->running = TRUE; /* now, we're running */
  825. return c;
  826. }
  827. /* sort this so that the longest path gets before the shorter path */
  828. static int cookie_sort(const void *p1, const void *p2)
  829. {
  830. struct Cookie *c1 = *(struct Cookie **)p1;
  831. struct Cookie *c2 = *(struct Cookie **)p2;
  832. size_t l1, l2;
  833. /* 1 - compare cookie path lengths */
  834. l1 = c1->path ? strlen(c1->path) : 0;
  835. l2 = c2->path ? strlen(c2->path) : 0;
  836. if(l1 != l2)
  837. return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
  838. /* 2 - compare cookie domain lengths */
  839. l1 = c1->domain ? strlen(c1->domain) : 0;
  840. l2 = c2->domain ? strlen(c2->domain) : 0;
  841. if(l1 != l2)
  842. return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
  843. /* 3 - compare cookie names */
  844. if(c1->name && c2->name)
  845. return strcmp(c1->name, c2->name);
  846. /* sorry, can't be more deterministic */
  847. return 0;
  848. }
  849. /*****************************************************************************
  850. *
  851. * Curl_cookie_getlist()
  852. *
  853. * For a given host and path, return a linked list of cookies that the
  854. * client should send to the server if used now. The secure boolean informs
  855. * the cookie if a secure connection is achieved or not.
  856. *
  857. * It shall only return cookies that haven't expired.
  858. *
  859. ****************************************************************************/
  860. struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
  861. const char *host, const char *path,
  862. bool secure)
  863. {
  864. struct Cookie *newco;
  865. struct Cookie *co;
  866. time_t now = time(NULL);
  867. struct Cookie *mainco=NULL;
  868. size_t matches = 0;
  869. bool is_ip;
  870. if(!c || !c->cookies)
  871. return NULL; /* no cookie struct or no cookies in the struct */
  872. /* at first, remove expired cookies */
  873. remove_expired(c);
  874. /* check if host is an IP(v4|v6) address */
  875. is_ip = isip(host);
  876. co = c->cookies;
  877. while(co) {
  878. /* only process this cookie if it is not expired or had no expire
  879. date AND that if the cookie requires we're secure we must only
  880. continue if we are! */
  881. if((!co->expires || (co->expires > now)) &&
  882. (co->secure?secure:TRUE)) {
  883. /* now check if the domain is correct */
  884. if(!co->domain ||
  885. (co->tailmatch && !is_ip && tailmatch(co->domain, host)) ||
  886. ((!co->tailmatch || is_ip) && Curl_raw_equal(host, co->domain)) ) {
  887. /* the right part of the host matches the domain stuff in the
  888. cookie data */
  889. /* now check the left part of the path with the cookies path
  890. requirement */
  891. if(!co->spath || pathmatch(co->spath, path) ) {
  892. /* and now, we know this is a match and we should create an
  893. entry for the return-linked-list */
  894. newco = malloc(sizeof(struct Cookie));
  895. if(newco) {
  896. /* first, copy the whole source cookie: */
  897. memcpy(newco, co, sizeof(struct Cookie));
  898. /* then modify our next */
  899. newco->next = mainco;
  900. /* point the main to us */
  901. mainco = newco;
  902. matches++;
  903. }
  904. else {
  905. fail:
  906. /* failure, clear up the allocated chain and return NULL */
  907. while(mainco) {
  908. co = mainco->next;
  909. free(mainco);
  910. mainco = co;
  911. }
  912. return NULL;
  913. }
  914. }
  915. }
  916. }
  917. co = co->next;
  918. }
  919. if(matches) {
  920. /* Now we need to make sure that if there is a name appearing more than
  921. once, the longest specified path version comes first. To make this
  922. the swiftest way, we just sort them all based on path length. */
  923. struct Cookie **array;
  924. size_t i;
  925. /* alloc an array and store all cookie pointers */
  926. array = malloc(sizeof(struct Cookie *) * matches);
  927. if(!array)
  928. goto fail;
  929. co = mainco;
  930. for(i=0; co; co = co->next)
  931. array[i++] = co;
  932. /* now sort the cookie pointers in path length order */
  933. qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
  934. /* remake the linked list order according to the new order */
  935. mainco = array[0]; /* start here */
  936. for(i=0; i<matches-1; i++)
  937. array[i]->next = array[i+1];
  938. array[matches-1]->next = NULL; /* terminate the list */
  939. free(array); /* remove the temporary data again */
  940. }
  941. return mainco; /* return the new list */
  942. }
  943. /*****************************************************************************
  944. *
  945. * Curl_cookie_clearall()
  946. *
  947. * Clear all existing cookies and reset the counter.
  948. *
  949. ****************************************************************************/
  950. void Curl_cookie_clearall(struct CookieInfo *cookies)
  951. {
  952. if(cookies) {
  953. Curl_cookie_freelist(cookies->cookies, TRUE);
  954. cookies->cookies = NULL;
  955. cookies->numcookies = 0;
  956. }
  957. }
  958. /*****************************************************************************
  959. *
  960. * Curl_cookie_freelist()
  961. *
  962. * Free a list of cookies previously returned by Curl_cookie_getlist();
  963. *
  964. * The 'cookiestoo' argument tells this function whether to just free the
  965. * list or actually also free all cookies within the list as well.
  966. *
  967. ****************************************************************************/
  968. void Curl_cookie_freelist(struct Cookie *co, bool cookiestoo)
  969. {
  970. struct Cookie *next;
  971. if(co) {
  972. while(co) {
  973. next = co->next;
  974. if(cookiestoo)
  975. freecookie(co);
  976. else
  977. free(co); /* we only free the struct since the "members" are all just
  978. pointed out in the main cookie list! */
  979. co = next;
  980. }
  981. }
  982. }
  983. /*****************************************************************************
  984. *
  985. * Curl_cookie_clearsess()
  986. *
  987. * Free all session cookies in the cookies list.
  988. *
  989. ****************************************************************************/
  990. void Curl_cookie_clearsess(struct CookieInfo *cookies)
  991. {
  992. struct Cookie *first, *curr, *next, *prev = NULL;
  993. if(!cookies || !cookies->cookies)
  994. return;
  995. first = curr = prev = cookies->cookies;
  996. for(; curr; curr = next) {
  997. next = curr->next;
  998. if(!curr->expires) {
  999. if(first == curr)
  1000. first = next;
  1001. if(prev == curr)
  1002. prev = next;
  1003. else
  1004. prev->next = next;
  1005. freecookie(curr);
  1006. cookies->numcookies--;
  1007. }
  1008. else
  1009. prev = curr;
  1010. }
  1011. cookies->cookies = first;
  1012. }
  1013. /*****************************************************************************
  1014. *
  1015. * Curl_cookie_cleanup()
  1016. *
  1017. * Free a "cookie object" previous created with cookie_init().
  1018. *
  1019. ****************************************************************************/
  1020. void Curl_cookie_cleanup(struct CookieInfo *c)
  1021. {
  1022. struct Cookie *co;
  1023. struct Cookie *next;
  1024. if(c) {
  1025. if(c->filename)
  1026. free(c->filename);
  1027. co = c->cookies;
  1028. while(co) {
  1029. next = co->next;
  1030. freecookie(co);
  1031. co = next;
  1032. }
  1033. free(c); /* free the base struct as well */
  1034. }
  1035. }
  1036. /* get_netscape_format()
  1037. *
  1038. * Formats a string for Netscape output file, w/o a newline at the end.
  1039. *
  1040. * Function returns a char * to a formatted line. Has to be free()d
  1041. */
  1042. static char *get_netscape_format(const struct Cookie *co)
  1043. {
  1044. return aprintf(
  1045. "%s" /* httponly preamble */
  1046. "%s%s\t" /* domain */
  1047. "%s\t" /* tailmatch */
  1048. "%s\t" /* path */
  1049. "%s\t" /* secure */
  1050. "%" CURL_FORMAT_CURL_OFF_T "\t" /* expires */
  1051. "%s\t" /* name */
  1052. "%s", /* value */
  1053. co->httponly?"#HttpOnly_":"",
  1054. /* Make sure all domains are prefixed with a dot if they allow
  1055. tailmatching. This is Mozilla-style. */
  1056. (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"",
  1057. co->domain?co->domain:"unknown",
  1058. co->tailmatch?"TRUE":"FALSE",
  1059. co->path?co->path:"/",
  1060. co->secure?"TRUE":"FALSE",
  1061. co->expires,
  1062. co->name,
  1063. co->value?co->value:"");
  1064. }
  1065. /*
  1066. * cookie_output()
  1067. *
  1068. * Writes all internally known cookies to the specified file. Specify
  1069. * "-" as file name to write to stdout.
  1070. *
  1071. * The function returns non-zero on write failure.
  1072. */
  1073. static int cookie_output(struct CookieInfo *c, const char *dumphere)
  1074. {
  1075. struct Cookie *co;
  1076. FILE *out;
  1077. bool use_stdout=FALSE;
  1078. if((NULL == c) || (0 == c->numcookies))
  1079. /* If there are no known cookies, we don't write or even create any
  1080. destination file */
  1081. return 0;
  1082. /* at first, remove expired cookies */
  1083. remove_expired(c);
  1084. if(strequal("-", dumphere)) {
  1085. /* use stdout */
  1086. out = stdout;
  1087. use_stdout=TRUE;
  1088. }
  1089. else {
  1090. out = fopen(dumphere, "w");
  1091. if(!out)
  1092. return 1; /* failure */
  1093. }
  1094. if(c) {
  1095. char *format_ptr;
  1096. fputs("# Netscape HTTP Cookie File\n"
  1097. "# http://curl.haxx.se/docs/http-cookies.html\n"
  1098. "# This file was generated by libcurl! Edit at your own risk.\n\n",
  1099. out);
  1100. co = c->cookies;
  1101. while(co) {
  1102. format_ptr = get_netscape_format(co);
  1103. if(format_ptr == NULL) {
  1104. fprintf(out, "#\n# Fatal libcurl error\n");
  1105. if(!use_stdout)
  1106. fclose(out);
  1107. return 1;
  1108. }
  1109. fprintf(out, "%s\n", format_ptr);
  1110. free(format_ptr);
  1111. co=co->next;
  1112. }
  1113. }
  1114. if(!use_stdout)
  1115. fclose(out);
  1116. return 0;
  1117. }
  1118. struct curl_slist *Curl_cookie_list(struct SessionHandle *data)
  1119. {
  1120. struct curl_slist *list = NULL;
  1121. struct curl_slist *beg;
  1122. struct Cookie *c;
  1123. char *line;
  1124. if((data->cookies == NULL) ||
  1125. (data->cookies->numcookies == 0))
  1126. return NULL;
  1127. c = data->cookies->cookies;
  1128. while(c) {
  1129. /* fill the list with _all_ the cookies we know */
  1130. line = get_netscape_format(c);
  1131. if(!line) {
  1132. curl_slist_free_all(list);
  1133. return NULL;
  1134. }
  1135. beg = Curl_slist_append_nodup(list, line);
  1136. if(!beg) {
  1137. free(line);
  1138. curl_slist_free_all(list);
  1139. return NULL;
  1140. }
  1141. list = beg;
  1142. c = c->next;
  1143. }
  1144. return list;
  1145. }
  1146. void Curl_flush_cookies(struct SessionHandle *data, int cleanup)
  1147. {
  1148. if(data->set.str[STRING_COOKIEJAR]) {
  1149. if(data->change.cookielist) {
  1150. /* If there is a list of cookie files to read, do it first so that
  1151. we have all the told files read before we write the new jar.
  1152. Curl_cookie_loadfiles() LOCKS and UNLOCKS the share itself! */
  1153. Curl_cookie_loadfiles(data);
  1154. }
  1155. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1156. /* if we have a destination file for all the cookies to get dumped to */
  1157. if(cookie_output(data->cookies, data->set.str[STRING_COOKIEJAR]))
  1158. infof(data, "WARNING: failed to save cookies in %s\n",
  1159. data->set.str[STRING_COOKIEJAR]);
  1160. }
  1161. else {
  1162. if(cleanup && data->change.cookielist) {
  1163. /* since nothing is written, we can just free the list of cookie file
  1164. names */
  1165. curl_slist_free_all(data->change.cookielist); /* clean up list */
  1166. data->change.cookielist = NULL;
  1167. }
  1168. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1169. }
  1170. if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
  1171. Curl_cookie_cleanup(data->cookies);
  1172. }
  1173. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  1174. }
  1175. #endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */