setupapi: Add stub implementations of SetupUninstallOEMInfA/W.
[wine] / dlls / setupapi / misc.c
1 /*
2  * Setupapi miscellaneous functions
3  *
4  * Copyright 2005 Eric Kohl
5  * Copyright 2007 Hans Leidekker
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include <stdarg.h>
23
24 #include "windef.h"
25 #include "winbase.h"
26 #include "wingdi.h"
27 #include "winuser.h"
28 #include "winreg.h"
29 #include "setupapi.h"
30 #include "lzexpand.h"
31 #include "softpub.h"
32 #include "mscat.h"
33
34 #include "wine/unicode.h"
35 #include "wine/debug.h"
36
37 #include "setupapi_private.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(setupapi);
40
41 /* arbitrary limit not related to what native actually uses */
42 #define OEM_INDEX_LIMIT 999
43
44 /**************************************************************************
45  * MyFree [SETUPAPI.@]
46  *
47  * Frees an allocated memory block from the process heap.
48  *
49  * PARAMS
50  *     lpMem [I] pointer to memory block which will be freed
51  *
52  * RETURNS
53  *     None
54  */
55 VOID WINAPI MyFree(LPVOID lpMem)
56 {
57     HeapFree(GetProcessHeap(), 0, lpMem);
58 }
59
60
61 /**************************************************************************
62  * MyMalloc [SETUPAPI.@]
63  *
64  * Allocates memory block from the process heap.
65  *
66  * PARAMS
67  *     dwSize [I] size of the allocated memory block
68  *
69  * RETURNS
70  *     Success: pointer to allocated memory block
71  *     Failure: NULL
72  */
73 LPVOID WINAPI MyMalloc(DWORD dwSize)
74 {
75     return HeapAlloc(GetProcessHeap(), 0, dwSize);
76 }
77
78
79 /**************************************************************************
80  * MyRealloc [SETUPAPI.@]
81  *
82  * Changes the size of an allocated memory block or allocates a memory
83  * block from the process heap.
84  *
85  * PARAMS
86  *     lpSrc  [I] pointer to memory block which will be resized
87  *     dwSize [I] new size of the memory block
88  *
89  * RETURNS
90  *     Success: pointer to the resized memory block
91  *     Failure: NULL
92  *
93  * NOTES
94  *     If lpSrc is a NULL-pointer, then MyRealloc allocates a memory
95  *     block like MyMalloc.
96  */
97 LPVOID WINAPI MyRealloc(LPVOID lpSrc, DWORD dwSize)
98 {
99     if (lpSrc == NULL)
100         return HeapAlloc(GetProcessHeap(), 0, dwSize);
101
102     return HeapReAlloc(GetProcessHeap(), 0, lpSrc, dwSize);
103 }
104
105
106 /**************************************************************************
107  * DuplicateString [SETUPAPI.@]
108  *
109  * Duplicates a unicode string.
110  *
111  * PARAMS
112  *     lpSrc  [I] pointer to the unicode string that will be duplicated
113  *
114  * RETURNS
115  *     Success: pointer to the duplicated unicode string
116  *     Failure: NULL
117  *
118  * NOTES
119  *     Call MyFree() to release the duplicated string.
120  */
121 LPWSTR WINAPI DuplicateString(LPCWSTR lpSrc)
122 {
123     LPWSTR lpDst;
124
125     lpDst = MyMalloc((lstrlenW(lpSrc) + 1) * sizeof(WCHAR));
126     if (lpDst == NULL)
127         return NULL;
128
129     strcpyW(lpDst, lpSrc);
130
131     return lpDst;
132 }
133
134
135 /**************************************************************************
136  * QueryRegistryValue [SETUPAPI.@]
137  *
138  * Retrieves value data from the registry and allocates memory for the
139  * value data.
140  *
141  * PARAMS
142  *     hKey        [I] Handle of the key to query
143  *     lpValueName [I] Name of value under hkey to query
144  *     lpData      [O] Destination for the values contents,
145  *     lpType      [O] Destination for the value type
146  *     lpcbData    [O] Destination for the size of data
147  *
148  * RETURNS
149  *     Success: ERROR_SUCCESS
150  *     Failure: Otherwise
151  *
152  * NOTES
153  *     Use MyFree to release the lpData buffer.
154  */
155 LONG WINAPI QueryRegistryValue(HKEY hKey,
156                                LPCWSTR lpValueName,
157                                LPBYTE  *lpData,
158                                LPDWORD lpType,
159                                LPDWORD lpcbData)
160 {
161     LONG lError;
162
163     TRACE("%p %s %p %p %p\n",
164           hKey, debugstr_w(lpValueName), lpData, lpType, lpcbData);
165
166     /* Get required buffer size */
167     *lpcbData = 0;
168     lError = RegQueryValueExW(hKey, lpValueName, 0, lpType, NULL, lpcbData);
169     if (lError != ERROR_SUCCESS)
170         return lError;
171
172     /* Allocate buffer */
173     *lpData = MyMalloc(*lpcbData);
174     if (*lpData == NULL)
175         return ERROR_NOT_ENOUGH_MEMORY;
176
177     /* Query registry value */
178     lError = RegQueryValueExW(hKey, lpValueName, 0, lpType, *lpData, lpcbData);
179     if (lError != ERROR_SUCCESS)
180         MyFree(*lpData);
181
182     return lError;
183 }
184
185
186 /**************************************************************************
187  * IsUserAdmin [SETUPAPI.@]
188  *
189  * Checks whether the current user is a member of the Administrators group.
190  *
191  * PARAMS
192  *     None
193  *
194  * RETURNS
195  *     Success: TRUE
196  *     Failure: FALSE
197  */
198 BOOL WINAPI IsUserAdmin(VOID)
199 {
200     SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
201     HANDLE hToken;
202     DWORD dwSize;
203     PTOKEN_GROUPS lpGroups;
204     PSID lpSid;
205     DWORD i;
206     BOOL bResult = FALSE;
207
208     TRACE("\n");
209
210     if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
211     {
212         return FALSE;
213     }
214
215     if (!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
216     {
217         if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
218         {
219             CloseHandle(hToken);
220             return FALSE;
221         }
222     }
223
224     lpGroups = MyMalloc(dwSize);
225     if (lpGroups == NULL)
226     {
227         CloseHandle(hToken);
228         return FALSE;
229     }
230
231     if (!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
232     {
233         MyFree(lpGroups);
234         CloseHandle(hToken);
235         return FALSE;
236     }
237
238     CloseHandle(hToken);
239
240     if (!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID,
241                                   DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
242                                   &lpSid))
243     {
244         MyFree(lpGroups);
245         return FALSE;
246     }
247
248     for (i = 0; i < lpGroups->GroupCount; i++)
249     {
250         if (EqualSid(lpSid, lpGroups->Groups[i].Sid))
251         {
252             bResult = TRUE;
253             break;
254         }
255     }
256
257     FreeSid(lpSid);
258     MyFree(lpGroups);
259
260     return bResult;
261 }
262
263
264 /**************************************************************************
265  * MultiByteToUnicode [SETUPAPI.@]
266  *
267  * Converts a multi-byte string to a Unicode string.
268  *
269  * PARAMS
270  *     lpMultiByteStr  [I] Multi-byte string to be converted
271  *     uCodePage       [I] Code page
272  *
273  * RETURNS
274  *     Success: pointer to the converted Unicode string
275  *     Failure: NULL
276  *
277  * NOTE
278  *     Use MyFree to release the returned Unicode string.
279  */
280 LPWSTR WINAPI MultiByteToUnicode(LPCSTR lpMultiByteStr, UINT uCodePage)
281 {
282     LPWSTR lpUnicodeStr;
283     int nLength;
284
285     nLength = MultiByteToWideChar(uCodePage, 0, lpMultiByteStr,
286                                   -1, NULL, 0);
287     if (nLength == 0)
288         return NULL;
289
290     lpUnicodeStr = MyMalloc(nLength * sizeof(WCHAR));
291     if (lpUnicodeStr == NULL)
292         return NULL;
293
294     if (!MultiByteToWideChar(uCodePage, 0, lpMultiByteStr,
295                              nLength, lpUnicodeStr, nLength))
296     {
297         MyFree(lpUnicodeStr);
298         return NULL;
299     }
300
301     return lpUnicodeStr;
302 }
303
304
305 /**************************************************************************
306  * UnicodeToMultiByte [SETUPAPI.@]
307  *
308  * Converts a Unicode string to a multi-byte string.
309  *
310  * PARAMS
311  *     lpUnicodeStr  [I] Unicode string to be converted
312  *     uCodePage     [I] Code page
313  *
314  * RETURNS
315  *     Success: pointer to the converted multi-byte string
316  *     Failure: NULL
317  *
318  * NOTE
319  *     Use MyFree to release the returned multi-byte string.
320  */
321 LPSTR WINAPI UnicodeToMultiByte(LPCWSTR lpUnicodeStr, UINT uCodePage)
322 {
323     LPSTR lpMultiByteStr;
324     int nLength;
325
326     nLength = WideCharToMultiByte(uCodePage, 0, lpUnicodeStr, -1,
327                                   NULL, 0, NULL, NULL);
328     if (nLength == 0)
329         return NULL;
330
331     lpMultiByteStr = MyMalloc(nLength);
332     if (lpMultiByteStr == NULL)
333         return NULL;
334
335     if (!WideCharToMultiByte(uCodePage, 0, lpUnicodeStr, -1,
336                              lpMultiByteStr, nLength, NULL, NULL))
337     {
338         MyFree(lpMultiByteStr);
339         return NULL;
340     }
341
342     return lpMultiByteStr;
343 }
344
345
346 /**************************************************************************
347  * DoesUserHavePrivilege [SETUPAPI.@]
348  *
349  * Check whether the current user has got a given privilege.
350  *
351  * PARAMS
352  *     lpPrivilegeName  [I] Name of the privilege to be checked
353  *
354  * RETURNS
355  *     Success: TRUE
356  *     Failure: FALSE
357  */
358 BOOL WINAPI DoesUserHavePrivilege(LPCWSTR lpPrivilegeName)
359 {
360     HANDLE hToken;
361     DWORD dwSize;
362     PTOKEN_PRIVILEGES lpPrivileges;
363     LUID PrivilegeLuid;
364     DWORD i;
365     BOOL bResult = FALSE;
366
367     TRACE("%s\n", debugstr_w(lpPrivilegeName));
368
369     if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
370         return FALSE;
371
372     if (!GetTokenInformation(hToken, TokenPrivileges, NULL, 0, &dwSize))
373     {
374         if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
375         {
376             CloseHandle(hToken);
377             return FALSE;
378         }
379     }
380
381     lpPrivileges = MyMalloc(dwSize);
382     if (lpPrivileges == NULL)
383     {
384         CloseHandle(hToken);
385         return FALSE;
386     }
387
388     if (!GetTokenInformation(hToken, TokenPrivileges, lpPrivileges, dwSize, &dwSize))
389     {
390         MyFree(lpPrivileges);
391         CloseHandle(hToken);
392         return FALSE;
393     }
394
395     CloseHandle(hToken);
396
397     if (!LookupPrivilegeValueW(NULL, lpPrivilegeName, &PrivilegeLuid))
398     {
399         MyFree(lpPrivileges);
400         return FALSE;
401     }
402
403     for (i = 0; i < lpPrivileges->PrivilegeCount; i++)
404     {
405         if (lpPrivileges->Privileges[i].Luid.HighPart == PrivilegeLuid.HighPart &&
406             lpPrivileges->Privileges[i].Luid.LowPart == PrivilegeLuid.LowPart)
407         {
408             bResult = TRUE;
409         }
410     }
411
412     MyFree(lpPrivileges);
413
414     return bResult;
415 }
416
417
418 /**************************************************************************
419  * EnablePrivilege [SETUPAPI.@]
420  *
421  * Enables or disables one of the current users privileges.
422  *
423  * PARAMS
424  *     lpPrivilegeName  [I] Name of the privilege to be changed
425  *     bEnable          [I] TRUE: Enables the privilege
426  *                          FALSE: Disables the privilege
427  *
428  * RETURNS
429  *     Success: TRUE
430  *     Failure: FALSE
431  */
432 BOOL WINAPI EnablePrivilege(LPCWSTR lpPrivilegeName, BOOL bEnable)
433 {
434     TOKEN_PRIVILEGES Privileges;
435     HANDLE hToken;
436     BOOL bResult;
437
438     TRACE("%s %s\n", debugstr_w(lpPrivilegeName), bEnable ? "TRUE" : "FALSE");
439
440     if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
441         return FALSE;
442
443     Privileges.PrivilegeCount = 1;
444     Privileges.Privileges[0].Attributes = (bEnable) ? SE_PRIVILEGE_ENABLED : 0;
445
446     if (!LookupPrivilegeValueW(NULL, lpPrivilegeName,
447                                &Privileges.Privileges[0].Luid))
448     {
449         CloseHandle(hToken);
450         return FALSE;
451     }
452
453     bResult = AdjustTokenPrivileges(hToken, FALSE, &Privileges, 0, NULL, NULL);
454
455     CloseHandle(hToken);
456
457     return bResult;
458 }
459
460
461 /**************************************************************************
462  * DelayedMove [SETUPAPI.@]
463  *
464  * Moves a file upon the next reboot.
465  *
466  * PARAMS
467  *     lpExistingFileName  [I] Current file name
468  *     lpNewFileName       [I] New file name
469  *
470  * RETURNS
471  *     Success: TRUE
472  *     Failure: FALSE
473  */
474 BOOL WINAPI DelayedMove(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName)
475 {
476     return MoveFileExW(lpExistingFileName, lpNewFileName,
477                        MOVEFILE_REPLACE_EXISTING | MOVEFILE_DELAY_UNTIL_REBOOT);
478 }
479
480
481 /**************************************************************************
482  * FileExists [SETUPAPI.@]
483  *
484  * Checks whether a file exists.
485  *
486  * PARAMS
487  *     lpFileName     [I] Name of the file to check
488  *     lpNewFileName  [O] Optional information about the existing file
489  *
490  * RETURNS
491  *     Success: TRUE
492  *     Failure: FALSE
493  */
494 BOOL WINAPI FileExists(LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFileFindData)
495 {
496     WIN32_FIND_DATAW FindData;
497     HANDLE hFind;
498     UINT uErrorMode;
499     DWORD dwError;
500
501     uErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
502
503     hFind = FindFirstFileW(lpFileName, &FindData);
504     if (hFind == INVALID_HANDLE_VALUE)
505     {
506         dwError = GetLastError();
507         SetErrorMode(uErrorMode);
508         SetLastError(dwError);
509         return FALSE;
510     }
511
512     FindClose(hFind);
513
514     if (lpFileFindData)
515         *lpFileFindData = FindData;
516
517     SetErrorMode(uErrorMode);
518
519     return TRUE;
520 }
521
522
523 /**************************************************************************
524  * CaptureStringArg [SETUPAPI.@]
525  *
526  * Captures a UNICODE string.
527  *
528  * PARAMS
529  *     lpSrc  [I] UNICODE string to be captured
530  *     lpDst  [O] Pointer to the captured UNICODE string
531  *
532  * RETURNS
533  *     Success: ERROR_SUCCESS
534  *     Failure: ERROR_INVALID_PARAMETER
535  *
536  * NOTE
537  *     Call MyFree to release the captured UNICODE string.
538  */
539 DWORD WINAPI CaptureStringArg(LPCWSTR pSrc, LPWSTR *pDst)
540 {
541     if (pDst == NULL)
542         return ERROR_INVALID_PARAMETER;
543
544     *pDst = DuplicateString(pSrc);
545
546     return ERROR_SUCCESS;
547 }
548
549
550 /**************************************************************************
551  * CaptureAndConvertAnsiArg [SETUPAPI.@]
552  *
553  * Captures an ANSI string and converts it to a UNICODE string.
554  *
555  * PARAMS
556  *     lpSrc  [I] ANSI string to be captured
557  *     lpDst  [O] Pointer to the captured UNICODE string
558  *
559  * RETURNS
560  *     Success: ERROR_SUCCESS
561  *     Failure: ERROR_INVALID_PARAMETER
562  *
563  * NOTE
564  *     Call MyFree to release the captured UNICODE string.
565  */
566 DWORD WINAPI CaptureAndConvertAnsiArg(LPCSTR pSrc, LPWSTR *pDst)
567 {
568     if (pDst == NULL)
569         return ERROR_INVALID_PARAMETER;
570
571     *pDst = MultiByteToUnicode(pSrc, CP_ACP);
572
573     return ERROR_SUCCESS;
574 }
575
576
577 /**************************************************************************
578  * OpenAndMapFileForRead [SETUPAPI.@]
579  *
580  * Open and map a file to a buffer.
581  *
582  * PARAMS
583  *     lpFileName [I] Name of the file to be opened
584  *     lpSize     [O] Pointer to the file size
585  *     lpFile     [0] Pointer to the file handle
586  *     lpMapping  [0] Pointer to the mapping handle
587  *     lpBuffer   [0] Pointer to the file buffer
588  *
589  * RETURNS
590  *     Success: ERROR_SUCCESS
591  *     Failure: Other
592  *
593  * NOTE
594  *     Call UnmapAndCloseFile to release the file.
595  */
596 DWORD WINAPI OpenAndMapFileForRead(LPCWSTR lpFileName,
597                                    LPDWORD lpSize,
598                                    LPHANDLE lpFile,
599                                    LPHANDLE lpMapping,
600                                    LPVOID *lpBuffer)
601 {
602     DWORD dwError;
603
604     TRACE("%s %p %p %p %p\n",
605           debugstr_w(lpFileName), lpSize, lpFile, lpMapping, lpBuffer);
606
607     *lpFile = CreateFileW(lpFileName, GENERIC_READ, FILE_SHARE_READ, NULL,
608                           OPEN_EXISTING, 0, NULL);
609     if (*lpFile == INVALID_HANDLE_VALUE)
610         return GetLastError();
611
612     *lpSize = GetFileSize(*lpFile, NULL);
613     if (*lpSize == INVALID_FILE_SIZE)
614     {
615         dwError = GetLastError();
616         CloseHandle(*lpFile);
617         return dwError;
618     }
619
620     *lpMapping = CreateFileMappingW(*lpFile, NULL, PAGE_READONLY, 0,
621                                     *lpSize, NULL);
622     if (*lpMapping == NULL)
623     {
624         dwError = GetLastError();
625         CloseHandle(*lpFile);
626         return dwError;
627     }
628
629     *lpBuffer = MapViewOfFile(*lpMapping, FILE_MAP_READ, 0, 0, *lpSize);
630     if (*lpBuffer == NULL)
631     {
632         dwError = GetLastError();
633         CloseHandle(*lpMapping);
634         CloseHandle(*lpFile);
635         return dwError;
636     }
637
638     return ERROR_SUCCESS;
639 }
640
641
642 /**************************************************************************
643  * UnmapAndCloseFile [SETUPAPI.@]
644  *
645  * Unmap and close a mapped file.
646  *
647  * PARAMS
648  *     hFile    [I] Handle to the file
649  *     hMapping [I] Handle to the file mapping
650  *     lpBuffer [I] Pointer to the file buffer
651  *
652  * RETURNS
653  *     Success: TRUE
654  *     Failure: FALSE
655  */
656 BOOL WINAPI UnmapAndCloseFile(HANDLE hFile, HANDLE hMapping, LPVOID lpBuffer)
657 {
658     TRACE("%p %p %p\n",
659           hFile, hMapping, lpBuffer);
660
661     if (!UnmapViewOfFile(lpBuffer))
662         return FALSE;
663
664     if (!CloseHandle(hMapping))
665         return FALSE;
666
667     if (!CloseHandle(hFile))
668         return FALSE;
669
670     return TRUE;
671 }
672
673
674 /**************************************************************************
675  * StampFileSecurity [SETUPAPI.@]
676  *
677  * Assign a new security descriptor to the given file.
678  *
679  * PARAMS
680  *     lpFileName          [I] Name of the file
681  *     pSecurityDescriptor [I] New security descriptor
682  *
683  * RETURNS
684  *     Success: ERROR_SUCCESS
685  *     Failure: other
686  */
687 DWORD WINAPI StampFileSecurity(LPCWSTR lpFileName, PSECURITY_DESCRIPTOR pSecurityDescriptor)
688 {
689     TRACE("%s %p\n", debugstr_w(lpFileName), pSecurityDescriptor);
690
691     if (!SetFileSecurityW(lpFileName, OWNER_SECURITY_INFORMATION |
692                           GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
693                           pSecurityDescriptor))
694         return GetLastError();
695
696     return ERROR_SUCCESS;
697 }
698
699
700 /**************************************************************************
701  * TakeOwnershipOfFile [SETUPAPI.@]
702  *
703  * Takes the ownership of the given file.
704  *
705  * PARAMS
706  *     lpFileName [I] Name of the file
707  *
708  * RETURNS
709  *     Success: ERROR_SUCCESS
710  *     Failure: other
711  */
712 DWORD WINAPI TakeOwnershipOfFile(LPCWSTR lpFileName)
713 {
714     SECURITY_DESCRIPTOR SecDesc;
715     HANDLE hToken = NULL;
716     PTOKEN_OWNER pOwner = NULL;
717     DWORD dwError;
718     DWORD dwSize;
719
720     TRACE("%s\n", debugstr_w(lpFileName));
721
722     if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
723         return GetLastError();
724
725     if (!GetTokenInformation(hToken, TokenOwner, NULL, 0, &dwSize))
726     {
727         goto fail;
728     }
729
730     pOwner = MyMalloc(dwSize);
731     if (pOwner == NULL)
732     {
733         CloseHandle(hToken);
734         return ERROR_NOT_ENOUGH_MEMORY;
735     }
736
737     if (!GetTokenInformation(hToken, TokenOwner, pOwner, dwSize, &dwSize))
738     {
739         goto fail;
740     }
741
742     if (!InitializeSecurityDescriptor(&SecDesc, SECURITY_DESCRIPTOR_REVISION))
743     {
744         goto fail;
745     }
746
747     if (!SetSecurityDescriptorOwner(&SecDesc, pOwner->Owner, FALSE))
748     {
749         goto fail;
750     }
751
752     if (!SetFileSecurityW(lpFileName, OWNER_SECURITY_INFORMATION, &SecDesc))
753     {
754         goto fail;
755     }
756
757     MyFree(pOwner);
758     CloseHandle(hToken);
759
760     return ERROR_SUCCESS;
761
762 fail:;
763     dwError = GetLastError();
764
765     MyFree(pOwner);
766
767     if (hToken != NULL)
768         CloseHandle(hToken);
769
770     return dwError;
771 }
772
773
774 /**************************************************************************
775  * RetreiveFileSecurity [SETUPAPI.@]
776  *
777  * Retrieve the security descriptor that is associated with the given file.
778  *
779  * PARAMS
780  *     lpFileName [I] Name of the file
781  *
782  * RETURNS
783  *     Success: ERROR_SUCCESS
784  *     Failure: other
785  */
786 DWORD WINAPI RetreiveFileSecurity(LPCWSTR lpFileName,
787                                   PSECURITY_DESCRIPTOR *pSecurityDescriptor)
788 {
789     PSECURITY_DESCRIPTOR SecDesc;
790     DWORD dwSize = 0x100;
791     DWORD dwError;
792
793     SecDesc = MyMalloc(dwSize);
794     if (SecDesc == NULL)
795         return ERROR_NOT_ENOUGH_MEMORY;
796
797     if (GetFileSecurityW(lpFileName, OWNER_SECURITY_INFORMATION |
798                          GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
799                          SecDesc, dwSize, &dwSize))
800     {
801       *pSecurityDescriptor = SecDesc;
802       return ERROR_SUCCESS;
803     }
804
805     dwError = GetLastError();
806     if (dwError != ERROR_INSUFFICIENT_BUFFER)
807     {
808         MyFree(SecDesc);
809         return dwError;
810     }
811
812     SecDesc = MyRealloc(SecDesc, dwSize);
813     if (SecDesc == NULL)
814         return ERROR_NOT_ENOUGH_MEMORY;
815
816     if (GetFileSecurityW(lpFileName, OWNER_SECURITY_INFORMATION |
817                          GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
818                          SecDesc, dwSize, &dwSize))
819     {
820       *pSecurityDescriptor = SecDesc;
821       return ERROR_SUCCESS;
822     }
823
824     dwError = GetLastError();
825     MyFree(SecDesc);
826
827     return dwError;
828 }
829
830
831 static DWORD global_flags = 0;  /* FIXME: what should be in here? */
832
833 /***********************************************************************
834  *              pSetupGetGlobalFlags  (SETUPAPI.@)
835  */
836 DWORD WINAPI pSetupGetGlobalFlags(void)
837 {
838     FIXME( "stub\n" );
839     return global_flags;
840 }
841
842
843 /***********************************************************************
844  *              pSetupSetGlobalFlags  (SETUPAPI.@)
845  */
846 void WINAPI pSetupSetGlobalFlags( DWORD flags )
847 {
848     global_flags = flags;
849 }
850
851 /***********************************************************************
852  *              CMP_WaitNoPendingInstallEvents  (SETUPAPI.@)
853  */
854 DWORD WINAPI CMP_WaitNoPendingInstallEvents( DWORD dwTimeout )
855 {
856     static BOOL warned = FALSE;
857
858     if (!warned)
859     {
860         FIXME("%d\n", dwTimeout);
861         warned = TRUE;
862     }
863     return WAIT_OBJECT_0;
864 }
865
866 /***********************************************************************
867  *              AssertFail  (SETUPAPI.@)
868  *
869  * Shows an assert fail error messagebox
870  *
871  * PARAMS
872  *   lpFile [I]         file where assert failed
873  *   uLine [I]          line number in file
874  *   lpMessage [I]      assert message
875  *
876  */
877 void WINAPI AssertFail(LPCSTR lpFile, UINT uLine, LPCSTR lpMessage)
878 {
879     FIXME("%s %u %s\n", lpFile, uLine, lpMessage);
880 }
881
882 /***********************************************************************
883  *      SetupCopyOEMInfA  (SETUPAPI.@)
884  */
885 BOOL WINAPI SetupCopyOEMInfA( PCSTR source, PCSTR location,
886                               DWORD media_type, DWORD style, PSTR dest,
887                               DWORD buffer_size, PDWORD required_size, PSTR *component )
888 {
889     BOOL ret = FALSE;
890     LPWSTR destW = NULL, sourceW = NULL, locationW = NULL;
891     DWORD size;
892
893     TRACE("%s, %s, %d, %d, %p, %d, %p, %p\n", debugstr_a(source), debugstr_a(location),
894           media_type, style, dest, buffer_size, required_size, component);
895
896     if (dest && !(destW = MyMalloc( buffer_size * sizeof(WCHAR) ))) return FALSE;
897     if (source && !(sourceW = strdupAtoW( source ))) goto done;
898     if (location && !(locationW = strdupAtoW( location ))) goto done;
899
900     if (!(ret = SetupCopyOEMInfW( sourceW, locationW, media_type, style, destW,
901                                   buffer_size, &size, NULL )))
902     {
903         if (required_size) *required_size = size;
904         goto done;
905     }
906
907     if (dest)
908     {
909         if (buffer_size >= size)
910         {
911             WideCharToMultiByte( CP_ACP, 0, destW, -1, dest, buffer_size, NULL, NULL );
912             if (component) *component = strrchr( dest, '\\' ) + 1;
913         }
914         else
915         {
916             SetLastError( ERROR_INSUFFICIENT_BUFFER );
917             goto done;
918         }
919     }
920
921 done:
922     MyFree( destW );
923     HeapFree( GetProcessHeap(), 0, sourceW );
924     HeapFree( GetProcessHeap(), 0, locationW );
925     if (ret) SetLastError(ERROR_SUCCESS);
926     return ret;
927 }
928
929 static int compare_files( HANDLE file1, HANDLE file2 )
930 {
931     char buffer1[2048];
932     char buffer2[2048];
933     DWORD size1;
934     DWORD size2;
935
936     while( ReadFile(file1, buffer1, sizeof(buffer1), &size1, NULL) &&
937            ReadFile(file2, buffer2, sizeof(buffer2), &size2, NULL) )
938     {
939         int ret;
940         if (size1 != size2)
941             return size1 > size2 ? 1 : -1;
942         if (!size1)
943             return 0;
944         ret = memcmp( buffer1, buffer2, size1 );
945         if (ret)
946             return ret;
947     }
948
949     return 0;
950 }
951
952 /***********************************************************************
953  *      SetupCopyOEMInfW  (SETUPAPI.@)
954  */
955 BOOL WINAPI SetupCopyOEMInfW( PCWSTR source, PCWSTR location,
956                               DWORD media_type, DWORD style, PWSTR dest,
957                               DWORD buffer_size, PDWORD required_size, PWSTR *component )
958 {
959     BOOL ret = FALSE;
960     WCHAR target[MAX_PATH], catalog_file[MAX_PATH], *p;
961     static const WCHAR inf[] = { '\\','i','n','f','\\',0 };
962     static const WCHAR wszVersion[] = { 'V','e','r','s','i','o','n',0 };
963     static const WCHAR wszCatalogFile[] = { 'C','a','t','a','l','o','g','F','i','l','e',0 };
964     DWORD size;
965     HINF hinf;
966
967     TRACE("%s, %s, %d, %d, %p, %d, %p, %p\n", debugstr_w(source), debugstr_w(location),
968           media_type, style, dest, buffer_size, required_size, component);
969
970     if (!source)
971     {
972         SetLastError(ERROR_INVALID_PARAMETER);
973         return FALSE;
974     }
975
976     /* check for a relative path */
977     if (!(*source == '\\' || (*source && source[1] == ':')))
978     {
979         SetLastError(ERROR_FILE_NOT_FOUND);
980         return FALSE;
981     }
982
983     if (!GetWindowsDirectoryW( target, sizeof(target)/sizeof(WCHAR) )) return FALSE;
984
985     strcatW( target, inf );
986     if ((p = strrchrW( source, '\\' )))
987         strcatW( target, p + 1 );
988
989     /* does the file exist already? */
990     if ((GetFileAttributesW( target ) != INVALID_FILE_ATTRIBUTES) &&
991         !(style & SP_COPY_NOOVERWRITE))
992     {
993         static const WCHAR oem[] = { 'o','e','m',0 };
994         unsigned int i;
995         LARGE_INTEGER source_file_size;
996         HANDLE source_file;
997
998         source_file = CreateFileW( source, FILE_READ_DATA | FILE_READ_ATTRIBUTES,
999                                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1000                                    NULL, OPEN_EXISTING, 0, NULL );
1001         if (source_file == INVALID_HANDLE_VALUE)
1002             return FALSE;
1003
1004         if (!GetFileSizeEx( source_file, &source_file_size ))
1005         {
1006             CloseHandle( source_file );
1007             return FALSE;
1008         }
1009
1010         p = strrchrW( target, '\\' ) + 1;
1011         memcpy( p, oem, sizeof(oem) );
1012         p += sizeof(oem)/sizeof(oem[0]) - 1;
1013
1014         /* generate OEMnnn.inf ending */
1015         for (i = 0; i < OEM_INDEX_LIMIT; i++)
1016         {
1017             static const WCHAR format[] = { '%','u','.','i','n','f',0 };
1018             HANDLE dest_file;
1019             LARGE_INTEGER dest_file_size;
1020
1021             wsprintfW( p, format, i );
1022             dest_file = CreateFileW( target, FILE_READ_DATA | FILE_READ_ATTRIBUTES,
1023                                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1024                                      NULL, OPEN_EXISTING, 0, NULL );
1025             /* if we found a file name that doesn't exist then we're done */
1026             if (dest_file == INVALID_HANDLE_VALUE)
1027                 break;
1028             /* now check if the same inf file has already been copied to the inf
1029              * directory. if so, use that file and don't create a new one */
1030             if (!GetFileSizeEx( dest_file, &dest_file_size ) ||
1031                 (dest_file_size.QuadPart != source_file_size.QuadPart) ||
1032                 compare_files( source_file, dest_file ))
1033             {
1034                 CloseHandle( dest_file );
1035                 continue;
1036             }
1037             CloseHandle( dest_file );
1038             break;
1039         }
1040
1041         CloseHandle( source_file );
1042         if (i == OEM_INDEX_LIMIT)
1043         {
1044             SetLastError( ERROR_FILENAME_EXCED_RANGE );
1045             return FALSE;
1046         }
1047     }
1048
1049     hinf = SetupOpenInfFileW( source, NULL, INF_STYLE_WIN4, NULL );
1050     if (hinf == INVALID_HANDLE_VALUE) return FALSE;
1051
1052     if (SetupGetLineTextW( NULL, hinf, wszVersion, wszCatalogFile, catalog_file,
1053                            sizeof(catalog_file)/sizeof(catalog_file[0]), NULL ))
1054     {
1055         WCHAR source_cat[MAX_PATH];
1056         HCATADMIN handle;
1057         HCATINFO cat;
1058         GUID msguid = DRIVER_ACTION_VERIFY;
1059
1060         SetupCloseInfFile( hinf );
1061
1062         strcpyW( source_cat, source );
1063         p = strrchrW( source_cat, '\\' );
1064         if (p) p++;
1065         else p = source_cat;
1066         strcpyW( p, catalog_file );
1067
1068         TRACE("installing catalog file %s\n", debugstr_w( source_cat ));
1069
1070         if (!CryptCATAdminAcquireContext(&handle, &msguid, 0))
1071         {
1072             ERR("Could not acquire security context\n");
1073             return FALSE;
1074         }
1075
1076         if (!(cat = CryptCATAdminAddCatalog(handle, source_cat, catalog_file, 0)))
1077         {
1078             ERR("Could not add catalog\n");
1079             CryptCATAdminReleaseContext(handle, 0);
1080             return FALSE;
1081         }
1082
1083         CryptCATAdminReleaseCatalogContext(handle, cat, 0);
1084         CryptCATAdminReleaseContext(handle, 0);
1085     }
1086     else
1087         SetupCloseInfFile( hinf );
1088
1089     if (!(ret = CopyFileW( source, target, (style & SP_COPY_NOOVERWRITE) != 0 )))
1090         return ret;
1091
1092     if (style & SP_COPY_DELETESOURCE)
1093         DeleteFileW( source );
1094
1095     size = strlenW( target ) + 1;
1096     if (dest)
1097     {
1098         if (buffer_size >= size)
1099         {
1100             strcpyW( dest, target );
1101         }
1102         else
1103         {
1104             SetLastError( ERROR_INSUFFICIENT_BUFFER );
1105             ret = FALSE;
1106         }
1107     }
1108
1109     if (component) *component = p + 1;
1110     if (required_size) *required_size = size;
1111     if (ret) SetLastError(ERROR_SUCCESS);
1112
1113     return ret;
1114 }
1115
1116 /***********************************************************************
1117  *      SetupUninstallOEMInfA  (SETUPAPI.@)
1118  */
1119 BOOL WINAPI SetupUninstallOEMInfA( PCSTR inf_file, DWORD flags, PVOID reserved )
1120 {
1121     BOOL ret;
1122     WCHAR *inf_fileW = NULL;
1123
1124     TRACE("%s, 0x%08x, %p\n", debugstr_a(inf_file), flags, reserved);
1125
1126     if (inf_file && !(inf_fileW = strdupAtoW( inf_file ))) return FALSE;
1127     ret = SetupUninstallOEMInfW( inf_fileW, flags, reserved );
1128     HeapFree( GetProcessHeap(), 0, inf_fileW );
1129     return ret;
1130 }
1131
1132 /***********************************************************************
1133  *      SetupUninstallOEMInfW  (SETUPAPI.@)
1134  */
1135 BOOL WINAPI SetupUninstallOEMInfW( PCWSTR inf_file, DWORD flags, PVOID reserved )
1136 {
1137     static const WCHAR infW[] = {'\\','i','n','f','\\',0};
1138     WCHAR target[MAX_PATH];
1139
1140     TRACE("%s, 0x%08x, %p\n", debugstr_w(inf_file), flags, reserved);
1141
1142     if (!GetWindowsDirectoryW( target, sizeof(target)/sizeof(WCHAR) )) return FALSE;
1143
1144     strcatW( target, infW );
1145     strcatW( target, inf_file );
1146
1147     if (flags & SUOI_FORCEDELETE)
1148         return DeleteFileW(target);
1149
1150     FIXME("not deleting %s\n", debugstr_w(target));
1151
1152     return TRUE;
1153 }
1154
1155 /***********************************************************************
1156  *      InstallCatalog  (SETUPAPI.@)
1157  */
1158 DWORD WINAPI InstallCatalog( LPCSTR catalog, LPCSTR basename, LPSTR fullname )
1159 {
1160     FIXME("%s, %s, %p\n", debugstr_a(catalog), debugstr_a(basename), fullname);
1161     return 0;
1162 }
1163
1164 /***********************************************************************
1165  *      pSetupInstallCatalog  (SETUPAPI.@)
1166  */
1167 DWORD WINAPI pSetupInstallCatalog( LPCWSTR catalog, LPCWSTR basename, LPWSTR fullname )
1168 {
1169     HCATADMIN admin;
1170     HCATINFO cat;
1171
1172     TRACE ("%s, %s, %p\n", debugstr_w(catalog), debugstr_w(basename), fullname);
1173
1174     if (!CryptCATAdminAcquireContext(&admin,NULL,0))
1175         return GetLastError();
1176
1177     if (!(cat = CryptCATAdminAddCatalog( admin, (PWSTR)catalog, (PWSTR)basename, 0 )))
1178     {
1179         DWORD rc = GetLastError();
1180         CryptCATAdminReleaseContext(admin, 0);
1181         return rc;
1182     }
1183     CryptCATAdminReleaseCatalogContext(admin, cat, 0);
1184     CryptCATAdminReleaseContext(admin,0);
1185
1186     if (fullname)
1187         FIXME("not returning full installed catalog path\n");
1188
1189     return NO_ERROR;
1190 }
1191
1192 static UINT detect_compression_type( LPCWSTR file )
1193 {
1194     DWORD size;
1195     HANDLE handle;
1196     UINT type = FILE_COMPRESSION_NONE;
1197     static const BYTE LZ_MAGIC[] = { 0x53, 0x5a, 0x44, 0x44, 0x88, 0xf0, 0x27, 0x33 };
1198     static const BYTE MSZIP_MAGIC[] = { 0x4b, 0x57, 0x41, 0x4a };
1199     static const BYTE NTCAB_MAGIC[] = { 0x4d, 0x53, 0x43, 0x46 };
1200     BYTE buffer[8];
1201
1202     handle = CreateFileW( file, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL );
1203     if (handle == INVALID_HANDLE_VALUE)
1204     {
1205         ERR("cannot open file %s\n", debugstr_w(file));
1206         return FILE_COMPRESSION_NONE;
1207     }
1208     if (!ReadFile( handle, buffer, sizeof(buffer), &size, NULL ) || size != sizeof(buffer))
1209     {
1210         CloseHandle( handle );
1211         return FILE_COMPRESSION_NONE;
1212     }
1213     if (!memcmp( buffer, LZ_MAGIC, sizeof(LZ_MAGIC) )) type = FILE_COMPRESSION_WINLZA;
1214     else if (!memcmp( buffer, MSZIP_MAGIC, sizeof(MSZIP_MAGIC) )) type = FILE_COMPRESSION_MSZIP;
1215     else if (!memcmp( buffer, NTCAB_MAGIC, sizeof(NTCAB_MAGIC) )) type = FILE_COMPRESSION_MSZIP; /* not a typo */
1216
1217     CloseHandle( handle );
1218     return type;
1219 }
1220
1221 static BOOL get_file_size( LPCWSTR file, DWORD *size )
1222 {
1223     HANDLE handle;
1224
1225     handle = CreateFileW( file, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL );
1226     if (handle == INVALID_HANDLE_VALUE)
1227     {
1228         ERR("cannot open file %s\n", debugstr_w(file));
1229         return FALSE;
1230     }
1231     *size = GetFileSize( handle, NULL );
1232     CloseHandle( handle );
1233     return TRUE;
1234 }
1235
1236 static BOOL get_file_sizes_none( LPCWSTR source, DWORD *source_size, DWORD *target_size )
1237 {
1238     DWORD size;
1239
1240     if (!get_file_size( source, &size )) return FALSE;
1241     if (source_size) *source_size = size;
1242     if (target_size) *target_size = size;
1243     return TRUE;
1244 }
1245
1246 static BOOL get_file_sizes_lz( LPCWSTR source, DWORD *source_size, DWORD *target_size )
1247 {
1248     DWORD size;
1249     BOOL ret = TRUE;
1250
1251     if (source_size)
1252     {
1253         if (!get_file_size( source, &size )) ret = FALSE;
1254         else *source_size = size;
1255     }
1256     if (target_size)
1257     {
1258         INT file;
1259         OFSTRUCT of;
1260
1261         if ((file = LZOpenFileW( (LPWSTR)source, &of, OF_READ )) < 0)
1262         {
1263             ERR("cannot open source file for reading\n");
1264             return FALSE;
1265         }
1266         *target_size = LZSeek( file, 0, 2 );
1267         LZClose( file );
1268     }
1269     return ret;
1270 }
1271
1272 static UINT CALLBACK file_compression_info_callback( PVOID context, UINT notification, UINT_PTR param1, UINT_PTR param2 )
1273 {
1274     DWORD *size = context;
1275     FILE_IN_CABINET_INFO_W *info = (FILE_IN_CABINET_INFO_W *)param1;
1276
1277     switch (notification)
1278     {
1279     case SPFILENOTIFY_FILEINCABINET:
1280     {
1281         *size = info->FileSize;
1282         return FILEOP_SKIP;
1283     }
1284     default: return NO_ERROR;
1285     }
1286 }
1287
1288 static BOOL get_file_sizes_cab( LPCWSTR source, DWORD *source_size, DWORD *target_size )
1289 {
1290     DWORD size;
1291     BOOL ret = TRUE;
1292
1293     if (source_size)
1294     {
1295         if (!get_file_size( source, &size )) ret = FALSE;
1296         else *source_size = size;
1297     }
1298     if (target_size)
1299     {
1300         ret = SetupIterateCabinetW( source, 0, file_compression_info_callback, target_size );
1301     }
1302     return ret;
1303 }
1304
1305 /***********************************************************************
1306  *      SetupGetFileCompressionInfoExA  (SETUPAPI.@)
1307  *
1308  * See SetupGetFileCompressionInfoExW.
1309  */
1310 BOOL WINAPI SetupGetFileCompressionInfoExA( PCSTR source, PSTR name, DWORD len, PDWORD required,
1311                                             PDWORD source_size, PDWORD target_size, PUINT type )
1312 {
1313     BOOL ret;
1314     WCHAR *nameW = NULL, *sourceW = NULL;
1315     DWORD nb_chars = 0;
1316     LPSTR nameA;
1317
1318     TRACE("%s, %p, %d, %p, %p, %p, %p\n", debugstr_a(source), name, len, required,
1319           source_size, target_size, type);
1320
1321     if (!source || !(sourceW = MultiByteToUnicode( source, CP_ACP ))) return FALSE;
1322
1323     if (name)
1324     {
1325         ret = SetupGetFileCompressionInfoExW( sourceW, NULL, 0, &nb_chars, NULL, NULL, NULL );
1326         if (!(nameW = HeapAlloc( GetProcessHeap(), 0, nb_chars * sizeof(WCHAR) )))
1327         {
1328             MyFree( sourceW );
1329             return FALSE;
1330         }
1331     }
1332     ret = SetupGetFileCompressionInfoExW( sourceW, nameW, nb_chars, &nb_chars, source_size, target_size, type );
1333     if (ret)
1334     {
1335         if ((nameA = UnicodeToMultiByte( nameW, CP_ACP )))
1336         {
1337             if (name && len >= nb_chars) lstrcpyA( name, nameA );
1338             else
1339             {
1340                 SetLastError( ERROR_INSUFFICIENT_BUFFER );
1341                 ret = FALSE;
1342             }
1343             MyFree( nameA );
1344         }
1345     }
1346     if (required) *required = nb_chars;
1347     HeapFree( GetProcessHeap(), 0, nameW );
1348     MyFree( sourceW );
1349
1350     return ret;
1351 }
1352
1353 /***********************************************************************
1354  *      SetupGetFileCompressionInfoExW  (SETUPAPI.@)
1355  *
1356  * Get compression type and compressed/uncompressed sizes of a given file.
1357  *
1358  * PARAMS
1359  *  source      [I] File to examine.
1360  *  name        [O] Actual filename used.
1361  *  len         [I] Length in characters of 'name' buffer.
1362  *  required    [O] Number of characters written to 'name'.
1363  *  source_size [O] Size of compressed file.
1364  *  target_size [O] Size of uncompressed file.
1365  *  type        [O] Compression type.
1366  *
1367  * RETURNS
1368  *  Success: TRUE
1369  *  Failure: FALSE
1370  */
1371 BOOL WINAPI SetupGetFileCompressionInfoExW( PCWSTR source, PWSTR name, DWORD len, PDWORD required,
1372                                             PDWORD source_size, PDWORD target_size, PUINT type )
1373 {
1374     UINT comp;
1375     BOOL ret = FALSE;
1376     DWORD source_len;
1377
1378     TRACE("%s, %p, %d, %p, %p, %p, %p\n", debugstr_w(source), name, len, required,
1379           source_size, target_size, type);
1380
1381     if (!source) return FALSE;
1382
1383     source_len = lstrlenW( source ) + 1;
1384     if (required) *required = source_len;
1385     if (name && len >= source_len)
1386     {
1387         lstrcpyW( name, source );
1388         ret = TRUE;
1389     }
1390     else return FALSE;
1391
1392     comp = detect_compression_type( source );
1393     if (type) *type = comp;
1394
1395     switch (comp)
1396     {
1397     case FILE_COMPRESSION_MSZIP:
1398     case FILE_COMPRESSION_NTCAB:  ret = get_file_sizes_cab( source, source_size, target_size ); break;
1399     case FILE_COMPRESSION_NONE:   ret = get_file_sizes_none( source, source_size, target_size ); break;
1400     case FILE_COMPRESSION_WINLZA: ret = get_file_sizes_lz( source, source_size, target_size ); break;
1401     default: break;
1402     }
1403     return ret;
1404 }
1405
1406 /***********************************************************************
1407  *      SetupGetFileCompressionInfoA  (SETUPAPI.@)
1408  *
1409  * See SetupGetFileCompressionInfoW.
1410  */
1411 DWORD WINAPI SetupGetFileCompressionInfoA( PCSTR source, PSTR *name, PDWORD source_size,
1412                                            PDWORD target_size, PUINT type )
1413 {
1414     BOOL ret;
1415     DWORD error, required;
1416     LPSTR actual_name;
1417
1418     TRACE("%s, %p, %p, %p, %p\n", debugstr_a(source), name, source_size, target_size, type);
1419
1420     if (!source || !name || !source_size || !target_size || !type)
1421         return ERROR_INVALID_PARAMETER;
1422
1423     ret = SetupGetFileCompressionInfoExA( source, NULL, 0, &required, NULL, NULL, NULL );
1424     if (!(actual_name = MyMalloc( required ))) return ERROR_NOT_ENOUGH_MEMORY;
1425
1426     ret = SetupGetFileCompressionInfoExA( source, actual_name, required, &required,
1427                                           source_size, target_size, type );
1428     if (!ret)
1429     {
1430         error = GetLastError();
1431         MyFree( actual_name );
1432         return error;
1433     }
1434     *name = actual_name;
1435     return ERROR_SUCCESS;
1436 }
1437
1438 /***********************************************************************
1439  *      SetupGetFileCompressionInfoW  (SETUPAPI.@)
1440  *
1441  * Get compression type and compressed/uncompressed sizes of a given file.
1442  *
1443  * PARAMS
1444  *  source      [I] File to examine.
1445  *  name        [O] Actual filename used.
1446  *  source_size [O] Size of compressed file.
1447  *  target_size [O] Size of uncompressed file.
1448  *  type        [O] Compression type.
1449  *
1450  * RETURNS
1451  *  Success: ERROR_SUCCESS
1452  *  Failure: Win32 error code.
1453  */
1454 DWORD WINAPI SetupGetFileCompressionInfoW( PCWSTR source, PWSTR *name, PDWORD source_size,
1455                                            PDWORD target_size, PUINT type )
1456 {
1457     BOOL ret;
1458     DWORD error, required;
1459     LPWSTR actual_name;
1460
1461     TRACE("%s, %p, %p, %p, %p\n", debugstr_w(source), name, source_size, target_size, type);
1462
1463     if (!source || !name || !source_size || !target_size || !type)
1464         return ERROR_INVALID_PARAMETER;
1465
1466     ret = SetupGetFileCompressionInfoExW( source, NULL, 0, &required, NULL, NULL, NULL );
1467     if (!(actual_name = MyMalloc( required ))) return ERROR_NOT_ENOUGH_MEMORY;
1468
1469     ret = SetupGetFileCompressionInfoExW( source, actual_name, required, &required,
1470                                           source_size, target_size, type );
1471     if (!ret)
1472     {
1473         error = GetLastError();
1474         MyFree( actual_name );
1475         return error;
1476     }
1477     *name = actual_name;
1478     return ERROR_SUCCESS;
1479 }
1480
1481 static DWORD decompress_file_lz( LPCWSTR source, LPCWSTR target )
1482 {
1483     DWORD ret;
1484     LONG error;
1485     INT src, dst;
1486     OFSTRUCT sof, dof;
1487
1488     if ((src = LZOpenFileW( (LPWSTR)source, &sof, OF_READ )) < 0)
1489     {
1490         ERR("cannot open source file for reading\n");
1491         return ERROR_FILE_NOT_FOUND;
1492     }
1493     if ((dst = LZOpenFileW( (LPWSTR)target, &dof, OF_CREATE )) < 0)
1494     {
1495         ERR("cannot open target file for writing\n");
1496         LZClose( src );
1497         return ERROR_FILE_NOT_FOUND;
1498     }
1499     if ((error = LZCopy( src, dst )) >= 0) ret = ERROR_SUCCESS;
1500     else
1501     {
1502         WARN("failed to decompress file %d\n", error);
1503         ret = ERROR_INVALID_DATA;
1504     }
1505
1506     LZClose( src );
1507     LZClose( dst );
1508     return ret;
1509 }
1510
1511 static UINT CALLBACK decompress_or_copy_callback( PVOID context, UINT notification, UINT_PTR param1, UINT_PTR param2 )
1512 {
1513     FILE_IN_CABINET_INFO_W *info = (FILE_IN_CABINET_INFO_W *)param1;
1514
1515     switch (notification)
1516     {
1517     case SPFILENOTIFY_FILEINCABINET:
1518     {
1519         LPCWSTR filename, targetname = context;
1520         WCHAR *p;
1521
1522         if ((p = strrchrW( targetname, '\\' ))) filename = p + 1;
1523         else filename = targetname;
1524
1525         if (!lstrcmpiW( filename, info->NameInCabinet ))
1526         {
1527             strcpyW( info->FullTargetName, targetname );
1528             return FILEOP_DOIT;
1529         }
1530         return FILEOP_SKIP;
1531     }
1532     default: return NO_ERROR;
1533     }
1534 }
1535
1536 static DWORD decompress_file_cab( LPCWSTR source, LPCWSTR target )
1537 {
1538     BOOL ret;
1539
1540     ret = SetupIterateCabinetW( source, 0, decompress_or_copy_callback, (PVOID)target );
1541
1542     if (ret) return ERROR_SUCCESS;
1543     else return GetLastError();
1544 }
1545
1546 /***********************************************************************
1547  *      SetupDecompressOrCopyFileA  (SETUPAPI.@)
1548  *
1549  * See SetupDecompressOrCopyFileW.
1550  */
1551 DWORD WINAPI SetupDecompressOrCopyFileA( PCSTR source, PCSTR target, PUINT type )
1552 {
1553     DWORD ret = FALSE;
1554     WCHAR *sourceW = NULL, *targetW = NULL;
1555
1556     if (source && !(sourceW = MultiByteToUnicode( source, CP_ACP ))) return FALSE;
1557     if (target && !(targetW = MultiByteToUnicode( target, CP_ACP )))
1558     {
1559         MyFree( sourceW );
1560         return ERROR_NOT_ENOUGH_MEMORY;
1561     }
1562
1563     ret = SetupDecompressOrCopyFileW( sourceW, targetW, type );
1564
1565     MyFree( sourceW );
1566     MyFree( targetW );
1567
1568     return ret;
1569 }
1570
1571 /***********************************************************************
1572  *      SetupDecompressOrCopyFileW  (SETUPAPI.@)
1573  *
1574  * Copy a file and decompress it if needed.
1575  *
1576  * PARAMS
1577  *  source [I] File to copy.
1578  *  target [I] Filename of the copy.
1579  *  type   [I] Compression type.
1580  *
1581  * RETURNS
1582  *  Success: ERROR_SUCCESS
1583  *  Failure: Win32 error code.
1584  */
1585 DWORD WINAPI SetupDecompressOrCopyFileW( PCWSTR source, PCWSTR target, PUINT type )
1586 {
1587     UINT comp;
1588     DWORD ret = ERROR_INVALID_PARAMETER;
1589
1590     if (!source || !target) return ERROR_INVALID_PARAMETER;
1591
1592     if (!type) comp = detect_compression_type( source );
1593     else comp = *type;
1594
1595     switch (comp)
1596     {
1597     case FILE_COMPRESSION_NONE:
1598         if (CopyFileW( source, target, FALSE )) ret = ERROR_SUCCESS;
1599         else ret = GetLastError();
1600         break;
1601     case FILE_COMPRESSION_WINLZA:
1602         ret = decompress_file_lz( source, target );
1603         break;
1604     case FILE_COMPRESSION_NTCAB:
1605     case FILE_COMPRESSION_MSZIP:
1606         ret = decompress_file_cab( source, target );
1607         break;
1608     default:
1609         WARN("unknown compression type %d\n", comp);
1610         break;
1611     }
1612
1613     TRACE("%s -> %s %d\n", debugstr_w(source), debugstr_w(target), comp);
1614     return ret;
1615 }