urlmon: Recognize <head> start tag as text/html MIME type.
[wine] / dlls / urlmon / urlmon_main.c
1 /*
2  * UrlMon
3  *
4  * Copyright (c) 2000 Patrik Stridvall
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <stdarg.h>
22
23 #include "urlmon_main.h"
24
25 #include "winreg.h"
26
27 #define NO_SHLWAPI_REG
28 #include "shlwapi.h"
29 #include "advpub.h"
30 #include "initguid.h"
31
32 #include "wine/debug.h"
33
34 #include "urlmon.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(urlmon);
37
38 DEFINE_GUID(CLSID_CUri, 0xDF2FCE13, 0x25EC, 0x45BB, 0x9D,0x4C, 0xCE,0xCD,0x47,0xC2,0x43,0x0C);
39
40 LONG URLMON_refCount = 0;
41
42 static HMODULE hCabinet = NULL;
43 static DWORD urlmon_tls = TLS_OUT_OF_INDEXES;
44
45 static void init_session(BOOL);
46
47 static struct list tls_list = LIST_INIT(tls_list);
48
49 static CRITICAL_SECTION tls_cs;
50 static CRITICAL_SECTION_DEBUG tls_cs_dbg =
51 {
52     0, 0, &tls_cs,
53     { &tls_cs_dbg.ProcessLocksList, &tls_cs_dbg.ProcessLocksList },
54       0, 0, { (DWORD_PTR)(__FILE__ ": tls") }
55 };
56
57 static CRITICAL_SECTION tls_cs = { &tls_cs_dbg, -1, 0, 0, 0, 0 };
58
59 tls_data_t *get_tls_data(void)
60 {
61     tls_data_t *data;
62
63     if(urlmon_tls == TLS_OUT_OF_INDEXES) {
64         DWORD tls = TlsAlloc();
65         if(tls == TLS_OUT_OF_INDEXES)
66             return NULL;
67
68         tls = InterlockedCompareExchange((LONG*)&urlmon_tls, tls, TLS_OUT_OF_INDEXES);
69         if(tls != urlmon_tls)
70             TlsFree(tls);
71     }
72
73     data = TlsGetValue(urlmon_tls);
74     if(!data) {
75         data = heap_alloc_zero(sizeof(tls_data_t));
76         if(!data)
77             return NULL;
78
79         EnterCriticalSection(&tls_cs);
80         list_add_tail(&tls_list, &data->entry);
81         LeaveCriticalSection(&tls_cs);
82
83         TlsSetValue(urlmon_tls, data);
84     }
85
86     return data;
87 }
88
89 static void free_tls_list(void)
90 {
91     tls_data_t *data;
92
93     if(urlmon_tls == TLS_OUT_OF_INDEXES)
94         return;
95
96     while(!list_empty(&tls_list)) {
97         data = LIST_ENTRY(list_head(&tls_list), tls_data_t, entry);
98         list_remove(&data->entry);
99         heap_free(data);
100     }
101
102     TlsFree(urlmon_tls);
103 }
104
105 static void detach_thread(void)
106 {
107     tls_data_t *data;
108
109     if(urlmon_tls == TLS_OUT_OF_INDEXES)
110         return;
111
112     data = TlsGetValue(urlmon_tls);
113     if(!data)
114         return;
115
116     EnterCriticalSection(&tls_cs);
117     list_remove(&data->entry);
118     LeaveCriticalSection(&tls_cs);
119
120     if(data->notif_hwnd) {
121         WARN("notif_hwnd not destroyed\n");
122         DestroyWindow(data->notif_hwnd);
123     }
124
125     heap_free(data);
126 }
127
128 static void process_detach(void)
129 {
130     HINTERNET internet_session;
131
132     internet_session = get_internet_session(NULL);
133     if(internet_session)
134         InternetCloseHandle(internet_session);
135
136     if (hCabinet)
137         FreeLibrary(hCabinet);
138
139     init_session(FALSE);
140     free_session();
141     free_tls_list();
142 }
143
144 /***********************************************************************
145  *              DllMain (URLMON.init)
146  */
147 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
148 {
149     TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
150
151     URLMON_DllMain( hinstDLL, fdwReason, fImpLoad );
152
153     switch(fdwReason) {
154     case DLL_PROCESS_ATTACH:
155         init_session(TRUE);
156         break;
157
158     case DLL_PROCESS_DETACH:
159         process_detach();
160         DeleteCriticalSection(&tls_cs);
161         break;
162
163     case DLL_THREAD_DETACH:
164         detach_thread();
165         break;
166     }
167     return TRUE;
168 }
169
170
171 /***********************************************************************
172  *              DllInstall (URLMON.@)
173  */
174 HRESULT WINAPI DllInstall(BOOL bInstall, LPCWSTR cmdline)
175 {
176   FIXME("(%s, %s): stub\n", bInstall?"TRUE":"FALSE",
177         debugstr_w(cmdline));
178
179   return S_OK;
180 }
181
182 /***********************************************************************
183  *              DllCanUnloadNow (URLMON.@)
184  */
185 HRESULT WINAPI DllCanUnloadNow(void)
186 {
187     return URLMON_refCount != 0 ? S_FALSE : S_OK;
188 }
189
190
191
192 /******************************************************************************
193  * Urlmon ClassFactory
194  */
195 typedef struct {
196     IClassFactory IClassFactory_iface;
197
198     HRESULT (*pfnCreateInstance)(IUnknown *pUnkOuter, LPVOID *ppObj);
199 } ClassFactory;
200
201 static inline ClassFactory *impl_from_IClassFactory(IClassFactory *iface)
202 {
203     return CONTAINING_RECORD(iface, ClassFactory, IClassFactory_iface);
204 }
205
206 static HRESULT WINAPI CF_QueryInterface(IClassFactory *iface, REFIID riid, LPVOID *ppv)
207 {
208     *ppv = NULL;
209
210     if(IsEqualGUID(riid, &IID_IUnknown)) {
211         TRACE("(%p)->(IID_IUnknown %p)\n", iface, ppv);
212         *ppv = iface;
213     }else if(IsEqualGUID(riid, &IID_IClassFactory)) {
214         TRACE("(%p)->(IID_IClassFactory %p)\n", iface, ppv);
215         *ppv = iface;
216     }
217
218     if(*ppv) {
219         IUnknown_AddRef((IUnknown*)*ppv);
220         return S_OK;
221     }
222
223     WARN("(%p)->(%s,%p),not found\n", iface, debugstr_guid(riid), ppv);
224     return E_NOINTERFACE;
225 }
226
227 static ULONG WINAPI CF_AddRef(IClassFactory *iface)
228 {
229     URLMON_LockModule();
230     return 2;
231 }
232
233 static ULONG WINAPI CF_Release(IClassFactory *iface)
234 {
235     URLMON_UnlockModule();
236     return 1;
237 }
238
239
240 static HRESULT WINAPI CF_CreateInstance(IClassFactory *iface, IUnknown *pOuter,
241                                         REFIID riid, LPVOID *ppobj)
242 {
243     ClassFactory *This = impl_from_IClassFactory(iface);
244     HRESULT hres;
245     LPUNKNOWN punk;
246     
247     TRACE("(%p)->(%p,%s,%p)\n",This,pOuter,debugstr_guid(riid),ppobj);
248
249     *ppobj = NULL;
250     if(SUCCEEDED(hres = This->pfnCreateInstance(pOuter, (LPVOID *) &punk))) {
251         hres = IUnknown_QueryInterface(punk, riid, ppobj);
252         IUnknown_Release(punk);
253     }
254     return hres;
255 }
256
257 static HRESULT WINAPI CF_LockServer(LPCLASSFACTORY iface,BOOL dolock)
258 {
259     TRACE("(%d)\n", dolock);
260
261     if (dolock)
262            URLMON_LockModule();
263     else
264            URLMON_UnlockModule();
265
266     return S_OK;
267 }
268
269 static const IClassFactoryVtbl ClassFactoryVtbl =
270 {
271     CF_QueryInterface,
272     CF_AddRef,
273     CF_Release,
274     CF_CreateInstance,
275     CF_LockServer
276 };
277
278 static ClassFactory FileProtocolCF =
279     { { &ClassFactoryVtbl }, FileProtocol_Construct};
280 static ClassFactory FtpProtocolCF =
281     { { &ClassFactoryVtbl }, FtpProtocol_Construct};
282 static ClassFactory GopherProtocolCF =
283     { { &ClassFactoryVtbl }, GopherProtocol_Construct};
284 static ClassFactory HttpProtocolCF =
285     { { &ClassFactoryVtbl }, HttpProtocol_Construct};
286 static ClassFactory HttpSProtocolCF =
287     { { &ClassFactoryVtbl }, HttpSProtocol_Construct};
288 static ClassFactory MkProtocolCF =
289     { { &ClassFactoryVtbl }, MkProtocol_Construct};
290 static ClassFactory SecurityManagerCF =
291     { { &ClassFactoryVtbl }, SecManagerImpl_Construct};
292 static ClassFactory ZoneManagerCF =
293     { { &ClassFactoryVtbl }, ZoneMgrImpl_Construct};
294 static ClassFactory StdURLMonikerCF =
295     { { &ClassFactoryVtbl }, StdURLMoniker_Construct};
296 static ClassFactory MimeFilterCF =
297     { { &ClassFactoryVtbl }, MimeFilter_Construct};
298 static ClassFactory CUriCF =
299     { { &ClassFactoryVtbl }, Uri_Construct};
300
301 struct object_creation_info
302 {
303     const CLSID *clsid;
304     IClassFactory *cf;
305     LPCWSTR protocol;
306 };
307
308 static const WCHAR wszFile[] = {'f','i','l','e',0};
309 static const WCHAR wszFtp[]  = {'f','t','p',0};
310 static const WCHAR wszGopher[]  = {'g','o','p','h','e','r',0};
311 static const WCHAR wszHttp[] = {'h','t','t','p',0};
312 static const WCHAR wszHttps[] = {'h','t','t','p','s',0};
313 static const WCHAR wszMk[]   = {'m','k',0};
314
315 static const struct object_creation_info object_creation[] =
316 {
317     { &CLSID_FileProtocol,            &FileProtocolCF.IClassFactory_iface,    wszFile },
318     { &CLSID_FtpProtocol,             &FtpProtocolCF.IClassFactory_iface,     wszFtp  },
319     { &CLSID_GopherProtocol,          &GopherProtocolCF.IClassFactory_iface,  wszGopher },
320     { &CLSID_HttpProtocol,            &HttpProtocolCF.IClassFactory_iface,    wszHttp },
321     { &CLSID_HttpSProtocol,           &HttpSProtocolCF.IClassFactory_iface,   wszHttps },
322     { &CLSID_MkProtocol,              &MkProtocolCF.IClassFactory_iface,      wszMk },
323     { &CLSID_InternetSecurityManager, &SecurityManagerCF.IClassFactory_iface, NULL    },
324     { &CLSID_InternetZoneManager,     &ZoneManagerCF.IClassFactory_iface,     NULL    },
325     { &CLSID_StdURLMoniker,           &StdURLMonikerCF.IClassFactory_iface,   NULL    },
326     { &CLSID_DeCompMimeFilter,        &MimeFilterCF.IClassFactory_iface,      NULL    },
327     { &CLSID_CUri,                    &CUriCF.IClassFactory_iface,            NULL    }
328 };
329
330 static void init_session(BOOL init)
331 {
332     unsigned int i;
333
334     for(i=0; i < sizeof(object_creation)/sizeof(object_creation[0]); i++) {
335
336         if(object_creation[i].protocol)
337             register_urlmon_namespace(object_creation[i].cf, object_creation[i].clsid,
338                                       object_creation[i].protocol, init);
339     }
340 }
341
342 /*******************************************************************************
343  * DllGetClassObject [URLMON.@]
344  * Retrieves class object from a DLL object
345  *
346  * NOTES
347  *    Docs say returns STDAPI
348  *
349  * PARAMS
350  *    rclsid [I] CLSID for the class object
351  *    riid   [I] Reference to identifier of interface for class object
352  *    ppv    [O] Address of variable to receive interface pointer for riid
353  *
354  * RETURNS
355  *    Success: S_OK
356  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
357  *             E_UNEXPECTED
358  */
359
360 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
361 {
362     unsigned int i;
363     HRESULT hr;
364     
365     TRACE("(%s,%s,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
366     
367     for (i=0; i < sizeof(object_creation)/sizeof(object_creation[0]); i++)
368     {
369         if (IsEqualGUID(object_creation[i].clsid, rclsid))
370             return IClassFactory_QueryInterface(object_creation[i].cf, riid, ppv);
371     }
372
373     hr = URLMON_DllGetClassObject(rclsid, riid, ppv);
374     if(SUCCEEDED(hr))
375         return hr;
376
377     FIXME("%s: no class found.\n", debugstr_guid(rclsid));
378     return CLASS_E_CLASSNOTAVAILABLE;
379 }
380
381 static HRESULT register_inf(BOOL doregister)
382 {
383     HRESULT (WINAPI *pRegInstall)(HMODULE hm, LPCSTR pszSection, const STRTABLEA* pstTable);
384     HMODULE hAdvpack;
385
386     static const WCHAR wszAdvpack[] = {'a','d','v','p','a','c','k','.','d','l','l',0};
387
388     hAdvpack = LoadLibraryW(wszAdvpack);
389     pRegInstall = (void *)GetProcAddress(hAdvpack, "RegInstall");
390
391     return pRegInstall(hProxyDll, doregister ? "RegisterDll" : "UnregisterDll", NULL);
392 }
393
394 /***********************************************************************
395  *              DllRegisterServer (URLMON.@)
396  */
397 HRESULT WINAPI DllRegisterServer(void)
398 {
399     HRESULT hr;
400
401     TRACE("\n");
402
403     hr = URLMON_DllRegisterServer();
404     return SUCCEEDED(hr) ? register_inf(TRUE) : hr;
405 }
406
407 /***********************************************************************
408  *              DllUnregisterServer (URLMON.@)
409  */
410 HRESULT WINAPI DllUnregisterServer(void)
411 {
412     HRESULT hr;
413
414     TRACE("\n");
415
416     hr = URLMON_DllUnregisterServer();
417     return SUCCEEDED(hr) ? register_inf(FALSE) : hr;
418 }
419
420 /***********************************************************************
421  *              DllRegisterServerEx (URLMON.@)
422  */
423 HRESULT WINAPI DllRegisterServerEx(void)
424 {
425     FIXME("(void): stub\n");
426
427     return E_FAIL;
428 }
429
430 /**************************************************************************
431  *                 IsValidURL (URLMON.@)
432  * 
433  * Determines if a specified string is a valid URL.
434  *
435  * PARAMS
436  *  pBC        [I] ignored, should be NULL.
437  *  szURL      [I] string that represents the URL in question.
438  *  dwReserved [I] reserved and must be zero.
439  *
440  * RETURNS
441  *  Success: S_OK.
442  *  Failure: S_FALSE.
443  *  returns E_INVALIDARG if one or more of the args is invalid.
444  *
445  * TODO:
446  *  test functionality against windows to see what a valid URL is.
447  */
448 HRESULT WINAPI IsValidURL(LPBC pBC, LPCWSTR szURL, DWORD dwReserved)
449 {
450     FIXME("(%p, %s, %d): stub\n", pBC, debugstr_w(szURL), dwReserved);
451
452     if (dwReserved || !szURL)
453         return E_INVALIDARG;
454
455     return S_OK;
456 }
457
458 /**************************************************************************
459  *                 FaultInIEFeature (URLMON.@)
460  *
461  *  Undocumented.  Appears to be used by native shdocvw.dll.
462  */
463 HRESULT WINAPI FaultInIEFeature( HWND hwnd, uCLSSPEC * pClassSpec,
464                                  QUERYCONTEXT *pQuery, DWORD flags )
465 {
466     FIXME("%p %p %p %08x\n", hwnd, pClassSpec, pQuery, flags);
467     return E_NOTIMPL;
468 }
469
470 /**************************************************************************
471  *                 CoGetClassObjectFromURL (URLMON.@)
472  */
473 HRESULT WINAPI CoGetClassObjectFromURL( REFCLSID rclsid, LPCWSTR szCodeURL, DWORD dwFileVersionMS,
474                                         DWORD dwFileVersionLS, LPCWSTR szContentType,
475                                         LPBINDCTX pBindCtx, DWORD dwClsContext, LPVOID pvReserved,
476                                         REFIID riid, LPVOID *ppv )
477 {
478     FIXME("(%s %s %d %d %s %p %d %p %s %p) Stub!\n", debugstr_guid(rclsid), debugstr_w(szCodeURL),
479         dwFileVersionMS, dwFileVersionLS, debugstr_w(szContentType), pBindCtx, dwClsContext, pvReserved,
480         debugstr_guid(riid), ppv);
481     return E_NOINTERFACE;
482 }
483
484 /***********************************************************************
485  *           ReleaseBindInfo (URLMON.@)
486  *
487  * Release the resources used by the specified BINDINFO structure.
488  *
489  * PARAMS
490  *  pbindinfo [I] BINDINFO to release.
491  *
492  * RETURNS
493  *  Nothing.
494  */
495 void WINAPI ReleaseBindInfo(BINDINFO* pbindinfo)
496 {
497     DWORD size;
498
499     TRACE("(%p)\n", pbindinfo);
500
501     if(!pbindinfo || !(size = pbindinfo->cbSize))
502         return;
503
504     CoTaskMemFree(pbindinfo->szExtraInfo);
505     ReleaseStgMedium(&pbindinfo->stgmedData);
506
507     if(offsetof(BINDINFO, szExtraInfo) < size)
508         CoTaskMemFree(pbindinfo->szCustomVerb);
509
510     if(pbindinfo->pUnk && offsetof(BINDINFO, pUnk) < size)
511         IUnknown_Release(pbindinfo->pUnk);
512
513     memset(pbindinfo, 0, size);
514     pbindinfo->cbSize = size;
515 }
516
517 /***********************************************************************
518  *           CopyStgMedium (URLMON.@)
519  */
520 HRESULT WINAPI CopyStgMedium(const STGMEDIUM *src, STGMEDIUM *dst)
521 {
522     TRACE("(%p %p)\n", src, dst);
523
524     if(!src || !dst)
525         return E_POINTER;
526
527     *dst = *src;
528
529     switch(dst->tymed) {
530     case TYMED_NULL:
531         break;
532     case TYMED_FILE:
533         if(src->u.lpszFileName && !src->pUnkForRelease) {
534             DWORD size = (strlenW(src->u.lpszFileName)+1)*sizeof(WCHAR);
535             dst->u.lpszFileName = CoTaskMemAlloc(size);
536             memcpy(dst->u.lpszFileName, src->u.lpszFileName, size);
537         }
538         break;
539     case TYMED_ISTREAM:
540         if(dst->u.pstm)
541             IStream_AddRef(dst->u.pstm);
542         break;
543     case TYMED_ISTORAGE:
544         if(dst->u.pstg)
545             IStorage_AddRef(dst->u.pstg);
546         break;
547     default:
548         FIXME("Unimplemented tymed %d\n", src->tymed);
549     }
550
551     if(dst->pUnkForRelease)
552         IUnknown_AddRef(dst->pUnkForRelease);
553
554     return S_OK;
555 }
556
557 static BOOL text_richtext_filter(const BYTE *b, DWORD size)
558 {
559     return size > 5 && !memcmp(b, "{\\rtf", 5);
560 }
561
562 static BOOL text_html_filter(const BYTE *b, DWORD size)
563 {
564     DWORD i;
565
566     if(size < 5)
567         return FALSE;
568
569     for(i = 0; i < size-5; i++) {
570         if((b[i] == '<'
571             && (b[i+1] == 'h' || b[i+1] == 'H')
572             && (b[i+2] == 't' || b[i+2] == 'T')
573             && (b[i+3] == 'm' || b[i+3] == 'M')
574             && (b[i+4] == 'l' || b[i+4] == 'L')) ||
575            ((size - i >= 6)
576             &&  b[i]   == '<'
577             && (b[i+1] == 'h' || b[i+1] == 'H')
578             && (b[i+2] == 'e' || b[i+2] == 'E')
579             && (b[i+3] == 'a' || b[i+3] == 'A')
580             && (b[i+4] == 'd' || b[i+4] == 'D')
581             &&  b[i+5] == '>')) return TRUE;
582     }
583
584     return FALSE;
585 }
586
587 static BOOL audio_basic_filter(const BYTE *b, DWORD size)
588 {
589     return size > 4
590         && b[0] == '.' && b[1] == 's' && b[2] == 'n' && b[3] == 'd';
591 }
592
593 static BOOL audio_wav_filter(const BYTE *b, DWORD size)
594 {
595     return size > 12
596         && b[0] == 'R' && b[1] == 'I' && b[2] == 'F' && b[3] == 'F'
597         && b[8] == 'W' && b[9] == 'A' && b[10] == 'V' && b[11] == 'E';
598 }
599
600 static BOOL image_gif_filter(const BYTE *b, DWORD size)
601 {
602     return size >= 6
603         && (b[0] == 'G' || b[0] == 'g')
604         && (b[1] == 'I' || b[1] == 'i')
605         && (b[2] == 'F' || b[2] == 'f')
606         &&  b[3] == '8'
607         && (b[4] == '7' || b[4] == '9')
608         && (b[5] == 'A' || b[5] == 'a');
609 }
610
611 static BOOL image_pjpeg_filter(const BYTE *b, DWORD size)
612 {
613     return size > 2 && b[0] == 0xff && b[1] == 0xd8;
614 }
615
616 static BOOL image_tiff_filter(const BYTE *b, DWORD size)
617 {
618     static const BYTE magic1[] = {0x4d,0x4d,0x00,0x2a};
619     static const BYTE magic2[] = {0x49,0x49,0x2a,0xff};
620
621     return size >= 4 && (!memcmp(b, magic1, 4) || !memcmp(b, magic2, 4));
622 }
623
624 static BOOL image_xpng_filter(const BYTE *b, DWORD size)
625 {
626     static const BYTE xpng_header[] = {0x89,'P','N','G',0x0d,0x0a,0x1a,0x0a};
627     return size > sizeof(xpng_header) && !memcmp(b, xpng_header, sizeof(xpng_header));
628 }
629
630 static BOOL image_bmp_filter(const BYTE *b, DWORD size)
631 {
632     return size >= 14
633         && b[0] == 0x42 && b[1] == 0x4d
634         && *(const DWORD *)(b+6) == 0;
635 }
636
637 static BOOL video_avi_filter(const BYTE *b, DWORD size)
638 {
639     return size > 12
640         && b[0] == 'R' && b[1] == 'I' && b[2] == 'F' && b[3] == 'F'
641         && b[8] == 'A' && b[9] == 'V' && b[10] == 'I' && b[11] == 0x20;
642 }
643
644 static BOOL video_mpeg_filter(const BYTE *b, DWORD size)
645 {
646     return size > 4
647         && !b[0] && !b[1] && b[2] == 0x01
648         && (b[3] == 0xb3 || b[3] == 0xba);
649 }
650
651 static BOOL application_postscript_filter(const BYTE *b, DWORD size)
652 {
653     return size > 2 && b[0] == '%' && b[1] == '!';
654 }
655
656 static BOOL application_pdf_filter(const BYTE *b, DWORD size)
657 {
658     return size > 4 && b[0] == 0x25 && b[1] == 0x50 && b[2] == 0x44 && b[3] == 0x46;
659 }
660
661 static BOOL application_xzip_filter(const BYTE *b, DWORD size)
662 {
663     return size > 2 && b[0] == 0x50 && b[1] == 0x4b;
664 }
665
666 static BOOL application_xgzip_filter(const BYTE *b, DWORD size)
667 {
668     return size > 2 && b[0] == 0x1f && b[1] == 0x8b;
669 }
670
671 static BOOL application_java_filter(const BYTE *b, DWORD size)
672 {
673     return size > 4 && b[0] == 0xca && b[1] == 0xfe && b[2] == 0xba && b[3] == 0xbe;
674 }
675
676 static BOOL application_xmsdownload(const BYTE *b, DWORD size)
677 {
678     return size > 2 && b[0] == 'M' && b[1] == 'Z';
679 }
680
681 static BOOL text_plain_filter(const BYTE *b, DWORD size)
682 {
683     const BYTE *ptr;
684
685     for(ptr = b; ptr < b+size-1; ptr++) {
686         if(*ptr < 0x20 && *ptr != '\n' && *ptr != '\r' && *ptr != '\t')
687             return FALSE;
688     }
689
690     return TRUE;
691 }
692
693 static BOOL application_octet_stream_filter(const BYTE *b, DWORD size)
694 {
695     return TRUE;
696 }
697
698 static HRESULT find_mime_from_buffer(const BYTE *buf, DWORD size, const WCHAR *proposed_mime, WCHAR **ret_mime)
699 {
700     LPCWSTR ret = NULL;
701     DWORD len, i;
702
703     static const WCHAR text_htmlW[] = {'t','e','x','t','/','h','t','m','l',0};
704     static const WCHAR text_richtextW[] = {'t','e','x','t','/','r','i','c','h','t','e','x','t',0};
705     static const WCHAR audio_basicW[] = {'a','u','d','i','o','/','b','a','s','i','c',0};
706     static const WCHAR audio_wavW[] = {'a','u','d','i','o','/','w','a','v',0};
707     static const WCHAR image_gifW[] = {'i','m','a','g','e','/','g','i','f',0};
708     static const WCHAR image_pjpegW[] = {'i','m','a','g','e','/','p','j','p','e','g',0};
709     static const WCHAR image_tiffW[] = {'i','m','a','g','e','/','t','i','f','f',0};
710     static const WCHAR image_xpngW[] = {'i','m','a','g','e','/','x','-','p','n','g',0};
711     static const WCHAR image_bmpW[] = {'i','m','a','g','e','/','b','m','p',0};
712     static const WCHAR video_aviW[] = {'v','i','d','e','o','/','a','v','i',0};
713     static const WCHAR video_mpegW[] = {'v','i','d','e','o','/','m','p','e','g',0};
714     static const WCHAR app_postscriptW[] =
715         {'a','p','p','l','i','c','a','t','i','o','n','/','p','o','s','t','s','c','r','i','p','t',0};
716     static const WCHAR app_pdfW[] = {'a','p','p','l','i','c','a','t','i','o','n','/','p','d','f',0};
717     static const WCHAR app_xzipW[] = {'a','p','p','l','i','c','a','t','i','o','n','/',
718         'x','-','z','i','p','-','c','o','m','p','r','e','s','s','e','d',0};
719     static const WCHAR app_xgzipW[] = {'a','p','p','l','i','c','a','t','i','o','n','/',
720         'x','-','g','z','i','p','-','c','o','m','p','r','e','s','s','e','d',0};
721     static const WCHAR app_javaW[] = {'a','p','p','l','i','c','a','t','i','o','n','/',
722         'j','a','v','a',0};
723     static const WCHAR app_xmsdownloadW[] = {'a','p','p','l','i','c','a','t','i','o','n','/',
724         'x','-','m','s','d','o','w','n','l','o','a','d',0};
725     static const WCHAR text_plainW[] = {'t','e','x','t','/','p','l','a','i','n','\0'};
726     static const WCHAR app_octetstreamW[] = {'a','p','p','l','i','c','a','t','i','o','n','/',
727         'o','c','t','e','t','-','s','t','r','e','a','m','\0'};
728
729     static const struct {
730         LPCWSTR mime;
731         BOOL (*filter)(const BYTE *,DWORD);
732     } mime_filters[] = {
733         {text_htmlW,       text_html_filter},
734         {text_richtextW,   text_richtext_filter},
735      /* {audio_xaiffW,     audio_xaiff_filter}, */
736         {audio_basicW,     audio_basic_filter},
737         {audio_wavW,       audio_wav_filter},
738         {image_gifW,       image_gif_filter},
739         {image_pjpegW,     image_pjpeg_filter},
740         {image_tiffW,      image_tiff_filter},
741         {image_xpngW,      image_xpng_filter},
742      /* {image_xbitmapW,   image_xbitmap_filter}, */
743         {image_bmpW,       image_bmp_filter},
744      /* {image_xjgW,       image_xjg_filter}, */
745      /* {image_xemfW,      image_xemf_filter}, */
746      /* {image_xwmfW,      image_xwmf_filter}, */
747         {video_aviW,       video_avi_filter},
748         {video_mpegW,      video_mpeg_filter},
749         {app_postscriptW,  application_postscript_filter},
750      /* {app_base64W,      application_base64_filter}, */
751      /* {app_macbinhex40W, application_macbinhex40_filter}, */
752         {app_pdfW,         application_pdf_filter},
753      /* {app_zcompressedW, application_xcompressed_filter}, */
754         {app_xzipW,        application_xzip_filter},
755         {app_xgzipW,       application_xgzip_filter},
756         {app_javaW,        application_java_filter},
757         {app_xmsdownloadW, application_xmsdownload},
758         {text_plainW,      text_plain_filter},
759         {app_octetstreamW, application_octet_stream_filter}
760     };
761
762     if(!buf || !size) {
763         if(!proposed_mime)
764             return E_FAIL;
765
766         len = strlenW(proposed_mime)+1;
767         *ret_mime = CoTaskMemAlloc(len*sizeof(WCHAR));
768         if(!*ret_mime)
769             return E_OUTOFMEMORY;
770
771         memcpy(*ret_mime, proposed_mime, len*sizeof(WCHAR));
772         return S_OK;
773     }
774
775     if(proposed_mime && strcmpW(proposed_mime, app_octetstreamW)) {
776         for(i=0; i < sizeof(mime_filters)/sizeof(*mime_filters); i++) {
777             if(!strcmpW(proposed_mime, mime_filters[i].mime))
778                 break;
779         }
780
781         if(i == sizeof(mime_filters)/sizeof(*mime_filters) || mime_filters[i].filter(buf, size)) {
782             len = strlenW(proposed_mime)+1;
783             *ret_mime = CoTaskMemAlloc(len*sizeof(WCHAR));
784             if(!*ret_mime)
785                 return E_OUTOFMEMORY;
786
787             memcpy(*ret_mime, proposed_mime, len*sizeof(WCHAR));
788             return S_OK;
789         }
790     }
791
792     i=0;
793     while(!ret) {
794         if(mime_filters[i].filter(buf, size))
795             ret = mime_filters[i].mime;
796         i++;
797     }
798
799     TRACE("found %s for %s\n", debugstr_w(ret), debugstr_an((const char*)buf, min(32, size)));
800
801     if(proposed_mime) {
802         if(i == sizeof(mime_filters)/sizeof(*mime_filters))
803             ret = proposed_mime;
804
805         /* text/html is a special case */
806         if(!strcmpW(proposed_mime, text_htmlW) && !strcmpW(ret, text_plainW))
807             ret = text_htmlW;
808     }
809
810     len = strlenW(ret)+1;
811     *ret_mime = CoTaskMemAlloc(len*sizeof(WCHAR));
812     if(!*ret_mime)
813         return E_OUTOFMEMORY;
814
815     memcpy(*ret_mime, ret, len*sizeof(WCHAR));
816     return S_OK;
817 }
818
819 /***********************************************************************
820  *           FindMimeFromData (URLMON.@)
821  *
822  * Determines the Multipurpose Internet Mail Extensions (MIME) type from the data provided.
823  */
824 HRESULT WINAPI FindMimeFromData(LPBC pBC, LPCWSTR pwzUrl, LPVOID pBuffer,
825         DWORD cbSize, LPCWSTR pwzMimeProposed, DWORD dwMimeFlags,
826         LPWSTR* ppwzMimeOut, DWORD dwReserved)
827 {
828     TRACE("(%p,%s,%p,%d,%s,0x%x,%p,0x%x)\n", pBC, debugstr_w(pwzUrl), pBuffer, cbSize,
829             debugstr_w(pwzMimeProposed), dwMimeFlags, ppwzMimeOut, dwReserved);
830
831     if(dwMimeFlags)
832         WARN("dwMimeFlags=%08x\n", dwMimeFlags);
833     if(dwReserved)
834         WARN("dwReserved=%d\n", dwReserved);
835
836     /* pBC seams to not be used */
837
838     if(!ppwzMimeOut || (!pwzUrl && !pBuffer))
839         return E_INVALIDARG;
840
841     if(pwzMimeProposed || pBuffer)
842         return find_mime_from_buffer(pBuffer, cbSize, pwzMimeProposed, ppwzMimeOut);
843
844     if(pwzUrl) {
845         HKEY hkey;
846         DWORD res, size;
847         LPCWSTR ptr;
848         WCHAR mime[64];
849
850         static const WCHAR wszContentType[] =
851                 {'C','o','n','t','e','n','t',' ','T','y','p','e','\0'};
852
853         ptr = strrchrW(pwzUrl, '.');
854         if(!ptr)
855             return E_FAIL;
856
857         res = RegOpenKeyW(HKEY_CLASSES_ROOT, ptr, &hkey);
858         if(res != ERROR_SUCCESS)
859             return HRESULT_FROM_WIN32(res);
860
861         size = sizeof(mime);
862         res = RegQueryValueExW(hkey, wszContentType, NULL, NULL, (LPBYTE)mime, &size);
863         RegCloseKey(hkey);
864         if(res != ERROR_SUCCESS)
865             return HRESULT_FROM_WIN32(res);
866
867         *ppwzMimeOut = CoTaskMemAlloc(size);
868         memcpy(*ppwzMimeOut, mime, size);
869         return S_OK;
870     }
871
872     return E_FAIL;
873 }
874
875 /***********************************************************************
876  *           GetClassFileOrMime (URLMON.@)
877  *
878  * Determines the class ID from the bind context, file name or MIME type.
879  */
880 HRESULT WINAPI GetClassFileOrMime(LPBC pBC, LPCWSTR pszFilename,
881         LPVOID pBuffer, DWORD cbBuffer, LPCWSTR pszMimeType, DWORD dwReserved,
882         CLSID *pclsid)
883 {
884     FIXME("(%p, %s, %p, %d, %p, 0x%08x, %p): stub\n", pBC,
885         debugstr_w(pszFilename), pBuffer, cbBuffer, debugstr_w(pszMimeType),
886         dwReserved, pclsid);
887     return E_NOTIMPL;
888 }
889
890 /***********************************************************************
891  * Extract (URLMON.@)
892  */
893 HRESULT WINAPI Extract(void *dest, LPCSTR szCabName)
894 {
895     HRESULT (WINAPI *pExtract)(void *, LPCSTR);
896
897     if (!hCabinet)
898         hCabinet = LoadLibraryA("cabinet.dll");
899
900     if (!hCabinet) return HRESULT_FROM_WIN32(GetLastError());
901     pExtract = (void *)GetProcAddress(hCabinet, "Extract");
902     if (!pExtract) return HRESULT_FROM_WIN32(GetLastError());
903
904     return pExtract(dest, szCabName);
905 }
906
907 /***********************************************************************
908  *           IsLoggingEnabledA (URLMON.@)
909  */
910 BOOL WINAPI IsLoggingEnabledA(LPCSTR url)
911 {
912     FIXME("(%s)\n", debugstr_a(url));
913     return FALSE;
914 }
915
916 /***********************************************************************
917  *           IsLoggingEnabledW (URLMON.@)
918  */
919 BOOL WINAPI IsLoggingEnabledW(LPCWSTR url)
920 {
921     FIXME("(%s)\n", debugstr_w(url));
922     return FALSE;
923 }
924
925 /***********************************************************************
926  *           IsProtectedModeURL (URLMON.111)
927  *    Undocumented, added in IE7
928  */
929 BOOL WINAPI IsProtectedModeURL(const WCHAR *url)
930 {
931     FIXME("stub: %s\n", debugstr_w(url));
932     return TRUE;
933 }
934
935 /***********************************************************************
936  *           LogSqmBits (URLMON.410)
937  *    Undocumented, added in IE8
938  */
939 int WINAPI LogSqmBits(DWORD unk1, DWORD unk2)
940 {
941     FIXME("stub: %d %d\n", unk1, unk2);
942     return 0;
943 }
944
945 /***********************************************************************
946  *           LogSqmUXCommandOffsetInternal (URLMON.423)
947  *    Undocumented, added in IE8
948  */
949 void WINAPI LogSqmUXCommandOffsetInternal(DWORD unk1, DWORD unk2, DWORD unk3, DWORD unk4)
950 {
951     FIXME("stub: %d %d %d %d\n", unk1, unk2, unk3, unk4);
952 }
953
954 /***********************************************************************
955  *           MapUriToBrowserEmulationState (URLMON.444)
956  *    Undocumented, added in IE8
957  */
958 int WINAPI MapUriToBrowserEmulationState(DWORD unk1, DWORD unk2, DWORD unk3)
959 {
960     FIXME("stub: %d %d %d\n", unk1, unk2, unk3);
961     return 0;
962 }
963
964 /***********************************************************************
965  *           MapBrowserEmulationModeToUserAgent (URLMON.445)
966  *    Undocumented, added in IE8
967  */
968 int WINAPI MapBrowserEmulationModeToUserAgent(DWORD unk1, DWORD unk2)
969 {
970     FIXME("stub: %d %d\n", unk1, unk2);
971     return 0;
972 }
973
974 /***********************************************************************
975  *            RegisterMediaTypes
976  *    Added in IE3, registers known MIME-type strings.
977  */
978 HRESULT WINAPI RegisterMediaTypes(UINT types, LPCSTR *szTypes, CLIPFORMAT *cfTypes)
979 {
980    FIXME("stub: %u %p %p\n", types, szTypes, cfTypes);
981    return E_INVALIDARG;
982 }