wineps.drv: Ignore requested resolutions not supported by device.
[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     WCHAR *url, *name;
661     DWORD len;
662     BOOL r;
663
664     TRACE("(%s %s %p %p(%u))\n", debugstr_a(lpszUrl), debugstr_a(lpszCookieName),
665           lpCookieData, lpdwSize, lpdwSize ? *lpdwSize : 0);
666
667     url = heap_strdupAtoW(lpszUrl);
668     name = heap_strdupAtoW(lpszCookieName);
669
670     r = InternetGetCookieW( url, name, NULL, &len );
671     if( r )
672     {
673         WCHAR *szCookieData;
674
675         szCookieData = heap_alloc(len * sizeof(WCHAR));
676         if( !szCookieData )
677         {
678             r = FALSE;
679         }
680         else
681         {
682             r = InternetGetCookieW( url, name, szCookieData, &len );
683
684             *lpdwSize = WideCharToMultiByte( CP_ACP, 0, szCookieData, len,
685                                              lpCookieData, lpCookieData ? *lpdwSize : 0, NULL, NULL );
686
687             heap_free( szCookieData );
688         }
689     }
690     heap_free( name );
691     heap_free( url );
692     return r;
693 }
694
695
696 /***********************************************************************
697  *           IsDomainLegalCookieDomainW (WININET.@)
698  */
699 BOOL WINAPI IsDomainLegalCookieDomainW( LPCWSTR s1, LPCWSTR s2 )
700 {
701     DWORD s1_len, s2_len;
702
703     FIXME("(%s, %s) semi-stub\n", debugstr_w(s1), debugstr_w(s2));
704
705     if (!s1 || !s2)
706     {
707         SetLastError(ERROR_INVALID_PARAMETER);
708         return FALSE;
709     }
710     if (s1[0] == '.' || !s1[0] || s2[0] == '.' || !s2[0])
711     {
712         SetLastError(ERROR_INVALID_NAME);
713         return FALSE;
714     }
715     if(!strchrW(s1, '.') || !strchrW(s2, '.'))
716         return FALSE;
717
718     s1_len = strlenW(s1);
719     s2_len = strlenW(s2);
720     if (s1_len > s2_len)
721         return FALSE;
722
723     if (strncmpiW(s1, s2+s2_len-s1_len, s1_len) || (s2_len>s1_len && s2[s2_len-s1_len-1]!='.'))
724     {
725         SetLastError(ERROR_INVALID_PARAMETER);
726         return FALSE;
727     }
728
729     return TRUE;
730 }
731
732 BOOL set_cookie(LPCWSTR domain, LPCWSTR path, LPCWSTR cookie_name, LPCWSTR cookie_data)
733 {
734     cookie_domain *thisCookieDomain = NULL;
735     cookie *thisCookie;
736     struct list *cursor;
737     LPWSTR data, value;
738     WCHAR *ptr;
739     FILETIME expiry, create;
740     BOOL expired = FALSE, update_persistent = FALSE;
741     DWORD flags = 0;
742
743     value = data = heap_strdupW(cookie_data);
744     if (!data)
745     {
746         ERR("could not allocate the cookie data buffer\n");
747         return FALSE;
748     }
749
750     memset(&expiry,0,sizeof(expiry));
751     GetSystemTimeAsFileTime(&create);
752
753     /* lots of information can be parsed out of the cookie value */
754
755     ptr = data;
756     for (;;)
757     {
758         static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
759         static const WCHAR szPath[] = {'p','a','t','h','=',0};
760         static const WCHAR szExpires[] = {'e','x','p','i','r','e','s','=',0};
761         static const WCHAR szSecure[] = {'s','e','c','u','r','e',0};
762         static const WCHAR szHttpOnly[] = {'h','t','t','p','o','n','l','y',0};
763
764         if (!(ptr = strchrW(ptr,';'))) break;
765         *ptr++ = 0;
766
767         if (value != data) heap_free(value);
768         value = heap_alloc((ptr - data) * sizeof(WCHAR));
769         if (value == NULL)
770         {
771             heap_free(data);
772             ERR("could not allocate the cookie value buffer\n");
773             return FALSE;
774         }
775         strcpyW(value, data);
776
777         while (*ptr == ' ') ptr++; /* whitespace */
778
779         if (strncmpiW(ptr, szDomain, 7) == 0)
780         {
781             WCHAR *end_ptr;
782
783             ptr += sizeof(szDomain)/sizeof(szDomain[0])-1;
784             if(*ptr == '.')
785                 ptr++;
786             end_ptr = strchrW(ptr, ';');
787             if(end_ptr)
788                 *end_ptr = 0;
789
790             if(!IsDomainLegalCookieDomainW(ptr, domain))
791             {
792                 if(value != data)
793                     heap_free(value);
794                 heap_free(data);
795                 return FALSE;
796             }
797
798             if(end_ptr)
799                 *end_ptr = ';';
800
801             domain = ptr;
802             TRACE("Parsing new domain %s\n",debugstr_w(domain));
803         }
804         else if (strncmpiW(ptr, szPath, 5) == 0)
805         {
806             ptr+=strlenW(szPath);
807             path = ptr;
808             TRACE("Parsing new path %s\n",debugstr_w(path));
809         }
810         else if (strncmpiW(ptr, szExpires, 8) == 0)
811         {
812             SYSTEMTIME st;
813             ptr+=strlenW(szExpires);
814             if (InternetTimeToSystemTimeW(ptr, &st, 0))
815             {
816                 SystemTimeToFileTime(&st, &expiry);
817
818                 if (CompareFileTime(&create,&expiry) > 0)
819                 {
820                     TRACE("Cookie already expired.\n");
821                     expired = TRUE;
822                 }
823             }
824         }
825         else if (strncmpiW(ptr, szSecure, 6) == 0)
826         {
827             FIXME("secure not handled (%s)\n",debugstr_w(ptr));
828             ptr += strlenW(szSecure);
829         }
830         else if (strncmpiW(ptr, szHttpOnly, 8) == 0)
831         {
832             FIXME("httponly not handled (%s)\n",debugstr_w(ptr));
833             ptr += strlenW(szHttpOnly);
834         }
835         else if (*ptr)
836         {
837             FIXME("Unknown additional option %s\n",debugstr_w(ptr));
838             break;
839         }
840     }
841
842     EnterCriticalSection(&cookie_cs);
843
844     load_persistent_cookie(domain, path);
845
846     LIST_FOR_EACH(cursor, &domain_list)
847     {
848         thisCookieDomain = LIST_ENTRY(cursor, cookie_domain, entry);
849         if (COOKIE_matchDomain(domain, path, thisCookieDomain, FALSE))
850             break;
851         thisCookieDomain = NULL;
852     }
853
854     if (!thisCookieDomain)
855     {
856         if (!expired)
857             thisCookieDomain = COOKIE_addDomain(domain, path);
858         else
859         {
860             heap_free(data);
861             if (value != data) heap_free(value);
862             LeaveCriticalSection(&cookie_cs);
863             return TRUE;
864         }
865     }
866
867     if(!expiry.dwLowDateTime && !expiry.dwHighDateTime)
868         flags |= INTERNET_COOKIE_IS_SESSION;
869     else
870         update_persistent = TRUE;
871
872     if ((thisCookie = COOKIE_findCookie(thisCookieDomain, cookie_name)))
873     {
874         if (!(thisCookie->flags & INTERNET_COOKIE_IS_SESSION))
875             update_persistent = TRUE;
876         COOKIE_deleteCookie(thisCookie, FALSE);
877     }
878
879     TRACE("setting cookie %s=%s for domain %s path %s\n", debugstr_w(cookie_name),
880           debugstr_w(value), debugstr_w(thisCookieDomain->lpCookieDomain),debugstr_w(thisCookieDomain->lpCookiePath));
881
882     if (!expired && !COOKIE_addCookie(thisCookieDomain, cookie_name, value, expiry, create, flags))
883     {
884         heap_free(data);
885         if (value != data) heap_free(value);
886         LeaveCriticalSection(&cookie_cs);
887         return FALSE;
888     }
889     heap_free(data);
890     if (value != data) heap_free(value);
891
892     if (!update_persistent || save_persistent_cookie(thisCookieDomain))
893     {
894         LeaveCriticalSection(&cookie_cs);
895         return TRUE;
896     }
897     LeaveCriticalSection(&cookie_cs);
898     return FALSE;
899 }
900
901 /***********************************************************************
902  *           InternetSetCookieW (WININET.@)
903  *
904  * Sets cookie for the specified url
905  *
906  * RETURNS
907  *    TRUE  on success
908  *    FALSE on failure
909  *
910  */
911 BOOL WINAPI InternetSetCookieW(LPCWSTR lpszUrl, LPCWSTR lpszCookieName,
912     LPCWSTR lpCookieData)
913 {
914     BOOL ret;
915     WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH], path[INTERNET_MAX_PATH_LENGTH];
916
917     TRACE("(%s,%s,%s)\n", debugstr_w(lpszUrl),
918         debugstr_w(lpszCookieName), debugstr_w(lpCookieData));
919
920     if (!lpszUrl || !lpCookieData)
921     {
922         SetLastError(ERROR_INVALID_PARAMETER);
923         return FALSE;
924     }
925
926     hostName[0] = 0;
927     ret = COOKIE_crackUrlSimple(lpszUrl, hostName, sizeof(hostName)/sizeof(hostName[0]), path, sizeof(path)/sizeof(path[0]));
928     if (!ret || !hostName[0]) return FALSE;
929
930     if (!lpszCookieName)
931     {
932         WCHAR *cookie, *data;
933
934         cookie = heap_strdupW(lpCookieData);
935         if (!cookie)
936         {
937             SetLastError(ERROR_OUTOFMEMORY);
938             return FALSE;
939         }
940
941         /* some apps (or is it us??) try to add a cookie with no cookie name, but
942          * the cookie data in the form of name[=data].
943          */
944         if (!(data = strchrW(cookie, '='))) data = cookie + strlenW(cookie);
945         else *data++ = 0;
946
947         ret = set_cookie(hostName, path, cookie, data);
948
949         heap_free(cookie);
950         return ret;
951     }
952     return set_cookie(hostName, path, lpszCookieName, lpCookieData);
953 }
954
955
956 /***********************************************************************
957  *           InternetSetCookieA (WININET.@)
958  *
959  * Sets cookie for the specified url
960  *
961  * RETURNS
962  *    TRUE  on success
963  *    FALSE on failure
964  *
965  */
966 BOOL WINAPI InternetSetCookieA(LPCSTR lpszUrl, LPCSTR lpszCookieName,
967     LPCSTR lpCookieData)
968 {
969     LPWSTR data, url, name;
970     BOOL r;
971
972     TRACE("(%s,%s,%s)\n", debugstr_a(lpszUrl),
973         debugstr_a(lpszCookieName), debugstr_a(lpCookieData));
974
975     url = heap_strdupAtoW(lpszUrl);
976     name = heap_strdupAtoW(lpszCookieName);
977     data = heap_strdupAtoW(lpCookieData);
978
979     r = InternetSetCookieW( url, name, data );
980
981     heap_free( data );
982     heap_free( name );
983     heap_free( url );
984     return r;
985 }
986
987 /***********************************************************************
988  *           InternetSetCookieExA (WININET.@)
989  *
990  * See InternetSetCookieExW.
991  */
992 DWORD WINAPI InternetSetCookieExA( LPCSTR lpszURL, LPCSTR lpszCookieName, LPCSTR lpszCookieData,
993                                    DWORD dwFlags, DWORD_PTR dwReserved)
994 {
995     TRACE("(%s, %s, %s, 0x%08x, 0x%08lx)\n",
996           debugstr_a(lpszURL), debugstr_a(lpszCookieName), debugstr_a(lpszCookieData),
997           dwFlags, dwReserved);
998
999     if (dwFlags) FIXME("flags 0x%08x not supported\n", dwFlags);
1000     return InternetSetCookieA(lpszURL, lpszCookieName, lpszCookieData);
1001 }
1002
1003 /***********************************************************************
1004  *           InternetSetCookieExW (WININET.@)
1005  *
1006  * Sets a cookie for the specified URL.
1007  *
1008  * RETURNS
1009  *    TRUE  on success
1010  *    FALSE on failure
1011  *
1012  */
1013 DWORD WINAPI InternetSetCookieExW( LPCWSTR lpszURL, LPCWSTR lpszCookieName, LPCWSTR lpszCookieData,
1014                                    DWORD dwFlags, DWORD_PTR dwReserved)
1015 {
1016     TRACE("(%s, %s, %s, 0x%08x, 0x%08lx)\n",
1017           debugstr_w(lpszURL), debugstr_w(lpszCookieName), debugstr_w(lpszCookieData),
1018           dwFlags, dwReserved);
1019
1020     if (dwFlags) FIXME("flags 0x%08x not supported\n", dwFlags);
1021     return InternetSetCookieW(lpszURL, lpszCookieName, lpszCookieData);
1022 }
1023
1024 /***********************************************************************
1025  *           InternetGetCookieExA (WININET.@)
1026  *
1027  * See InternetGetCookieExW.
1028  */
1029 BOOL WINAPI InternetGetCookieExA( LPCSTR pchURL, LPCSTR pchCookieName, LPSTR pchCookieData,
1030                                   LPDWORD pcchCookieData, DWORD dwFlags, LPVOID lpReserved)
1031 {
1032     TRACE("(%s, %s, %s, %p, 0x%08x, %p)\n",
1033           debugstr_a(pchURL), debugstr_a(pchCookieName), debugstr_a(pchCookieData),
1034           pcchCookieData, dwFlags, lpReserved);
1035
1036     if (dwFlags) FIXME("flags 0x%08x not supported\n", dwFlags);
1037     return InternetGetCookieA(pchURL, pchCookieName, pchCookieData, pcchCookieData);
1038 }
1039
1040 /***********************************************************************
1041  *           InternetGetCookieExW (WININET.@)
1042  *
1043  * Retrieve cookie for the specified URL.
1044  *
1045  * RETURNS
1046  *    TRUE  on success
1047  *    FALSE on failure
1048  *
1049  */
1050 BOOL WINAPI InternetGetCookieExW( LPCWSTR pchURL, LPCWSTR pchCookieName, LPWSTR pchCookieData,
1051                                   LPDWORD pcchCookieData, DWORD dwFlags, LPVOID lpReserved)
1052 {
1053     TRACE("(%s, %s, %s, %p, 0x%08x, %p)\n",
1054           debugstr_w(pchURL), debugstr_w(pchCookieName), debugstr_w(pchCookieData),
1055           pcchCookieData, dwFlags, lpReserved);
1056
1057     if (dwFlags) FIXME("flags 0x%08x not supported\n", dwFlags);
1058     return InternetGetCookieW(pchURL, pchCookieName, pchCookieData, pcchCookieData);
1059 }
1060
1061 /***********************************************************************
1062  *           InternetClearAllPerSiteCookieDecisions (WININET.@)
1063  *
1064  * Clears all per-site decisions about cookies.
1065  *
1066  * RETURNS
1067  *    TRUE  on success
1068  *    FALSE on failure
1069  *
1070  */
1071 BOOL WINAPI InternetClearAllPerSiteCookieDecisions( VOID )
1072 {
1073     FIXME("stub\n");
1074     return TRUE;
1075 }
1076
1077 /***********************************************************************
1078  *           InternetEnumPerSiteCookieDecisionA (WININET.@)
1079  *
1080  * See InternetEnumPerSiteCookieDecisionW.
1081  */
1082 BOOL WINAPI InternetEnumPerSiteCookieDecisionA( LPSTR pszSiteName, ULONG *pcSiteNameSize,
1083                                                 ULONG *pdwDecision, ULONG dwIndex )
1084 {
1085     FIXME("(%s, %p, %p, 0x%08x) stub\n",
1086           debugstr_a(pszSiteName), pcSiteNameSize, pdwDecision, dwIndex);
1087     return FALSE;
1088 }
1089
1090 /***********************************************************************
1091  *           InternetEnumPerSiteCookieDecisionW (WININET.@)
1092  *
1093  * Enumerates all per-site decisions about cookies.
1094  *
1095  * RETURNS
1096  *    TRUE  on success
1097  *    FALSE on failure
1098  *
1099  */
1100 BOOL WINAPI InternetEnumPerSiteCookieDecisionW( LPWSTR pszSiteName, ULONG *pcSiteNameSize,
1101                                                 ULONG *pdwDecision, ULONG dwIndex )
1102 {
1103     FIXME("(%s, %p, %p, 0x%08x) stub\n",
1104           debugstr_w(pszSiteName), pcSiteNameSize, pdwDecision, dwIndex);
1105     return FALSE;
1106 }
1107
1108 /***********************************************************************
1109  *           InternetGetPerSiteCookieDecisionA (WININET.@)
1110  */
1111 BOOL WINAPI InternetGetPerSiteCookieDecisionA( LPCSTR pwchHostName, ULONG *pResult )
1112 {
1113     FIXME("(%s, %p) stub\n", debugstr_a(pwchHostName), pResult);
1114     return FALSE;
1115 }
1116
1117 /***********************************************************************
1118  *           InternetGetPerSiteCookieDecisionW (WININET.@)
1119  */
1120 BOOL WINAPI InternetGetPerSiteCookieDecisionW( LPCWSTR pwchHostName, ULONG *pResult )
1121 {
1122     FIXME("(%s, %p) stub\n", debugstr_w(pwchHostName), pResult);
1123     return FALSE;
1124 }
1125
1126 /***********************************************************************
1127  *           InternetSetPerSiteCookieDecisionA (WININET.@)
1128  */
1129 BOOL WINAPI InternetSetPerSiteCookieDecisionA( LPCSTR pchHostName, DWORD dwDecision )
1130 {
1131     FIXME("(%s, 0x%08x) stub\n", debugstr_a(pchHostName), dwDecision);
1132     return FALSE;
1133 }
1134
1135 /***********************************************************************
1136  *           InternetSetPerSiteCookieDecisionW (WININET.@)
1137  */
1138 BOOL WINAPI InternetSetPerSiteCookieDecisionW( LPCWSTR pchHostName, DWORD dwDecision )
1139 {
1140     FIXME("(%s, 0x%08x) stub\n", debugstr_w(pchHostName), dwDecision);
1141     return FALSE;
1142 }
1143
1144 void free_cookie(void)
1145 {
1146     DeleteCriticalSection(&cookie_cs);
1147 }