cookie.c 37 KB

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