wininet: Handle empty expires for cookie setting.
[wine.git] / dlls / wininet / cookie.c
blob66c012a0db0d0b8c182186bec1dcb88be7e870dc
1 /*
2 * Wininet - cookie handling stuff
4 * Copyright 2002 TransGaming Technologies Inc.
6 * David Hammerton
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "ws2tcpip.h"
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <assert.h>
30 #include <wchar.h>
32 #include "windef.h"
33 #include "winbase.h"
34 #include "wininet.h"
35 #include "lmcons.h"
36 #include "winerror.h"
38 #include "wine/debug.h"
39 #include "internet.h"
41 #define RESPONSE_TIMEOUT 30 /* FROM internet.c */
44 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
46 /* FIXME
47 * Cookies could use A LOT OF MEMORY. We need some kind of memory management here!
50 struct _cookie_domain_t;
51 struct _cookie_container_t;
53 typedef struct _cookie_t {
54 struct list entry;
56 struct _cookie_container_t *container;
58 WCHAR *name;
59 WCHAR *data;
60 DWORD flags;
61 FILETIME expiry;
62 FILETIME create;
63 } cookie_t;
65 typedef struct _cookie_container_t {
66 struct list entry;
68 WCHAR *cookie_url;
69 substr_t path;
70 struct _cookie_domain_t *domain;
72 struct list cookie_list;
73 } cookie_container_t;
75 typedef struct _cookie_domain_t {
76 struct list entry;
78 WCHAR *domain;
79 unsigned subdomain_len;
81 struct _cookie_domain_t *parent;
82 struct list subdomain_list;
84 /* List of stored paths sorted by length of the path. */
85 struct list path_list;
86 } cookie_domain_t;
88 static CRITICAL_SECTION cookie_cs;
89 static CRITICAL_SECTION_DEBUG cookie_cs_debug =
91 0, 0, &cookie_cs,
92 { &cookie_cs_debug.ProcessLocksList, &cookie_cs_debug.ProcessLocksList },
93 0, 0, { (DWORD_PTR)(__FILE__ ": cookie_cs") }
95 static CRITICAL_SECTION cookie_cs = { &cookie_cs_debug, -1, 0, 0, 0, 0 };
96 static struct list domain_list = LIST_INIT(domain_list);
98 static cookie_domain_t *get_cookie_domain(substr_t domain, BOOL create)
100 const WCHAR *ptr = domain.str + domain.len, *ptr_end, *subdomain_ptr;
101 cookie_domain_t *iter, *current_domain, *prev_domain = NULL;
102 struct list *current_list = &domain_list;
104 while(1) {
105 for(ptr_end = ptr--; ptr > domain.str && *ptr != '.'; ptr--);
106 subdomain_ptr = *ptr == '.' ? ptr+1 : ptr;
108 current_domain = NULL;
109 LIST_FOR_EACH_ENTRY(iter, current_list, cookie_domain_t, entry) {
110 if(ptr_end-subdomain_ptr == iter->subdomain_len
111 && !memcmp(subdomain_ptr, iter->domain, iter->subdomain_len*sizeof(WCHAR))) {
112 current_domain = iter;
113 break;
117 if(!current_domain) {
118 if(!create)
119 return prev_domain;
121 current_domain = heap_alloc(sizeof(*current_domain));
122 if(!current_domain)
123 return NULL;
125 current_domain->domain = heap_strndupW(subdomain_ptr, domain.str + domain.len - subdomain_ptr);
126 if(!current_domain->domain) {
127 heap_free(current_domain);
128 return NULL;
131 current_domain->subdomain_len = ptr_end-subdomain_ptr;
133 current_domain->parent = prev_domain;
134 list_init(&current_domain->path_list);
135 list_init(&current_domain->subdomain_list);
137 list_add_tail(current_list, &current_domain->entry);
140 if(ptr == domain.str)
141 return current_domain;
143 prev_domain = current_domain;
144 current_list = &current_domain->subdomain_list;
148 static WCHAR *create_cookie_url(substr_t domain, substr_t path, substr_t *ret_path)
150 WCHAR *p, *url;
151 DWORD len, user_len, i;
153 static const WCHAR cookie_prefix[] = {'C','o','o','k','i','e',':'};
155 user_len = 0;
156 if(GetUserNameW(NULL, &user_len) || GetLastError() != ERROR_INSUFFICIENT_BUFFER)
157 return NULL;
159 /* user_len already accounts for terminating NULL */
160 len = ARRAY_SIZE(cookie_prefix) + user_len + 1 /* @ */ + domain.len + path.len;
161 url = heap_alloc(len * sizeof(WCHAR));
162 if(!url)
163 return NULL;
165 memcpy(url, cookie_prefix, sizeof(cookie_prefix));
166 p = url + ARRAY_SIZE(cookie_prefix);
168 if(!GetUserNameW(p, &user_len)) {
169 heap_free(url);
170 return NULL;
172 p += user_len;
174 *(p - 1) = '@';
176 memcpy(p, domain.str, domain.len*sizeof(WCHAR));
177 p += domain.len;
179 for(i=0; i < path.len; i++)
180 p[i] = towlower(path.str[i]);
181 p[path.len] = 0;
183 ret_path->str = p;
184 ret_path->len = path.len;
185 return url;
188 static cookie_container_t *get_cookie_container(substr_t domain, substr_t path, BOOL create)
190 cookie_domain_t *cookie_domain;
191 cookie_container_t *cookie_container, *iter;
193 cookie_domain = get_cookie_domain(domain, create);
194 if(!cookie_domain)
195 return NULL;
197 LIST_FOR_EACH_ENTRY(cookie_container, &cookie_domain->path_list, cookie_container_t, entry) {
198 if(cookie_container->path.len < path.len)
199 break;
201 if(path.len == cookie_container->path.len && !wcsnicmp(cookie_container->path.str, path.str, path.len))
202 return cookie_container;
205 if(!create)
206 return NULL;
208 cookie_container = heap_alloc(sizeof(*cookie_container));
209 if(!cookie_container)
210 return NULL;
212 cookie_container->cookie_url = create_cookie_url(substrz(cookie_domain->domain), path, &cookie_container->path);
213 if(!cookie_container->cookie_url) {
214 heap_free(cookie_container);
215 return NULL;
218 cookie_container->domain = cookie_domain;
219 list_init(&cookie_container->cookie_list);
221 LIST_FOR_EACH_ENTRY(iter, &cookie_domain->path_list, cookie_container_t, entry) {
222 if(iter->path.len <= path.len) {
223 list_add_before(&iter->entry, &cookie_container->entry);
224 return cookie_container;
228 list_add_tail(&cookie_domain->path_list, &cookie_container->entry);
229 return cookie_container;
232 static void delete_cookie(cookie_t *cookie)
234 list_remove(&cookie->entry);
236 heap_free(cookie->name);
237 heap_free(cookie->data);
238 heap_free(cookie);
241 static cookie_t *alloc_cookie(substr_t name, substr_t data, FILETIME expiry, FILETIME create_time, DWORD flags)
243 cookie_t *new_cookie;
245 new_cookie = heap_alloc_zero(sizeof(*new_cookie));
246 if(!new_cookie)
247 return NULL;
249 new_cookie->expiry = expiry;
250 new_cookie->create = create_time;
251 new_cookie->flags = flags;
252 list_init(&new_cookie->entry);
254 if(name.str && !(new_cookie->name = heap_strndupW(name.str, name.len))) {
255 delete_cookie(new_cookie);
256 return NULL;
259 if(data.str && !(new_cookie->data = heap_strndupW(data.str, data.len))) {
260 delete_cookie(new_cookie);
261 return NULL;
264 return new_cookie;
267 static cookie_t *find_cookie(cookie_container_t *container, substr_t name)
269 cookie_t *iter;
271 LIST_FOR_EACH_ENTRY(iter, &container->cookie_list, cookie_t, entry) {
272 if(lstrlenW(iter->name) == name.len && !wcsnicmp(iter->name, name.str, name.len))
273 return iter;
276 return NULL;
279 static void add_cookie(cookie_container_t *container, cookie_t *new_cookie)
281 TRACE("Adding %s=%s to %s\n", debugstr_w(new_cookie->name), debugstr_w(new_cookie->data),
282 debugstr_w(container->cookie_url));
284 list_add_tail(&container->cookie_list, &new_cookie->entry);
285 new_cookie->container = container;
288 static void replace_cookie(cookie_container_t *container, cookie_t *new_cookie)
290 cookie_t *old_cookie;
292 old_cookie = find_cookie(container, substrz(new_cookie->name));
293 if(old_cookie)
294 delete_cookie(old_cookie);
296 add_cookie(container, new_cookie);
299 static BOOL cookie_match_path(cookie_container_t *container, substr_t path)
301 return path.len >= container->path.len && !wcsnicmp(container->path.str, path.str, container->path.len);
304 static BOOL load_persistent_cookie(substr_t domain, substr_t path)
306 INTERNET_CACHE_ENTRY_INFOW *info;
307 cookie_container_t *cookie_container;
308 cookie_t *new_cookie;
309 HANDLE cookie;
310 char *str = NULL, *pbeg, *pend;
311 DWORD size, flags;
312 WCHAR *name, *data;
313 FILETIME expiry, create, time;
315 cookie_container = get_cookie_container(domain, path, TRUE);
316 if(!cookie_container)
317 return FALSE;
319 size = 0;
320 RetrieveUrlCacheEntryStreamW(cookie_container->cookie_url, NULL, &size, FALSE, 0);
321 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
322 return TRUE;
323 info = heap_alloc(size);
324 if(!info)
325 return FALSE;
326 cookie = RetrieveUrlCacheEntryStreamW(cookie_container->cookie_url, info, &size, FALSE, 0);
327 size = info->dwSizeLow;
328 heap_free(info);
329 if(!cookie)
330 return FALSE;
332 if(!(str = heap_alloc(size+1)) || !ReadUrlCacheEntryStream(cookie, 0, str, &size, 0)) {
333 UnlockUrlCacheEntryStream(cookie, 0);
334 heap_free(str);
335 return FALSE;
337 str[size] = 0;
338 UnlockUrlCacheEntryStream(cookie, 0);
340 GetSystemTimeAsFileTime(&time);
341 for(pbeg=str; pbeg && *pbeg; name=data=NULL) {
342 pend = strchr(pbeg, '\n');
343 if(!pend)
344 break;
345 *pend = 0;
346 name = heap_strdupAtoW(pbeg);
348 pbeg = pend+1;
349 pend = strchr(pbeg, '\n');
350 if(!pend)
351 break;
352 *pend = 0;
353 data = heap_strdupAtoW(pbeg);
355 pbeg = strchr(pend+1, '\n');
356 if(!pbeg)
357 break;
358 sscanf(pbeg, "%u %u %u %u %u", &flags, &expiry.dwLowDateTime, &expiry.dwHighDateTime,
359 &create.dwLowDateTime, &create.dwHighDateTime);
361 /* skip "*\n" */
362 pbeg = strchr(pbeg, '*');
363 if(pbeg) {
364 pbeg++;
365 if(*pbeg)
366 pbeg++;
369 if(!name || !data)
370 break;
372 if(CompareFileTime(&time, &expiry) <= 0) {
373 new_cookie = alloc_cookie(substr(NULL, 0), substr(NULL, 0), expiry, create, flags);
374 if(!new_cookie)
375 break;
377 new_cookie->name = name;
378 new_cookie->data = data;
380 replace_cookie(cookie_container, new_cookie);
381 }else {
382 heap_free(name);
383 heap_free(data);
386 heap_free(str);
387 heap_free(name);
388 heap_free(data);
390 return TRUE;
393 static BOOL save_persistent_cookie(cookie_container_t *container)
395 static const WCHAR txtW[] = {'t','x','t',0};
397 WCHAR cookie_file[MAX_PATH];
398 HANDLE cookie_handle;
399 cookie_t *cookie_container = NULL, *cookie_iter;
400 BOOL do_save = FALSE;
401 char buf[64], *dyn_buf;
402 FILETIME time;
403 DWORD bytes_written;
404 size_t len;
406 /* check if there's anything to save */
407 GetSystemTimeAsFileTime(&time);
408 LIST_FOR_EACH_ENTRY_SAFE(cookie_container, cookie_iter, &container->cookie_list, cookie_t, entry)
410 if((cookie_container->expiry.dwLowDateTime || cookie_container->expiry.dwHighDateTime)
411 && CompareFileTime(&time, &cookie_container->expiry) > 0) {
412 delete_cookie(cookie_container);
413 continue;
416 if(!(cookie_container->flags & INTERNET_COOKIE_IS_SESSION)) {
417 do_save = TRUE;
418 break;
422 if(!do_save) {
423 DeleteUrlCacheEntryW(container->cookie_url);
424 return TRUE;
427 if(!CreateUrlCacheEntryW(container->cookie_url, 0, txtW, cookie_file, 0))
428 return FALSE;
430 cookie_handle = CreateFileW(cookie_file, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
431 if(cookie_handle == INVALID_HANDLE_VALUE) {
432 DeleteFileW(cookie_file);
433 return FALSE;
436 LIST_FOR_EACH_ENTRY(cookie_container, &container->cookie_list, cookie_t, entry)
438 if(cookie_container->flags & INTERNET_COOKIE_IS_SESSION)
439 continue;
441 dyn_buf = heap_strdupWtoA(cookie_container->name);
442 if(!dyn_buf || !WriteFile(cookie_handle, dyn_buf, strlen(dyn_buf), &bytes_written, NULL)) {
443 heap_free(dyn_buf);
444 do_save = FALSE;
445 break;
447 heap_free(dyn_buf);
448 if(!WriteFile(cookie_handle, "\n", 1, &bytes_written, NULL)) {
449 do_save = FALSE;
450 break;
453 dyn_buf = heap_strdupWtoA(cookie_container->data);
454 if(!dyn_buf || !WriteFile(cookie_handle, dyn_buf, strlen(dyn_buf), &bytes_written, NULL)) {
455 heap_free(dyn_buf);
456 do_save = FALSE;
457 break;
459 heap_free(dyn_buf);
460 if(!WriteFile(cookie_handle, "\n", 1, &bytes_written, NULL)) {
461 do_save = FALSE;
462 break;
465 dyn_buf = heap_strdupWtoA(container->domain->domain);
466 if(!dyn_buf || !WriteFile(cookie_handle, dyn_buf, strlen(dyn_buf), &bytes_written, NULL)) {
467 heap_free(dyn_buf);
468 do_save = FALSE;
469 break;
471 heap_free(dyn_buf);
473 len = WideCharToMultiByte(CP_ACP, 0, container->path.str, container->path.len, NULL, 0, NULL, NULL);
474 dyn_buf = heap_alloc(len+1);
475 if(dyn_buf) {
476 WideCharToMultiByte(CP_ACP, 0, container->path.str, container->path.len, dyn_buf, len, NULL, NULL);
477 dyn_buf[len] = 0;
479 if(!dyn_buf || !WriteFile(cookie_handle, dyn_buf, strlen(dyn_buf), &bytes_written, NULL)) {
480 heap_free(dyn_buf);
481 do_save = FALSE;
482 break;
484 heap_free(dyn_buf);
486 sprintf(buf, "\n%u\n%u\n%u\n%u\n%u\n*\n", cookie_container->flags,
487 cookie_container->expiry.dwLowDateTime, cookie_container->expiry.dwHighDateTime,
488 cookie_container->create.dwLowDateTime, cookie_container->create.dwHighDateTime);
489 if(!WriteFile(cookie_handle, buf, strlen(buf), &bytes_written, NULL)) {
490 do_save = FALSE;
491 break;
495 CloseHandle(cookie_handle);
496 if(!do_save) {
497 ERR("error saving cookie file\n");
498 DeleteFileW(cookie_file);
499 return FALSE;
502 memset(&time, 0, sizeof(time));
503 return CommitUrlCacheEntryW(container->cookie_url, cookie_file, time, time, 0, NULL, 0, txtW, 0);
506 static BOOL cookie_parse_url(const WCHAR *url, substr_t *host, substr_t *path)
508 URL_COMPONENTSW comp = { sizeof(comp) };
509 static const WCHAR rootW[] = {'/',0};
511 comp.dwHostNameLength = 1;
512 comp.dwUrlPathLength = 1;
514 if(!InternetCrackUrlW(url, 0, 0, &comp) || !comp.dwHostNameLength)
515 return FALSE;
517 /* discard the webpage off the end of the path */
518 while(comp.dwUrlPathLength && comp.lpszUrlPath[comp.dwUrlPathLength-1] != '/')
519 comp.dwUrlPathLength--;
521 *host = substr(comp.lpszHostName, comp.dwHostNameLength);
522 *path = comp.dwUrlPathLength ? substr(comp.lpszUrlPath, comp.dwUrlPathLength) : substr(rootW, 1);
523 return TRUE;
526 typedef struct {
527 cookie_t **cookies;
528 unsigned cnt;
529 unsigned size;
531 unsigned string_len;
532 } cookie_set_t;
534 static DWORD get_cookie(substr_t host, substr_t path, DWORD flags, cookie_set_t *res)
536 static const WCHAR empty_path[] = { '/',0 };
538 const WCHAR *p;
539 cookie_domain_t *domain;
540 cookie_container_t *container;
541 FILETIME tm;
543 GetSystemTimeAsFileTime(&tm);
545 p = host.str + host.len;
546 while(p > host.str && p[-1] != '.') p--;
547 while(p != host.str) {
548 p--;
549 while(p > host.str && p[-1] != '.') p--;
550 if(p == host.str) break;
552 load_persistent_cookie(substr(p, host.str+host.len-p), substr(empty_path, 1));
555 p = path.str + path.len;
556 do {
557 load_persistent_cookie(host, substr(path.str, p-path.str));
559 p--;
560 while(p > path.str && p[-1] != '/') p--;
561 }while(p != path.str);
563 domain = get_cookie_domain(host, FALSE);
564 if(!domain) {
565 TRACE("Unknown host %s\n", debugstr_wn(host.str, host.len));
566 return ERROR_NO_MORE_ITEMS;
569 for(domain = get_cookie_domain(host, FALSE); domain; domain = domain->parent) {
570 LIST_FOR_EACH_ENTRY(container, &domain->path_list, cookie_container_t, entry) {
571 struct list *cursor, *cursor2;
573 if(!cookie_match_path(container, path))
574 continue;
576 LIST_FOR_EACH_SAFE(cursor, cursor2, &container->cookie_list) {
577 cookie_t *cookie_iter = LIST_ENTRY(cursor, cookie_t, entry);
579 /* check for expiry */
580 if((cookie_iter->expiry.dwLowDateTime != 0 || cookie_iter->expiry.dwHighDateTime != 0)
581 && CompareFileTime(&tm, &cookie_iter->expiry) > 0) {
582 TRACE("Found expired cookie. deleting\n");
583 delete_cookie(cookie_iter);
584 continue;
587 if((cookie_iter->flags & INTERNET_COOKIE_HTTPONLY) && !(flags & INTERNET_COOKIE_HTTPONLY))
588 continue;
590 if(!res->size) {
591 res->cookies = heap_alloc(4*sizeof(*res->cookies));
592 if(!res->cookies)
593 continue;
594 res->size = 4;
595 }else if(res->cnt == res->size) {
596 cookie_t **new_cookies = heap_realloc(res->cookies, res->size*2*sizeof(*res->cookies));
597 if(!new_cookies)
598 continue;
599 res->cookies = new_cookies;
600 res->size *= 2;
603 TRACE("%s = %s domain %s path %s\n", debugstr_w(cookie_iter->name), debugstr_w(cookie_iter->data),
604 debugstr_w(domain->domain), debugstr_wn(container->path.str, container->path.len));
606 if(res->cnt)
607 res->string_len += 2; /* '; ' */
608 res->cookies[res->cnt++] = cookie_iter;
610 res->string_len += lstrlenW(cookie_iter->name);
611 if(*cookie_iter->data)
612 res->string_len += 1 /* = */ + lstrlenW(cookie_iter->data);
617 return ERROR_SUCCESS;
620 static void cookie_set_to_string(const cookie_set_t *cookie_set, WCHAR *str)
622 WCHAR *ptr = str;
623 unsigned i, len;
625 for(i=0; i<cookie_set->cnt; i++) {
626 if(i) {
627 *ptr++ = ';';
628 *ptr++ = ' ';
631 len = lstrlenW(cookie_set->cookies[i]->name);
632 memcpy(ptr, cookie_set->cookies[i]->name, len*sizeof(WCHAR));
633 ptr += len;
635 if(*cookie_set->cookies[i]->data) {
636 *ptr++ = '=';
637 len = lstrlenW(cookie_set->cookies[i]->data);
638 memcpy(ptr, cookie_set->cookies[i]->data, len*sizeof(WCHAR));
639 ptr += len;
643 assert(ptr-str == cookie_set->string_len);
644 TRACE("%s\n", debugstr_wn(str, ptr-str));
647 DWORD get_cookie_header(const WCHAR *host, const WCHAR *path, WCHAR **ret)
649 cookie_set_t cookie_set = {0};
650 DWORD res;
652 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' '};
654 EnterCriticalSection(&cookie_cs);
656 res = get_cookie(substrz(host), substrz(path), INTERNET_COOKIE_HTTPONLY, &cookie_set);
657 if(res != ERROR_SUCCESS) {
658 LeaveCriticalSection(&cookie_cs);
659 return res;
662 if(cookie_set.cnt) {
663 WCHAR *header, *ptr;
665 ptr = header = heap_alloc(sizeof(cookieW) + (cookie_set.string_len + 3 /* crlf0 */) * sizeof(WCHAR));
666 if(header) {
667 memcpy(ptr, cookieW, sizeof(cookieW));
668 ptr += ARRAY_SIZE(cookieW);
670 cookie_set_to_string(&cookie_set, ptr);
671 heap_free(cookie_set.cookies);
672 ptr += cookie_set.string_len;
674 *ptr++ = '\r';
675 *ptr++ = '\n';
676 *ptr++ = 0;
678 *ret = header;
679 }else {
680 res = ERROR_NOT_ENOUGH_MEMORY;
682 }else {
683 *ret = NULL;
686 LeaveCriticalSection(&cookie_cs);
687 return res;
690 static void free_cookie_domain_list(struct list *list)
692 cookie_container_t *container;
693 cookie_domain_t *domain;
695 while(!list_empty(list)) {
696 domain = LIST_ENTRY(list_head(list), cookie_domain_t, entry);
698 free_cookie_domain_list(&domain->subdomain_list);
700 while(!list_empty(&domain->path_list)) {
701 container = LIST_ENTRY(list_head(&domain->path_list), cookie_container_t, entry);
703 while(!list_empty(&container->cookie_list))
704 delete_cookie(LIST_ENTRY(list_head(&container->cookie_list), cookie_t, entry));
706 heap_free(container->cookie_url);
707 list_remove(&container->entry);
708 heap_free(container);
711 heap_free(domain->domain);
712 list_remove(&domain->entry);
713 heap_free(domain);
717 /***********************************************************************
718 * InternetGetCookieExW (WININET.@)
720 * Retrieve cookie from the specified url
722 * It should be noted that on windows the lpszCookieName parameter is "not implemented".
723 * So it won't be implemented here.
725 * RETURNS
726 * TRUE on success
727 * FALSE on failure
730 BOOL WINAPI InternetGetCookieExW(LPCWSTR lpszUrl, LPCWSTR lpszCookieName,
731 LPWSTR lpCookieData, LPDWORD lpdwSize, DWORD flags, void *reserved)
733 cookie_set_t cookie_set = {0};
734 substr_t host, path;
735 DWORD res;
736 BOOL ret;
738 TRACE("(%s, %s, %p, %p, %x, %p)\n", debugstr_w(lpszUrl),debugstr_w(lpszCookieName), lpCookieData, lpdwSize, flags, reserved);
740 if (flags & ~INTERNET_COOKIE_HTTPONLY)
741 FIXME("flags 0x%08x not supported\n", flags);
743 if (!lpszUrl)
745 SetLastError(ERROR_INVALID_PARAMETER);
746 return FALSE;
749 ret = cookie_parse_url(lpszUrl, &host, &path);
750 if (!ret) {
751 SetLastError(ERROR_INVALID_PARAMETER);
752 return FALSE;
755 EnterCriticalSection(&cookie_cs);
757 res = get_cookie(host, path, flags, &cookie_set);
758 if(res != ERROR_SUCCESS) {
759 LeaveCriticalSection(&cookie_cs);
760 SetLastError(res);
761 return FALSE;
764 if(cookie_set.cnt) {
765 if(!lpCookieData || cookie_set.string_len+1 > *lpdwSize) {
766 *lpdwSize = (cookie_set.string_len + 1) * sizeof(WCHAR);
767 TRACE("returning %u\n", *lpdwSize);
768 if(lpCookieData) {
769 SetLastError(ERROR_INSUFFICIENT_BUFFER);
770 ret = FALSE;
772 }else {
773 *lpdwSize = cookie_set.string_len + 1;
774 cookie_set_to_string(&cookie_set, lpCookieData);
775 lpCookieData[cookie_set.string_len] = 0;
777 }else {
778 TRACE("no cookies found for %s\n", debugstr_wn(host.str, host.len));
779 SetLastError(ERROR_NO_MORE_ITEMS);
780 ret = FALSE;
783 heap_free(cookie_set.cookies);
784 LeaveCriticalSection(&cookie_cs);
785 return ret;
788 /***********************************************************************
789 * InternetGetCookieW (WININET.@)
791 * Retrieve cookie for the specified URL.
793 BOOL WINAPI InternetGetCookieW(const WCHAR *url, const WCHAR *name, WCHAR *data, DWORD *size)
795 TRACE("(%s, %s, %s, %p)\n", debugstr_w(url), debugstr_w(name), debugstr_w(data), size);
797 return InternetGetCookieExW(url, name, data, size, 0, NULL);
800 /***********************************************************************
801 * InternetGetCookieExA (WININET.@)
803 * Retrieve cookie from the specified url
805 * RETURNS
806 * TRUE on success
807 * FALSE on failure
810 BOOL WINAPI InternetGetCookieExA(LPCSTR lpszUrl, LPCSTR lpszCookieName,
811 LPSTR lpCookieData, LPDWORD lpdwSize, DWORD flags, void *reserved)
813 WCHAR *url, *name;
814 DWORD len, size = 0;
815 BOOL r;
817 TRACE("(%s %s %p %p(%u) %x %p)\n", debugstr_a(lpszUrl), debugstr_a(lpszCookieName),
818 lpCookieData, lpdwSize, lpdwSize ? *lpdwSize : 0, flags, reserved);
820 url = heap_strdupAtoW(lpszUrl);
821 name = heap_strdupAtoW(lpszCookieName);
823 r = InternetGetCookieExW( url, name, NULL, &len, flags, reserved );
824 if( r )
826 WCHAR *szCookieData;
828 szCookieData = heap_alloc(len * sizeof(WCHAR));
829 if( !szCookieData )
831 r = FALSE;
833 else
835 r = InternetGetCookieExW( url, name, szCookieData, &len, flags, reserved );
837 if(r) {
838 size = WideCharToMultiByte( CP_ACP, 0, szCookieData, len, NULL, 0, NULL, NULL);
839 if(lpCookieData) {
840 if(*lpdwSize >= size) {
841 WideCharToMultiByte( CP_ACP, 0, szCookieData, len, lpCookieData, *lpdwSize, NULL, NULL);
842 }else {
843 SetLastError(ERROR_INSUFFICIENT_BUFFER);
844 r = FALSE;
849 heap_free( szCookieData );
852 *lpdwSize = size;
853 heap_free( name );
854 heap_free( url );
855 return r;
858 /***********************************************************************
859 * InternetGetCookieA (WININET.@)
861 * See InternetGetCookieW.
863 BOOL WINAPI InternetGetCookieA(const char *url, const char *name, char *data, DWORD *size)
865 TRACE("(%s, %s, %p, %p)\n", debugstr_a(url), debugstr_a(name), data, size);
867 return InternetGetCookieExA(url, name, data, size, 0, NULL);
870 static BOOL is_domain_legal_for_cookie(substr_t domain, substr_t full_domain)
872 const WCHAR *ptr;
874 if(!domain.len || *domain.str == '.' || !full_domain.len || *full_domain.str == '.') {
875 SetLastError(ERROR_INVALID_NAME);
876 return FALSE;
879 if(domain.len > full_domain.len || !wmemchr(domain.str, '.', domain.len) || !wmemchr(full_domain.str, '.', full_domain.len))
880 return FALSE;
882 ptr = full_domain.str + full_domain.len - domain.len;
883 if (wcsnicmp(domain.str, ptr, domain.len) || (full_domain.len > domain.len && ptr[-1] != '.')) {
884 SetLastError(ERROR_INVALID_PARAMETER);
885 return FALSE;
888 return TRUE;
891 /***********************************************************************
892 * IsDomainLegalCookieDomainW (WININET.@)
894 BOOL WINAPI IsDomainLegalCookieDomainW(const WCHAR *domain, const WCHAR *full_domain)
896 FIXME("(%s, %s) semi-stub\n", debugstr_w(domain), debugstr_w(full_domain));
898 if (!domain || !full_domain) {
899 SetLastError(ERROR_INVALID_PARAMETER);
900 return FALSE;
903 return is_domain_legal_for_cookie(substrz(domain), substrz(full_domain));
906 static void substr_skip(substr_t *str, size_t len)
908 assert(str->len >= len);
909 str->str += len;
910 str->len -= len;
913 DWORD set_cookie(substr_t domain, substr_t path, substr_t name, substr_t data, DWORD flags)
915 cookie_container_t *container;
916 cookie_t *thisCookie;
917 substr_t value;
918 const WCHAR *end_ptr;
919 FILETIME expiry, create;
920 BOOL expired = FALSE, update_persistent = FALSE;
921 DWORD cookie_flags = 0, len;
923 TRACE("%s %s %s=%s %x\n", debugstr_wn(domain.str, domain.len), debugstr_wn(path.str, path.len),
924 debugstr_wn(name.str, name.len), debugstr_wn(data.str, data.len), flags);
926 memset(&expiry,0,sizeof(expiry));
927 GetSystemTimeAsFileTime(&create);
929 /* lots of information can be parsed out of the cookie value */
931 if(!(end_ptr = wmemchr(data.str, ';', data.len)))
932 end_ptr = data.str + data.len;
933 value = substr(data.str, end_ptr-data.str);
934 data.str += value.len;
935 data.len -= value.len;
937 for(;;) {
938 static const WCHAR szDomain[] = {'d','o','m','a','i','n','='};
939 static const WCHAR szPath[] = {'p','a','t','h','='};
940 static const WCHAR szExpires[] = {'e','x','p','i','r','e','s','='};
941 static const WCHAR szSecure[] = {'s','e','c','u','r','e'};
942 static const WCHAR szHttpOnly[] = {'h','t','t','p','o','n','l','y'};
943 static const WCHAR szVersion[] = {'v','e','r','s','i','o','n','='};
944 static const WCHAR max_ageW[] = {'m','a','x','-','a','g','e','='};
946 /* Skip ';' */
947 if(data.len)
948 substr_skip(&data, 1);
950 while(data.len && *data.str == ' ')
951 substr_skip(&data, 1);
953 if(!data.len)
954 break;
956 if(!(end_ptr = wmemchr(data.str, ';', data.len)))
957 end_ptr = data.str + data.len;
959 if(data.len >= (len = ARRAY_SIZE(szDomain)) && !wcsnicmp(data.str, szDomain, len)) {
960 substr_skip(&data, len);
962 if(data.len && *data.str == '.')
963 substr_skip(&data, 1);
965 if(!is_domain_legal_for_cookie(substr(data.str, end_ptr-data.str), domain))
966 return COOKIE_STATE_UNKNOWN;
968 domain = substr(data.str, end_ptr-data.str);
969 TRACE("Parsing new domain %s\n", debugstr_wn(domain.str, domain.len));
970 }else if(data.len >= (len = ARRAY_SIZE(szPath)) && !wcsnicmp(data.str, szPath, len)) {
971 substr_skip(&data, len);
972 path = substr(data.str, end_ptr - data.str);
973 TRACE("Parsing new path %s\n", debugstr_wn(path.str, path.len));
974 }else if(data.len >= (len = ARRAY_SIZE(szExpires)) && !wcsnicmp(data.str, szExpires, len)) {
975 SYSTEMTIME st;
976 WCHAR buf[128];
978 substr_skip(&data, len);
980 if(end_ptr > data.str && (end_ptr - data.str < ARRAY_SIZE(buf) - 1)) {
981 memcpy(buf, data.str, data.len*sizeof(WCHAR));
982 buf[data.len] = 0;
984 if (InternetTimeToSystemTimeW(data.str, &st, 0)) {
985 SystemTimeToFileTime(&st, &expiry);
987 if (CompareFileTime(&create,&expiry) > 0) {
988 TRACE("Cookie already expired.\n");
989 expired = TRUE;
993 }else if(data.len >= (len = ARRAY_SIZE(szSecure)) && !wcsnicmp(data.str, szSecure, len)) {
994 substr_skip(&data, len);
995 FIXME("secure not handled\n");
996 }else if(data.len >= (len = ARRAY_SIZE(szHttpOnly)) && !wcsnicmp(data.str, szHttpOnly, len)) {
997 substr_skip(&data, len);
999 if(!(flags & INTERNET_COOKIE_HTTPONLY)) {
1000 WARN("HTTP only cookie added without INTERNET_COOKIE_HTTPONLY flag\n");
1001 SetLastError(ERROR_INVALID_OPERATION);
1002 return COOKIE_STATE_REJECT;
1005 cookie_flags |= INTERNET_COOKIE_HTTPONLY;
1006 }else if(data.len >= (len = ARRAY_SIZE(szVersion)) && !wcsnicmp(data.str, szVersion, len)) {
1007 substr_skip(&data, len);
1009 FIXME("version not handled (%s)\n",debugstr_wn(data.str, data.len));
1010 }else if(data.len >= (len = ARRAY_SIZE(max_ageW)) && !wcsnicmp(data.str, max_ageW, len)) {
1011 /* Native doesn't support Max-Age attribute. */
1012 WARN("Max-Age ignored\n");
1013 }else if(data.len) {
1014 FIXME("Unknown additional option %s\n", debugstr_wn(data.str, data.len));
1017 substr_skip(&data, end_ptr - data.str);
1020 EnterCriticalSection(&cookie_cs);
1022 load_persistent_cookie(domain, path);
1024 container = get_cookie_container(domain, path, !expired);
1025 if(!container) {
1026 LeaveCriticalSection(&cookie_cs);
1027 return COOKIE_STATE_ACCEPT;
1030 if(!expiry.dwLowDateTime && !expiry.dwHighDateTime)
1031 cookie_flags |= INTERNET_COOKIE_IS_SESSION;
1032 else
1033 update_persistent = TRUE;
1035 if ((thisCookie = find_cookie(container, name))) {
1036 if ((thisCookie->flags & INTERNET_COOKIE_HTTPONLY) && !(flags & INTERNET_COOKIE_HTTPONLY)) {
1037 WARN("An attempt to override httponly cookie\n");
1038 SetLastError(ERROR_INVALID_OPERATION);
1039 LeaveCriticalSection(&cookie_cs);
1040 return COOKIE_STATE_REJECT;
1043 if (!(thisCookie->flags & INTERNET_COOKIE_IS_SESSION))
1044 update_persistent = TRUE;
1045 delete_cookie(thisCookie);
1048 TRACE("setting cookie %s=%s for domain %s path %s\n", debugstr_wn(name.str, name.len),
1049 debugstr_wn(value.str, value.len), debugstr_w(container->domain->domain),
1050 debugstr_wn(container->path.str, container->path.len));
1052 if (!expired) {
1053 cookie_t *new_cookie;
1055 new_cookie = alloc_cookie(name, value, expiry, create, cookie_flags);
1056 if(!new_cookie) {
1057 LeaveCriticalSection(&cookie_cs);
1058 return COOKIE_STATE_UNKNOWN;
1061 add_cookie(container, new_cookie);
1064 if (!update_persistent || save_persistent_cookie(container))
1066 LeaveCriticalSection(&cookie_cs);
1067 return COOKIE_STATE_ACCEPT;
1069 LeaveCriticalSection(&cookie_cs);
1070 return COOKIE_STATE_UNKNOWN;
1073 /***********************************************************************
1074 * InternetSetCookieExW (WININET.@)
1076 * Sets cookie for the specified url
1078 DWORD WINAPI InternetSetCookieExW(LPCWSTR lpszUrl, LPCWSTR lpszCookieName,
1079 LPCWSTR lpCookieData, DWORD flags, DWORD_PTR reserved)
1081 substr_t host, path, name, data;
1082 BOOL ret;
1084 TRACE("(%s, %s, %s, %x, %lx)\n", debugstr_w(lpszUrl), debugstr_w(lpszCookieName),
1085 debugstr_w(lpCookieData), flags, reserved);
1087 if (flags & ~INTERNET_COOKIE_HTTPONLY)
1088 FIXME("flags %x not supported\n", flags);
1090 if (!lpszUrl || !lpCookieData)
1092 SetLastError(ERROR_INVALID_PARAMETER);
1093 return COOKIE_STATE_UNKNOWN;
1096 ret = cookie_parse_url(lpszUrl, &host, &path);
1097 if (!ret || !host.len) return COOKIE_STATE_UNKNOWN;
1099 if (!lpszCookieName) {
1100 const WCHAR *ptr;
1102 /* some apps (or is it us??) try to add a cookie with no cookie name, but
1103 * the cookie data in the form of name[=data].
1105 if (!(ptr = wcschr(lpCookieData, '=')))
1106 ptr = lpCookieData + lstrlenW(lpCookieData);
1108 name = substr(lpCookieData, ptr - lpCookieData);
1109 data = substrz(*ptr == '=' ? ptr+1 : ptr);
1110 }else {
1111 name = substrz(lpszCookieName);
1112 data = substrz(lpCookieData);
1115 return set_cookie(host, path, name, data, flags);
1118 /***********************************************************************
1119 * InternetSetCookieW (WININET.@)
1121 * Sets a cookie for the specified URL.
1123 BOOL WINAPI InternetSetCookieW(const WCHAR *url, const WCHAR *name, const WCHAR *data)
1125 TRACE("(%s, %s, %s)\n", debugstr_w(url), debugstr_w(name), debugstr_w(data));
1127 return InternetSetCookieExW(url, name, data, 0, 0) == COOKIE_STATE_ACCEPT;
1130 /***********************************************************************
1131 * InternetSetCookieA (WININET.@)
1133 * Sets cookie for the specified url
1135 * RETURNS
1136 * TRUE on success
1137 * FALSE on failure
1140 BOOL WINAPI InternetSetCookieA(LPCSTR lpszUrl, LPCSTR lpszCookieName,
1141 LPCSTR lpCookieData)
1143 LPWSTR data, url, name;
1144 BOOL r;
1146 TRACE("(%s,%s,%s)\n", debugstr_a(lpszUrl),
1147 debugstr_a(lpszCookieName), debugstr_a(lpCookieData));
1149 url = heap_strdupAtoW(lpszUrl);
1150 name = heap_strdupAtoW(lpszCookieName);
1151 data = heap_strdupAtoW(lpCookieData);
1153 r = InternetSetCookieW( url, name, data );
1155 heap_free( data );
1156 heap_free( name );
1157 heap_free( url );
1158 return r;
1161 /***********************************************************************
1162 * InternetSetCookieExA (WININET.@)
1164 * See InternetSetCookieExW.
1166 DWORD WINAPI InternetSetCookieExA( LPCSTR lpszURL, LPCSTR lpszCookieName, LPCSTR lpszCookieData,
1167 DWORD dwFlags, DWORD_PTR dwReserved)
1169 WCHAR *data, *url, *name;
1170 DWORD r;
1172 TRACE("(%s, %s, %s, %x, %lx)\n", debugstr_a(lpszURL), debugstr_a(lpszCookieName),
1173 debugstr_a(lpszCookieData), dwFlags, dwReserved);
1175 url = heap_strdupAtoW(lpszURL);
1176 name = heap_strdupAtoW(lpszCookieName);
1177 data = heap_strdupAtoW(lpszCookieData);
1179 r = InternetSetCookieExW(url, name, data, dwFlags, dwReserved);
1181 heap_free( data );
1182 heap_free( name );
1183 heap_free( url );
1184 return r;
1187 /***********************************************************************
1188 * InternetClearAllPerSiteCookieDecisions (WININET.@)
1190 * Clears all per-site decisions about cookies.
1192 * RETURNS
1193 * TRUE on success
1194 * FALSE on failure
1197 BOOL WINAPI InternetClearAllPerSiteCookieDecisions( VOID )
1199 FIXME("stub\n");
1200 return TRUE;
1203 /***********************************************************************
1204 * InternetEnumPerSiteCookieDecisionA (WININET.@)
1206 * See InternetEnumPerSiteCookieDecisionW.
1208 BOOL WINAPI InternetEnumPerSiteCookieDecisionA( LPSTR pszSiteName, ULONG *pcSiteNameSize,
1209 ULONG *pdwDecision, ULONG dwIndex )
1211 FIXME("(%s, %p, %p, 0x%08x) stub\n",
1212 debugstr_a(pszSiteName), pcSiteNameSize, pdwDecision, dwIndex);
1213 return FALSE;
1216 /***********************************************************************
1217 * InternetEnumPerSiteCookieDecisionW (WININET.@)
1219 * Enumerates all per-site decisions about cookies.
1221 * RETURNS
1222 * TRUE on success
1223 * FALSE on failure
1226 BOOL WINAPI InternetEnumPerSiteCookieDecisionW( LPWSTR pszSiteName, ULONG *pcSiteNameSize,
1227 ULONG *pdwDecision, ULONG dwIndex )
1229 FIXME("(%s, %p, %p, 0x%08x) stub\n",
1230 debugstr_w(pszSiteName), pcSiteNameSize, pdwDecision, dwIndex);
1231 return FALSE;
1234 /***********************************************************************
1235 * InternetGetPerSiteCookieDecisionA (WININET.@)
1237 BOOL WINAPI InternetGetPerSiteCookieDecisionA( LPCSTR pwchHostName, ULONG *pResult )
1239 FIXME("(%s, %p) stub\n", debugstr_a(pwchHostName), pResult);
1240 return FALSE;
1243 /***********************************************************************
1244 * InternetGetPerSiteCookieDecisionW (WININET.@)
1246 BOOL WINAPI InternetGetPerSiteCookieDecisionW( LPCWSTR pwchHostName, ULONG *pResult )
1248 FIXME("(%s, %p) stub\n", debugstr_w(pwchHostName), pResult);
1249 return FALSE;
1252 /***********************************************************************
1253 * InternetSetPerSiteCookieDecisionA (WININET.@)
1255 BOOL WINAPI InternetSetPerSiteCookieDecisionA( LPCSTR pchHostName, DWORD dwDecision )
1257 FIXME("(%s, 0x%08x) stub\n", debugstr_a(pchHostName), dwDecision);
1258 return FALSE;
1261 /***********************************************************************
1262 * InternetSetPerSiteCookieDecisionW (WININET.@)
1264 BOOL WINAPI InternetSetPerSiteCookieDecisionW( LPCWSTR pchHostName, DWORD dwDecision )
1266 FIXME("(%s, 0x%08x) stub\n", debugstr_w(pchHostName), dwDecision);
1267 return FALSE;
1270 void free_cookie(void)
1272 EnterCriticalSection(&cookie_cs);
1274 free_cookie_domain_list(&domain_list);
1276 LeaveCriticalSection(&cookie_cs);