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