wininet: Make cookies functions thread-safe.
[wine] / dlls / wininet / cookie.c
1 /*
2  * Wininet - cookie handling stuff
3  *
4  * Copyright 2002 TransGaming Technologies Inc.
5  *
6  * David Hammerton
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #if defined(__MINGW32__) || defined (_MSC_VER)
27 #include <ws2tcpip.h>
28 #endif
29
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #ifdef HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37
38 #include "windef.h"
39 #include "winbase.h"
40 #include "wininet.h"
41 #include "winerror.h"
42
43 #include "wine/debug.h"
44 #include "internet.h"
45
46 #define RESPONSE_TIMEOUT        30            /* FROM internet.c */
47
48
49 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
50
51 /* FIXME
52  *     Cookies could use A LOT OF MEMORY. We need some kind of memory management here!
53  */
54
55 typedef struct _cookie_domain cookie_domain;
56 typedef struct _cookie cookie;
57
58 struct _cookie
59 {
60     struct list entry;
61
62     struct _cookie_domain *parent;
63
64     LPWSTR lpCookieName;
65     LPWSTR lpCookieData;
66     DWORD flags;
67     FILETIME expiry;
68     FILETIME create;
69 };
70
71 struct _cookie_domain
72 {
73     struct list entry;
74
75     LPWSTR lpCookieDomain;
76     LPWSTR lpCookiePath;
77     struct list cookie_list;
78 };
79
80 static CRITICAL_SECTION cookie_cs;
81 static CRITICAL_SECTION_DEBUG cookie_cs_debug =
82 {
83     0, 0, &cookie_cs,
84     { &cookie_cs_debug.ProcessLocksList, &cookie_cs_debug.ProcessLocksList },
85     0, 0, { (DWORD_PTR)(__FILE__ ": cookie_cs") }
86 };
87 static CRITICAL_SECTION cookie_cs = { &cookie_cs_debug, -1, 0, 0, 0, 0 };
88 static struct list domain_list = LIST_INIT(domain_list);
89
90 static cookie *COOKIE_addCookie(cookie_domain *domain, LPCWSTR name, LPCWSTR data,
91         FILETIME expiry, FILETIME create, DWORD flags);
92 static cookie *COOKIE_findCookie(cookie_domain *domain, LPCWSTR lpszCookieName);
93 static void COOKIE_deleteCookie(cookie *deadCookie, BOOL deleteDomain);
94 static cookie_domain *COOKIE_addDomain(LPCWSTR domain, LPCWSTR path);
95 static void COOKIE_deleteDomain(cookie_domain *deadDomain);
96 static BOOL COOKIE_matchDomain(LPCWSTR lpszCookieDomain, LPCWSTR lpszCookiePath,
97         cookie_domain *searchDomain, BOOL allow_partial);
98
99 static BOOL create_cookie_url(LPCWSTR domain, LPCWSTR path, WCHAR *buf, DWORD buf_len)
100 {
101     static const WCHAR cookie_prefix[] = {'C','o','o','k','i','e',':'};
102
103     WCHAR *p;
104     DWORD len;
105
106     if(buf_len < sizeof(cookie_prefix)/sizeof(WCHAR))
107         return FALSE;
108     memcpy(buf, cookie_prefix, sizeof(cookie_prefix));
109     buf += sizeof(cookie_prefix)/sizeof(WCHAR);
110     buf_len -= sizeof(cookie_prefix)/sizeof(WCHAR);
111     p = buf;
112
113     len = buf_len;
114     if(!GetUserNameW(buf, &len))
115         return FALSE;
116     buf += len-1;
117     buf_len -= len-1;
118
119     if(!buf_len)
120         return FALSE;
121     *(buf++) = '@';
122     buf_len--;
123
124     len = strlenW(domain);
125     if(len >= buf_len)
126         return FALSE;
127     memcpy(buf, domain, len*sizeof(WCHAR));
128     buf += len;
129     buf_len -= len;
130
131     len = strlenW(path);
132     if(len >= buf_len)
133         return FALSE;
134     memcpy(buf, path, len*sizeof(WCHAR));
135     buf += len;
136
137     *buf = 0;
138
139     for(; *p; p++)
140         *p = tolowerW(*p);
141     return TRUE;
142 }
143
144 static BOOL load_persistent_cookie(LPCWSTR domain, LPCWSTR path)
145 {
146     INTERNET_CACHE_ENTRY_INFOW *info;
147     cookie_domain *domain_container = NULL;
148     cookie *old_cookie;
149     struct list *iter;
150     WCHAR cookie_url[MAX_PATH];
151     HANDLE cookie;
152     char *str = NULL, *pbeg, *pend;
153     DWORD size, flags;
154     WCHAR *name, *data;
155     FILETIME expiry, create, time;
156
157     if (!create_cookie_url(domain, path, cookie_url, sizeof(cookie_url)/sizeof(cookie_url[0])))
158         return FALSE;
159
160     size = 0;
161     RetrieveUrlCacheEntryStreamW(cookie_url, NULL, &size, FALSE, 0);
162     if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
163         return TRUE;
164     info = heap_alloc(size);
165     if(!info)
166         return FALSE;
167     cookie = RetrieveUrlCacheEntryStreamW(cookie_url, info, &size, FALSE, 0);
168     size = info->dwSizeLow;
169     heap_free(info);
170     if(!cookie)
171         return FALSE;
172
173     if(!(str = heap_alloc(size)) || !ReadUrlCacheEntryStream(cookie, 0, str, &size, 0)) {
174         UnlockUrlCacheEntryStream(cookie, 0);
175         heap_free(str);
176         return FALSE;
177     }
178     UnlockUrlCacheEntryStream(cookie, 0);
179
180     LIST_FOR_EACH(iter, &domain_list)
181     {
182         domain_container = LIST_ENTRY(iter, cookie_domain, entry);
183         if(COOKIE_matchDomain(domain, path, domain_container, FALSE))
184             break;
185         domain_container = NULL;
186     }
187     if(!domain_container)
188         domain_container = COOKIE_addDomain(domain, path);
189     if(!domain_container) {
190         heap_free(str);
191         return FALSE;
192     }
193
194     GetSystemTimeAsFileTime(&time);
195     for(pbeg=str; pbeg && *pbeg; name=data=NULL) {
196         pend = strchr(pbeg, '\n');
197         if(!pend)
198             break;
199         *pend = 0;
200         name = heap_strdupAtoW(pbeg);
201
202         pbeg = pend+1;
203         pend = strchr(pbeg, '\n');
204         if(!pend)
205             break;
206         *pend = 0;
207         data = heap_strdupAtoW(pbeg);
208
209         pbeg = pend+1;
210         pbeg = strchr(pend+1, '\n');
211         if(!pbeg)
212             break;
213         sscanf(pbeg, "%u %u %u %u %u", &flags, &expiry.dwLowDateTime, &expiry.dwHighDateTime,
214                 &create.dwLowDateTime, &create.dwHighDateTime);
215
216         /* skip "*\n" */
217         pbeg = strchr(pbeg, '*');
218         if(pbeg) {
219             pbeg++;
220             if(*pbeg)
221                 pbeg++;
222         }
223
224         if(!name || !data)
225             break;
226
227         if(CompareFileTime(&time, &expiry) <= 0) {
228             if((old_cookie = COOKIE_findCookie(domain_container, name)))
229                 COOKIE_deleteCookie(old_cookie, FALSE);
230             COOKIE_addCookie(domain_container, name, data, expiry, create, flags);
231         }
232         heap_free(name);
233         heap_free(data);
234     }
235     heap_free(name);
236     heap_free(data);
237
238     return TRUE;
239 }
240
241 static BOOL save_persistent_cookie(cookie_domain *domain)
242 {
243     static const WCHAR txtW[] = {'t','x','t',0};
244
245     WCHAR cookie_url[MAX_PATH], cookie_file[MAX_PATH];
246     HANDLE cookie_handle;
247     cookie *cookie_container = NULL, *cookie_iter;
248     BOOL do_save = FALSE;
249     char buf[64], *dyn_buf;
250     FILETIME time;
251
252     if (!create_cookie_url(domain->lpCookieDomain, domain->lpCookiePath, cookie_url, sizeof(cookie_url)/sizeof(cookie_url[0])))
253         return FALSE;
254
255     /* check if there's anything to save */
256     GetSystemTimeAsFileTime(&time);
257     LIST_FOR_EACH_ENTRY_SAFE(cookie_container, cookie_iter, &domain->cookie_list, cookie, entry)
258     {
259         if((cookie_container->expiry.dwLowDateTime || cookie_container->expiry.dwHighDateTime)
260                 && CompareFileTime(&time, &cookie_container->expiry) > 0) {
261             COOKIE_deleteCookie(cookie_container, FALSE);
262             continue;
263         }
264
265         if(!(cookie_container->flags & INTERNET_COOKIE_IS_SESSION)) {
266             do_save = TRUE;
267             break;
268         }
269     }
270     if(!do_save) {
271         DeleteUrlCacheEntryW(cookie_url);
272         return TRUE;
273     }
274
275     if(!CreateUrlCacheEntryW(cookie_url, 0, txtW, cookie_file, 0))
276         return FALSE;
277     cookie_handle = CreateFileW(cookie_file, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
278     if(cookie_handle == INVALID_HANDLE_VALUE) {
279         DeleteFileW(cookie_file);
280         return FALSE;
281     }
282
283     LIST_FOR_EACH_ENTRY(cookie_container, &domain->cookie_list, cookie, entry)
284     {
285         if(cookie_container->flags & INTERNET_COOKIE_IS_SESSION)
286             continue;
287
288         dyn_buf = heap_strdupWtoA(cookie_container->lpCookieName);
289         if(!dyn_buf || !WriteFile(cookie_handle, dyn_buf, strlen(dyn_buf), NULL, NULL)) {
290             heap_free(dyn_buf);
291             do_save = FALSE;
292             break;
293         }
294         heap_free(dyn_buf);
295         if(!WriteFile(cookie_handle, "\n", 1, NULL, NULL)) {
296             do_save = FALSE;
297             break;
298         }
299
300         dyn_buf = heap_strdupWtoA(cookie_container->lpCookieData);
301         if(!dyn_buf || !WriteFile(cookie_handle, dyn_buf, strlen(dyn_buf), NULL, NULL)) {
302             heap_free(dyn_buf);
303             do_save = FALSE;
304             break;
305         }
306         heap_free(dyn_buf);
307         if(!WriteFile(cookie_handle, "\n", 1, NULL, NULL)) {
308             do_save = FALSE;
309             break;
310         }
311
312         dyn_buf = heap_strdupWtoA(domain->lpCookieDomain);
313         if(!dyn_buf || !WriteFile(cookie_handle, dyn_buf, strlen(dyn_buf), NULL, NULL)) {
314             heap_free(dyn_buf);
315             do_save = FALSE;
316             break;
317         }
318         heap_free(dyn_buf);
319
320         dyn_buf = heap_strdupWtoA(domain->lpCookiePath);
321         if(!dyn_buf || !WriteFile(cookie_handle, dyn_buf, strlen(dyn_buf), NULL, NULL)) {
322             heap_free(dyn_buf);
323             do_save = FALSE;
324             break;
325         }
326         heap_free(dyn_buf);
327
328         sprintf(buf, "\n%u\n%u\n%u\n%u\n%u\n*\n", cookie_container->flags,
329                 cookie_container->expiry.dwLowDateTime, cookie_container->expiry.dwHighDateTime,
330                 cookie_container->create.dwLowDateTime, cookie_container->create.dwHighDateTime);
331         if(!WriteFile(cookie_handle, buf, strlen(buf), NULL, NULL)) {
332             do_save = FALSE;
333             break;
334         }
335     }
336
337     CloseHandle(cookie_handle);
338     if(!do_save) {
339         ERR("error saving cookie file\n");
340         DeleteFileW(cookie_file);
341         return FALSE;
342     }
343
344     memset(&time, 0, sizeof(time));
345     return CommitUrlCacheEntryW(cookie_url, cookie_file, time, time, 0, NULL, 0, txtW, 0);
346 }
347
348 /* adds a cookie to the domain */
349 static cookie *COOKIE_addCookie(cookie_domain *domain, LPCWSTR name, LPCWSTR data,
350         FILETIME expiry, FILETIME create, DWORD flags)
351 {
352     cookie *newCookie = heap_alloc(sizeof(cookie));
353     if (!newCookie)
354         return NULL;
355
356     newCookie->lpCookieName = heap_strdupW(name);
357     newCookie->lpCookieData = heap_strdupW(data);
358
359     if (!newCookie->lpCookieName || !newCookie->lpCookieData)
360     {
361         heap_free(newCookie->lpCookieName);
362         heap_free(newCookie->lpCookieData);
363         heap_free(newCookie);
364
365         return NULL;
366     }
367
368     newCookie->flags = flags;
369     newCookie->expiry = expiry;
370     newCookie->create = create;
371
372     TRACE("added cookie %p (data is %s)\n", newCookie, debugstr_w(data) );
373
374     list_add_tail(&domain->cookie_list, &newCookie->entry);
375     newCookie->parent = domain;
376     return newCookie;
377 }
378
379
380 /* finds a cookie in the domain matching the cookie name */
381 static cookie *COOKIE_findCookie(cookie_domain *domain, LPCWSTR lpszCookieName)
382 {
383     struct list * cursor;
384     TRACE("(%p, %s)\n", domain, debugstr_w(lpszCookieName));
385
386     LIST_FOR_EACH(cursor, &domain->cookie_list)
387     {
388         cookie *searchCookie = LIST_ENTRY(cursor, cookie, entry);
389         BOOL candidate = TRUE;
390         if (candidate && lpszCookieName)
391         {
392             if (candidate && !searchCookie->lpCookieName)
393                 candidate = FALSE;
394             if (candidate && strcmpW(lpszCookieName, searchCookie->lpCookieName) != 0)
395                 candidate = FALSE;
396         }
397         if (candidate)
398             return searchCookie;
399     }
400     return NULL;
401 }
402
403 /* removes a cookie from the list, if its the last cookie we also remove the domain */
404 static void COOKIE_deleteCookie(cookie *deadCookie, BOOL deleteDomain)
405 {
406     heap_free(deadCookie->lpCookieName);
407     heap_free(deadCookie->lpCookieData);
408     list_remove(&deadCookie->entry);
409
410     /* special case: last cookie, lets remove the domain to save memory */
411     if (list_empty(&deadCookie->parent->cookie_list) && deleteDomain)
412         COOKIE_deleteDomain(deadCookie->parent);
413     heap_free(deadCookie);
414 }
415
416 /* allocates a domain and adds it to the end */
417 static cookie_domain *COOKIE_addDomain(LPCWSTR domain, LPCWSTR path)
418 {
419     cookie_domain *newDomain = heap_alloc(sizeof(cookie_domain));
420
421     list_init(&newDomain->entry);
422     list_init(&newDomain->cookie_list);
423     newDomain->lpCookieDomain = heap_strdupW(domain);
424     newDomain->lpCookiePath = heap_strdupW(path);
425
426     list_add_tail(&domain_list, &newDomain->entry);
427
428     TRACE("Adding domain: %p\n", newDomain);
429     return newDomain;
430 }
431
432 static BOOL COOKIE_crackUrlSimple(LPCWSTR lpszUrl, LPWSTR hostName, int hostNameLen, LPWSTR path, int pathLen)
433 {
434     URL_COMPONENTSW UrlComponents;
435
436     UrlComponents.lpszExtraInfo = NULL;
437     UrlComponents.lpszPassword = NULL;
438     UrlComponents.lpszScheme = NULL;
439     UrlComponents.lpszUrlPath = path;
440     UrlComponents.lpszUserName = NULL;
441     UrlComponents.lpszHostName = hostName;
442     UrlComponents.dwExtraInfoLength = 0;
443     UrlComponents.dwPasswordLength = 0;
444     UrlComponents.dwSchemeLength = 0;
445     UrlComponents.dwUserNameLength = 0;
446     UrlComponents.dwHostNameLength = hostNameLen;
447     UrlComponents.dwUrlPathLength = pathLen;
448
449     if (!InternetCrackUrlW(lpszUrl, 0, 0, &UrlComponents)) return FALSE;
450
451     /* discard the webpage off the end of the path */
452     if (UrlComponents.dwUrlPathLength)
453     {
454         if (path[UrlComponents.dwUrlPathLength - 1] != '/')
455         {
456             WCHAR *ptr;
457             if ((ptr = strrchrW(path, '/'))) *(++ptr) = 0;
458             else
459             {
460                 path[0] = '/';
461                 path[1] = 0;
462             }
463         }
464     }
465     else if (pathLen >= 2)
466     {
467         path[0] = '/';
468         path[1] = 0;
469     }
470     return TRUE;
471 }
472
473 /* match a domain. domain must match if the domain is not NULL. path must match if the path is not NULL */
474 static BOOL COOKIE_matchDomain(LPCWSTR lpszCookieDomain, LPCWSTR lpszCookiePath,
475                                cookie_domain *searchDomain, BOOL allow_partial)
476 {
477     TRACE("searching on domain %p\n", searchDomain);
478         if (lpszCookieDomain)
479         {
480             if (!searchDomain->lpCookieDomain)
481             return FALSE;
482
483             TRACE("comparing domain %s with %s\n",
484             debugstr_w(lpszCookieDomain),
485             debugstr_w(searchDomain->lpCookieDomain));
486
487         if (allow_partial && !strstrW(lpszCookieDomain, searchDomain->lpCookieDomain))
488             return FALSE;
489         else if (!allow_partial && lstrcmpW(lpszCookieDomain, searchDomain->lpCookieDomain) != 0)
490             return FALSE;
491         }
492     if (lpszCookiePath)
493     {
494         INT len;
495         TRACE("comparing paths: %s with %s\n", debugstr_w(lpszCookiePath), debugstr_w(searchDomain->lpCookiePath));
496         /* paths match at the beginning.  so a path of  /foo would match
497          * /foobar and /foo/bar
498          */
499         if (!searchDomain->lpCookiePath)
500             return FALSE;
501         if (allow_partial)
502         {
503             len = lstrlenW(searchDomain->lpCookiePath);
504             if (strncmpiW(searchDomain->lpCookiePath, lpszCookiePath, len)!=0)
505                 return FALSE;
506         }
507         else if (strcmpW(lpszCookiePath, searchDomain->lpCookiePath))
508             return FALSE;
509
510         }
511         return TRUE;
512 }
513
514 /* remove a domain from the list and delete it */
515 static void COOKIE_deleteDomain(cookie_domain *deadDomain)
516 {
517     struct list * cursor;
518     while ((cursor = list_tail(&deadDomain->cookie_list)))
519     {
520         COOKIE_deleteCookie(LIST_ENTRY(cursor, cookie, entry), FALSE);
521         list_remove(cursor);
522     }
523     heap_free(deadDomain->lpCookieDomain);
524     heap_free(deadDomain->lpCookiePath);
525
526     list_remove(&deadDomain->entry);
527
528     heap_free(deadDomain);
529 }
530
531 BOOL get_cookie(const WCHAR *host, const WCHAR *path, WCHAR *cookie_data, DWORD *size)
532 {
533     unsigned cnt = 0, len, domain_count = 0, cookie_count = 0;
534     cookie_domain *domain;
535     FILETIME tm;
536
537     GetSystemTimeAsFileTime(&tm);
538
539     EnterCriticalSection(&cookie_cs);
540
541     load_persistent_cookie(host, path);
542
543     LIST_FOR_EACH_ENTRY(domain, &domain_list, cookie_domain, entry) {
544         struct list *cursor, *cursor2;
545
546         if(!COOKIE_matchDomain(host, path, domain, TRUE))
547             continue;
548
549         domain_count++;
550         TRACE("found domain %p\n", domain);
551
552         LIST_FOR_EACH_SAFE(cursor, cursor2, &domain->cookie_list) {
553             cookie *cookie_iter = LIST_ENTRY(cursor, cookie, entry);
554
555             /* check for expiry */
556             if((cookie_iter->expiry.dwLowDateTime != 0 || cookie_iter->expiry.dwHighDateTime != 0)
557                 && CompareFileTime(&tm, &cookie_iter->expiry)  > 0)
558             {
559                 TRACE("Found expired cookie. deleting\n");
560                 COOKIE_deleteCookie(cookie_iter, FALSE);
561                 continue;
562             }
563
564             if(!cookie_data) { /* return the size of the buffer required to lpdwSize */
565                 if (cookie_count)
566                     cnt += 2; /* '; ' */
567                 cnt += strlenW(cookie_iter->lpCookieName);
568                 if ((len = strlenW(cookie_iter->lpCookieData))) {
569                     cnt += 1; /* = */
570                     cnt += len;
571                 }
572             }else {
573                 static const WCHAR szsc[] = { ';',' ',0 };
574                 static const WCHAR szname[] = { '%','s',0 };
575                 static const WCHAR szdata[] = { '=','%','s',0 };
576
577                 if (cookie_count) cnt += snprintfW(cookie_data + cnt, *size - cnt, szsc);
578                 cnt += snprintfW(cookie_data + cnt, *size - cnt, szname, cookie_iter->lpCookieName);
579
580                 if (cookie_iter->lpCookieData[0])
581                     cnt += snprintfW(cookie_data + cnt, *size - cnt, szdata, cookie_iter->lpCookieData);
582
583                 TRACE("Cookie: %s\n", debugstr_w(cookie_data));
584             }
585             cookie_count++;
586         }
587     }
588
589     LeaveCriticalSection(&cookie_cs);
590
591     if (!domain_count) {
592         TRACE("no cookies found for %s\n", debugstr_w(host));
593         SetLastError(ERROR_NO_MORE_ITEMS);
594         return FALSE;
595     }
596
597     if(!cookie_data) {
598         *size = (cnt + 1) * sizeof(WCHAR);
599         TRACE("returning %u\n", *size);
600         return TRUE;
601     }
602
603     *size = cnt + 1;
604
605     TRACE("Returning %u (from %u domains): %s\n", cnt, domain_count, debugstr_w(cookie_data));
606     return cnt != 0;
607 }
608
609 /***********************************************************************
610  *           InternetGetCookieW (WININET.@)
611  *
612  * Retrieve cookie from the specified url
613  *
614  *  It should be noted that on windows the lpszCookieName parameter is "not implemented".
615  *    So it won't be implemented here.
616  *
617  * RETURNS
618  *    TRUE  on success
619  *    FALSE on failure
620  *
621  */
622 BOOL WINAPI InternetGetCookieW(LPCWSTR lpszUrl, LPCWSTR lpszCookieName,
623     LPWSTR lpCookieData, LPDWORD lpdwSize)
624 {
625     WCHAR host[INTERNET_MAX_HOST_NAME_LENGTH], path[INTERNET_MAX_PATH_LENGTH];
626     BOOL ret;
627
628     TRACE("(%s, %s, %p, %p)\n", debugstr_w(lpszUrl),debugstr_w(lpszCookieName), lpCookieData, lpdwSize);
629
630     if (!lpszUrl)
631     {
632         SetLastError(ERROR_INVALID_PARAMETER);
633         return FALSE;
634     }
635
636     host[0] = 0;
637     ret = COOKIE_crackUrlSimple(lpszUrl, host, sizeof(host)/sizeof(host[0]), path, sizeof(path)/sizeof(path[0]));
638     if (!ret || !host[0]) {
639         SetLastError(ERROR_INVALID_PARAMETER);
640         return FALSE;
641     }
642
643     return get_cookie(host, path, lpCookieData, lpdwSize);
644 }
645
646
647 /***********************************************************************
648  *           InternetGetCookieA (WININET.@)
649  *
650  * Retrieve cookie from the specified url
651  *
652  * RETURNS
653  *    TRUE  on success
654  *    FALSE on failure
655  *
656  */
657 BOOL WINAPI InternetGetCookieA(LPCSTR lpszUrl, LPCSTR lpszCookieName,
658     LPSTR lpCookieData, LPDWORD lpdwSize)
659 {
660     DWORD len;
661     LPWSTR szCookieData = NULL, url, name;
662     BOOL r;
663
664     TRACE("(%s,%s,%p)\n", debugstr_a(lpszUrl), debugstr_a(lpszCookieName),
665         lpCookieData);
666
667     url = heap_strdupAtoW(lpszUrl);
668     name = heap_strdupAtoW(lpszCookieName);
669
670     r = InternetGetCookieW( url, name, NULL, &len );
671     if( r )
672     {
673         szCookieData = heap_alloc(len * sizeof(WCHAR));
674         if( !szCookieData )
675         {
676             r = FALSE;
677         }
678         else
679         {
680             r = InternetGetCookieW( url, name, szCookieData, &len );
681
682             *lpdwSize = WideCharToMultiByte( CP_ACP, 0, szCookieData, len,
683                                     lpCookieData, *lpdwSize, NULL, NULL );
684         }
685     }
686     heap_free( szCookieData );
687     heap_free( name );
688     heap_free( url );
689     return r;
690 }
691
692
693 /***********************************************************************
694  *           IsDomainLegalCookieDomainW (WININET.@)
695  */
696 BOOL WINAPI IsDomainLegalCookieDomainW( LPCWSTR s1, LPCWSTR s2 )
697 {
698     DWORD s1_len, s2_len;
699
700     FIXME("(%s, %s) semi-stub\n", debugstr_w(s1), debugstr_w(s2));
701
702     if (!s1 || !s2)
703     {
704         SetLastError(ERROR_INVALID_PARAMETER);
705         return FALSE;
706     }
707     if (s1[0] == '.' || !s1[0] || s2[0] == '.' || !s2[0])
708     {
709         SetLastError(ERROR_INVALID_NAME);
710         return FALSE;
711     }
712     if(!strchrW(s1, '.') || !strchrW(s2, '.'))
713         return FALSE;
714
715     s1_len = strlenW(s1);
716     s2_len = strlenW(s2);
717     if (s1_len > s2_len)
718         return FALSE;
719
720     if (strncmpiW(s1, s2+s2_len-s1_len, s1_len) || (s2_len>s1_len && s2[s2_len-s1_len-1]!='.'))
721     {
722         SetLastError(ERROR_INVALID_PARAMETER);
723         return FALSE;
724     }
725
726     return TRUE;
727 }
728
729 BOOL set_cookie(LPCWSTR domain, LPCWSTR path, LPCWSTR cookie_name, LPCWSTR cookie_data)
730 {
731     cookie_domain *thisCookieDomain = NULL;
732     cookie *thisCookie;
733     struct list *cursor;
734     LPWSTR data, value;
735     WCHAR *ptr;
736     FILETIME expiry, create;
737     BOOL expired = FALSE, update_persistent = FALSE;
738     DWORD flags = 0;
739
740     value = data = heap_strdupW(cookie_data);
741     if (!data)
742     {
743         ERR("could not allocate the cookie data buffer\n");
744         return FALSE;
745     }
746
747     memset(&expiry,0,sizeof(expiry));
748     GetSystemTimeAsFileTime(&create);
749
750     /* lots of information can be parsed out of the cookie value */
751
752     ptr = data;
753     for (;;)
754     {
755         static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
756         static const WCHAR szPath[] = {'p','a','t','h','=',0};
757         static const WCHAR szExpires[] = {'e','x','p','i','r','e','s','=',0};
758         static const WCHAR szSecure[] = {'s','e','c','u','r','e',0};
759         static const WCHAR szHttpOnly[] = {'h','t','t','p','o','n','l','y',0};
760
761         if (!(ptr = strchrW(ptr,';'))) break;
762         *ptr++ = 0;
763
764         if (value != data) heap_free(value);
765         value = heap_alloc((ptr - data) * sizeof(WCHAR));
766         if (value == NULL)
767         {
768             heap_free(data);
769             ERR("could not allocate the cookie value buffer\n");
770             return FALSE;
771         }
772         strcpyW(value, data);
773
774         while (*ptr == ' ') ptr++; /* whitespace */
775
776         if (strncmpiW(ptr, szDomain, 7) == 0)
777         {
778             WCHAR *end_ptr;
779
780             ptr += sizeof(szDomain)/sizeof(szDomain[0])-1;
781             if(*ptr == '.')
782                 ptr++;
783             end_ptr = strchrW(ptr, ';');
784             if(end_ptr)
785                 *end_ptr = 0;
786
787             if(!IsDomainLegalCookieDomainW(ptr, domain))
788             {
789                 if(value != data)
790                     heap_free(value);
791                 heap_free(data);
792                 return FALSE;
793             }
794
795             if(end_ptr)
796                 *end_ptr = ';';
797
798             domain = ptr;
799             TRACE("Parsing new domain %s\n",debugstr_w(domain));
800         }
801         else if (strncmpiW(ptr, szPath, 5) == 0)
802         {
803             ptr+=strlenW(szPath);
804             path = ptr;
805             TRACE("Parsing new path %s\n",debugstr_w(path));
806         }
807         else if (strncmpiW(ptr, szExpires, 8) == 0)
808         {
809             SYSTEMTIME st;
810             ptr+=strlenW(szExpires);
811             if (InternetTimeToSystemTimeW(ptr, &st, 0))
812             {
813                 SystemTimeToFileTime(&st, &expiry);
814
815                 if (CompareFileTime(&create,&expiry) > 0)
816                 {
817                     TRACE("Cookie already expired.\n");
818                     expired = TRUE;
819                 }
820             }
821         }
822         else if (strncmpiW(ptr, szSecure, 6) == 0)
823         {
824             FIXME("secure not handled (%s)\n",debugstr_w(ptr));
825             ptr += strlenW(szSecure);
826         }
827         else if (strncmpiW(ptr, szHttpOnly, 8) == 0)
828         {
829             FIXME("httponly not handled (%s)\n",debugstr_w(ptr));
830             ptr += strlenW(szHttpOnly);
831         }
832         else if (*ptr)
833         {
834             FIXME("Unknown additional option %s\n",debugstr_w(ptr));
835             break;
836         }
837     }
838
839     EnterCriticalSection(&cookie_cs);
840
841     load_persistent_cookie(domain, path);
842
843     LIST_FOR_EACH(cursor, &domain_list)
844     {
845         thisCookieDomain = LIST_ENTRY(cursor, cookie_domain, entry);
846         if (COOKIE_matchDomain(domain, path, thisCookieDomain, FALSE))
847             break;
848         thisCookieDomain = NULL;
849     }
850
851     if (!thisCookieDomain)
852     {
853         if (!expired)
854             thisCookieDomain = COOKIE_addDomain(domain, path);
855         else
856         {
857             heap_free(data);
858             if (value != data) heap_free(value);
859             LeaveCriticalSection(&cookie_cs);
860             return TRUE;
861         }
862     }
863
864     if(!expiry.dwLowDateTime && !expiry.dwHighDateTime)
865         flags |= INTERNET_COOKIE_IS_SESSION;
866     else
867         update_persistent = TRUE;
868
869     if ((thisCookie = COOKIE_findCookie(thisCookieDomain, cookie_name)))
870     {
871         if (!(thisCookie->flags & INTERNET_COOKIE_IS_SESSION))
872             update_persistent = TRUE;
873         COOKIE_deleteCookie(thisCookie, FALSE);
874     }
875
876     TRACE("setting cookie %s=%s for domain %s path %s\n", debugstr_w(cookie_name),
877           debugstr_w(value), debugstr_w(thisCookieDomain->lpCookieDomain),debugstr_w(thisCookieDomain->lpCookiePath));
878
879     if (!expired && !COOKIE_addCookie(thisCookieDomain, cookie_name, value, expiry, create, flags))
880     {
881         heap_free(data);
882         if (value != data) heap_free(value);
883         LeaveCriticalSection(&cookie_cs);
884         return FALSE;
885     }
886     heap_free(data);
887     if (value != data) heap_free(value);
888
889     if (!update_persistent || save_persistent_cookie(thisCookieDomain))
890     {
891         LeaveCriticalSection(&cookie_cs);
892         return TRUE;
893     }
894     LeaveCriticalSection(&cookie_cs);
895     return FALSE;
896 }
897
898 /***********************************************************************
899  *           InternetSetCookieW (WININET.@)
900  *
901  * Sets cookie for the specified url
902  *
903  * RETURNS
904  *    TRUE  on success
905  *    FALSE on failure
906  *
907  */
908 BOOL WINAPI InternetSetCookieW(LPCWSTR lpszUrl, LPCWSTR lpszCookieName,
909     LPCWSTR lpCookieData)
910 {
911     BOOL ret;
912     WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH], path[INTERNET_MAX_PATH_LENGTH];
913
914     TRACE("(%s,%s,%s)\n", debugstr_w(lpszUrl),
915         debugstr_w(lpszCookieName), debugstr_w(lpCookieData));
916
917     if (!lpszUrl || !lpCookieData)
918     {
919         SetLastError(ERROR_INVALID_PARAMETER);
920         return FALSE;
921     }
922
923     hostName[0] = 0;
924     ret = COOKIE_crackUrlSimple(lpszUrl, hostName, sizeof(hostName)/sizeof(hostName[0]), path, sizeof(path)/sizeof(path[0]));
925     if (!ret || !hostName[0]) return FALSE;
926
927     if (!lpszCookieName)
928     {
929         WCHAR *cookie, *data;
930
931         cookie = heap_strdupW(lpCookieData);
932         if (!cookie)
933         {
934             SetLastError(ERROR_OUTOFMEMORY);
935             return FALSE;
936         }
937
938         /* some apps (or is it us??) try to add a cookie with no cookie name, but
939          * the cookie data in the form of name[=data].
940          */
941         if (!(data = strchrW(cookie, '='))) data = cookie + strlenW(cookie);
942         else *data++ = 0;
943
944         ret = set_cookie(hostName, path, cookie, data);
945
946         heap_free(cookie);
947         return ret;
948     }
949     return set_cookie(hostName, path, lpszCookieName, lpCookieData);
950 }
951
952
953 /***********************************************************************
954  *           InternetSetCookieA (WININET.@)
955  *
956  * Sets cookie for the specified url
957  *
958  * RETURNS
959  *    TRUE  on success
960  *    FALSE on failure
961  *
962  */
963 BOOL WINAPI InternetSetCookieA(LPCSTR lpszUrl, LPCSTR lpszCookieName,
964     LPCSTR lpCookieData)
965 {
966     LPWSTR data, url, name;
967     BOOL r;
968
969     TRACE("(%s,%s,%s)\n", debugstr_a(lpszUrl),
970         debugstr_a(lpszCookieName), debugstr_a(lpCookieData));
971
972     url = heap_strdupAtoW(lpszUrl);
973     name = heap_strdupAtoW(lpszCookieName);
974     data = heap_strdupAtoW(lpCookieData);
975
976     r = InternetSetCookieW( url, name, data );
977
978     heap_free( data );
979     heap_free( name );
980     heap_free( url );
981     return r;
982 }
983
984 /***********************************************************************
985  *           InternetSetCookieExA (WININET.@)
986  *
987  * See InternetSetCookieExW.
988  */
989 DWORD WINAPI InternetSetCookieExA( LPCSTR lpszURL, LPCSTR lpszCookieName, LPCSTR lpszCookieData,
990                                    DWORD dwFlags, DWORD_PTR dwReserved)
991 {
992     TRACE("(%s, %s, %s, 0x%08x, 0x%08lx)\n",
993           debugstr_a(lpszURL), debugstr_a(lpszCookieName), debugstr_a(lpszCookieData),
994           dwFlags, dwReserved);
995
996     if (dwFlags) FIXME("flags 0x%08x not supported\n", dwFlags);
997     return InternetSetCookieA(lpszURL, lpszCookieName, lpszCookieData);
998 }
999
1000 /***********************************************************************
1001  *           InternetSetCookieExW (WININET.@)
1002  *
1003  * Sets a cookie for the specified URL.
1004  *
1005  * RETURNS
1006  *    TRUE  on success
1007  *    FALSE on failure
1008  *
1009  */
1010 DWORD WINAPI InternetSetCookieExW( LPCWSTR lpszURL, LPCWSTR lpszCookieName, LPCWSTR lpszCookieData,
1011                                    DWORD dwFlags, DWORD_PTR dwReserved)
1012 {
1013     TRACE("(%s, %s, %s, 0x%08x, 0x%08lx)\n",
1014           debugstr_w(lpszURL), debugstr_w(lpszCookieName), debugstr_w(lpszCookieData),
1015           dwFlags, dwReserved);
1016
1017     if (dwFlags) FIXME("flags 0x%08x not supported\n", dwFlags);
1018     return InternetSetCookieW(lpszURL, lpszCookieName, lpszCookieData);
1019 }
1020
1021 /***********************************************************************
1022  *           InternetGetCookieExA (WININET.@)
1023  *
1024  * See InternetGetCookieExW.
1025  */
1026 BOOL WINAPI InternetGetCookieExA( LPCSTR pchURL, LPCSTR pchCookieName, LPSTR pchCookieData,
1027                                   LPDWORD pcchCookieData, DWORD dwFlags, LPVOID lpReserved)
1028 {
1029     TRACE("(%s, %s, %s, %p, 0x%08x, %p)\n",
1030           debugstr_a(pchURL), debugstr_a(pchCookieName), debugstr_a(pchCookieData),
1031           pcchCookieData, dwFlags, lpReserved);
1032
1033     if (dwFlags) FIXME("flags 0x%08x not supported\n", dwFlags);
1034     return InternetGetCookieA(pchURL, pchCookieName, pchCookieData, pcchCookieData);
1035 }
1036
1037 /***********************************************************************
1038  *           InternetGetCookieExW (WININET.@)
1039  *
1040  * Retrieve cookie for the specified URL.
1041  *
1042  * RETURNS
1043  *    TRUE  on success
1044  *    FALSE on failure
1045  *
1046  */
1047 BOOL WINAPI InternetGetCookieExW( LPCWSTR pchURL, LPCWSTR pchCookieName, LPWSTR pchCookieData,
1048                                   LPDWORD pcchCookieData, DWORD dwFlags, LPVOID lpReserved)
1049 {
1050     TRACE("(%s, %s, %s, %p, 0x%08x, %p)\n",
1051           debugstr_w(pchURL), debugstr_w(pchCookieName), debugstr_w(pchCookieData),
1052           pcchCookieData, dwFlags, lpReserved);
1053
1054     if (dwFlags) FIXME("flags 0x%08x not supported\n", dwFlags);
1055     return InternetGetCookieW(pchURL, pchCookieName, pchCookieData, pcchCookieData);
1056 }
1057
1058 /***********************************************************************
1059  *           InternetClearAllPerSiteCookieDecisions (WININET.@)
1060  *
1061  * Clears all per-site decisions about cookies.
1062  *
1063  * RETURNS
1064  *    TRUE  on success
1065  *    FALSE on failure
1066  *
1067  */
1068 BOOL WINAPI InternetClearAllPerSiteCookieDecisions( VOID )
1069 {
1070     FIXME("stub\n");
1071     return TRUE;
1072 }
1073
1074 /***********************************************************************
1075  *           InternetEnumPerSiteCookieDecisionA (WININET.@)
1076  *
1077  * See InternetEnumPerSiteCookieDecisionW.
1078  */
1079 BOOL WINAPI InternetEnumPerSiteCookieDecisionA( LPSTR pszSiteName, ULONG *pcSiteNameSize,
1080                                                 ULONG *pdwDecision, ULONG dwIndex )
1081 {
1082     FIXME("(%s, %p, %p, 0x%08x) stub\n",
1083           debugstr_a(pszSiteName), pcSiteNameSize, pdwDecision, dwIndex);
1084     return FALSE;
1085 }
1086
1087 /***********************************************************************
1088  *           InternetEnumPerSiteCookieDecisionW (WININET.@)
1089  *
1090  * Enumerates all per-site decisions about cookies.
1091  *
1092  * RETURNS
1093  *    TRUE  on success
1094  *    FALSE on failure
1095  *
1096  */
1097 BOOL WINAPI InternetEnumPerSiteCookieDecisionW( LPWSTR pszSiteName, ULONG *pcSiteNameSize,
1098                                                 ULONG *pdwDecision, ULONG dwIndex )
1099 {
1100     FIXME("(%s, %p, %p, 0x%08x) stub\n",
1101           debugstr_w(pszSiteName), pcSiteNameSize, pdwDecision, dwIndex);
1102     return FALSE;
1103 }
1104
1105 /***********************************************************************
1106  *           InternetGetPerSiteCookieDecisionA (WININET.@)
1107  */
1108 BOOL WINAPI InternetGetPerSiteCookieDecisionA( LPCSTR pwchHostName, ULONG *pResult )
1109 {
1110     FIXME("(%s, %p) stub\n", debugstr_a(pwchHostName), pResult);
1111     return FALSE;
1112 }
1113
1114 /***********************************************************************
1115  *           InternetGetPerSiteCookieDecisionW (WININET.@)
1116  */
1117 BOOL WINAPI InternetGetPerSiteCookieDecisionW( LPCWSTR pwchHostName, ULONG *pResult )
1118 {
1119     FIXME("(%s, %p) stub\n", debugstr_w(pwchHostName), pResult);
1120     return FALSE;
1121 }
1122
1123 /***********************************************************************
1124  *           InternetSetPerSiteCookieDecisionA (WININET.@)
1125  */
1126 BOOL WINAPI InternetSetPerSiteCookieDecisionA( LPCSTR pchHostName, DWORD dwDecision )
1127 {
1128     FIXME("(%s, 0x%08x) stub\n", debugstr_a(pchHostName), dwDecision);
1129     return FALSE;
1130 }
1131
1132 /***********************************************************************
1133  *           InternetSetPerSiteCookieDecisionW (WININET.@)
1134  */
1135 BOOL WINAPI InternetSetPerSiteCookieDecisionW( LPCWSTR pchHostName, DWORD dwDecision )
1136 {
1137     FIXME("(%s, 0x%08x) stub\n", debugstr_w(pchHostName), dwDecision);
1138     return FALSE;
1139 }
1140
1141 void free_cookie(void)
1142 {
1143     DeleteCriticalSection(&cookie_cs);
1144 }