xref: /reactos/dll/win32/advpack/files.c (revision 3fb5957d)
1 /*
2  * Advpack file functions
3  *
4  * Copyright 2006 James Hawkins
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 #include <stdlib.h>
23 
24 #include "windef.h"
25 #include "winbase.h"
26 #include "winuser.h"
27 #include "winreg.h"
28 #include "winnls.h"
29 #include "winver.h"
30 #include "winternl.h"
31 #include "setupapi.h"
32 #include "advpub.h"
33 #include "fdi.h"
34 #include "wine/debug.h"
35 #include "advpack_private.h"
36 
37 WINE_DEFAULT_DEBUG_CHANNEL(advpack);
38 
39 /* converts an ansi double null-terminated list to a unicode list */
40 static LPWSTR ansi_to_unicode_list(LPCSTR ansi_list)
41 {
42     DWORD len, wlen = 0;
43     LPWSTR list;
44     LPCSTR ptr = ansi_list;
45 
46     while (*ptr) ptr += lstrlenA(ptr) + 1;
47     len = ptr + 1 - ansi_list;
48     wlen = MultiByteToWideChar(CP_ACP, 0, ansi_list, len, NULL, 0);
49     list = HeapAlloc(GetProcessHeap(), 0, wlen * sizeof(WCHAR));
50     MultiByteToWideChar(CP_ACP, 0, ansi_list, len, list, wlen);
51     return list;
52 }
53 
54 /***********************************************************************
55  *      AddDelBackupEntryA (ADVPACK.@)
56  *
57  * See AddDelBackupEntryW.
58  */
59 HRESULT WINAPI AddDelBackupEntryA(LPCSTR lpcszFileList, LPCSTR lpcszBackupDir,
60                                   LPCSTR lpcszBaseName, DWORD dwFlags)
61 {
62     UNICODE_STRING backupdir, basename;
63     LPWSTR filelist;
64     LPCWSTR backup;
65     HRESULT res;
66 
67     TRACE("(%s, %s, %s, %d)\n", debugstr_a(lpcszFileList),
68           debugstr_a(lpcszBackupDir), debugstr_a(lpcszBaseName), dwFlags);
69 
70     if (lpcszFileList)
71         filelist = ansi_to_unicode_list(lpcszFileList);
72     else
73         filelist = NULL;
74 
75     RtlCreateUnicodeStringFromAsciiz(&backupdir, lpcszBackupDir);
76     RtlCreateUnicodeStringFromAsciiz(&basename, lpcszBaseName);
77 
78     if (lpcszBackupDir)
79         backup = backupdir.Buffer;
80     else
81         backup = NULL;
82 
83     res = AddDelBackupEntryW(filelist, backup, basename.Buffer, dwFlags);
84 
85     HeapFree(GetProcessHeap(), 0, filelist);
86 
87     RtlFreeUnicodeString(&backupdir);
88     RtlFreeUnicodeString(&basename);
89 
90     return res;
91 }
92 
93 /***********************************************************************
94  *      AddDelBackupEntryW (ADVPACK.@)
95  *
96  * Either appends the files in the file list to the backup section of
97  * the specified INI, or deletes the entries from the INI file.
98  *
99  * PARAMS
100  *   lpcszFileList  [I] NULL-separated list of filenames.
101  *   lpcszBackupDir [I] Path of the backup directory.
102  *   lpcszBaseName  [I] Basename of the INI file.
103  *   dwFlags        [I] AADBE_ADD_ENTRY adds the entries in the file list
104  *                      to the INI file, while AADBE_DEL_ENTRY removes
105  *                      the entries from the INI file.
106  *
107  * RETURNS
108  *   S_OK in all cases.
109  *
110  * NOTES
111  *   If the INI file does not exist before adding entries to it, the file
112  *   will be created.
113  *
114  *   If lpcszBackupDir is NULL, the INI file is assumed to exist in
115  *   c:\windows or created there if it does not exist.
116  */
117 HRESULT WINAPI AddDelBackupEntryW(LPCWSTR lpcszFileList, LPCWSTR lpcszBackupDir,
118                                   LPCWSTR lpcszBaseName, DWORD dwFlags)
119 {
120     WCHAR szIniPath[MAX_PATH];
121     LPCWSTR szString = NULL;
122 
123     static const WCHAR szBackupEntry[] = {
124         '-','1',',','0',',','0',',','0',',','0',',','0',',','-','1',0
125     };
126 
127     static const WCHAR backslash[] = {'\\',0};
128     static const WCHAR ini[] = {'.','i','n','i',0};
129     static const WCHAR backup[] = {'b','a','c','k','u','p',0};
130 
131     TRACE("(%s, %s, %s, %d)\n", debugstr_w(lpcszFileList),
132           debugstr_w(lpcszBackupDir), debugstr_w(lpcszBaseName), dwFlags);
133 
134     if (!lpcszFileList || !*lpcszFileList)
135         return S_OK;
136 
137     if (lpcszBackupDir)
138         lstrcpyW(szIniPath, lpcszBackupDir);
139     else
140         GetWindowsDirectoryW(szIniPath, MAX_PATH);
141 
142     lstrcatW(szIniPath, backslash);
143     lstrcatW(szIniPath, lpcszBaseName);
144     lstrcatW(szIniPath, ini);
145 
146     SetFileAttributesW(szIniPath, FILE_ATTRIBUTE_NORMAL);
147 
148     if (dwFlags & AADBE_ADD_ENTRY)
149         szString = szBackupEntry;
150     else if (dwFlags & AADBE_DEL_ENTRY)
151         szString = NULL;
152 
153     /* add or delete the INI entries */
154     while (*lpcszFileList)
155     {
156         WritePrivateProfileStringW(backup, lpcszFileList, szString, szIniPath);
157         lpcszFileList += lstrlenW(lpcszFileList) + 1;
158     }
159 
160     /* hide the INI file */
161     SetFileAttributesW(szIniPath, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN);
162 
163     return S_OK;
164 }
165 
166 /* FIXME: this is only for the local case, X:\ */
167 #define ROOT_LENGTH 3
168 
169 static UINT CALLBACK pQuietQueueCallback(PVOID Context, UINT Notification,
170                                          UINT_PTR Param1, UINT_PTR Param2)
171 {
172     return 1;
173 }
174 
175 static UINT CALLBACK pQueueCallback(PVOID Context, UINT Notification,
176                                     UINT_PTR Param1, UINT_PTR Param2)
177 {
178     /* only be verbose for error notifications */
179     if (!Notification ||
180         Notification == SPFILENOTIFY_RENAMEERROR ||
181         Notification == SPFILENOTIFY_DELETEERROR ||
182         Notification == SPFILENOTIFY_COPYERROR)
183     {
184         return SetupDefaultQueueCallbackW(Context, Notification,
185                                           Param1, Param2);
186     }
187 
188     return 1;
189 }
190 
191 /***********************************************************************
192  *      AdvInstallFileA (ADVPACK.@)
193  *
194  * See AdvInstallFileW.
195  */
196 HRESULT WINAPI AdvInstallFileA(HWND hwnd, LPCSTR lpszSourceDir, LPCSTR lpszSourceFile,
197                                LPCSTR lpszDestDir, LPCSTR lpszDestFile,
198                                DWORD dwFlags, DWORD dwReserved)
199 {
200     UNICODE_STRING sourcedir, sourcefile;
201     UNICODE_STRING destdir, destfile;
202     HRESULT res;
203 
204     TRACE("(%p, %s, %s, %s, %s, %d, %d)\n", hwnd, debugstr_a(lpszSourceDir),
205           debugstr_a(lpszSourceFile), debugstr_a(lpszDestDir),
206           debugstr_a(lpszDestFile), dwFlags, dwReserved);
207 
208     if (!lpszSourceDir || !lpszSourceFile || !lpszDestDir)
209         return E_INVALIDARG;
210 
211     RtlCreateUnicodeStringFromAsciiz(&sourcedir, lpszSourceDir);
212     RtlCreateUnicodeStringFromAsciiz(&sourcefile, lpszSourceFile);
213     RtlCreateUnicodeStringFromAsciiz(&destdir, lpszDestDir);
214     RtlCreateUnicodeStringFromAsciiz(&destfile, lpszDestFile);
215 
216     res = AdvInstallFileW(hwnd, sourcedir.Buffer, sourcefile.Buffer,
217                           destdir.Buffer, destfile.Buffer, dwFlags, dwReserved);
218 
219     RtlFreeUnicodeString(&sourcedir);
220     RtlFreeUnicodeString(&sourcefile);
221     RtlFreeUnicodeString(&destdir);
222     RtlFreeUnicodeString(&destfile);
223 
224     return res;
225 }
226 
227 /***********************************************************************
228  *      AdvInstallFileW (ADVPACK.@)
229  *
230  * Copies a file from the source to a destination.
231  *
232  * PARAMS
233  *   hwnd           [I] Handle to the window used for messages.
234  *   lpszSourceDir  [I] Source directory.
235  *   lpszSourceFile [I] Source filename.
236  *   lpszDestDir    [I] Destination directory.
237  *   lpszDestFile   [I] Optional destination filename.
238  *   dwFlags        [I] See advpub.h.
239  *   dwReserved     [I] Reserved.  Must be 0.
240  *
241  * RETURNS
242  *   Success: S_OK.
243  *   Failure: E_FAIL.
244  *
245  * NOTES
246  *   If lpszDestFile is NULL, the destination filename is the same as
247  *   lpszSourceFIle.
248  */
249 HRESULT WINAPI AdvInstallFileW(HWND hwnd, LPCWSTR lpszSourceDir, LPCWSTR lpszSourceFile,
250                                LPCWSTR lpszDestDir, LPCWSTR lpszDestFile,
251                                DWORD dwFlags, DWORD dwReserved)
252 {
253     PSP_FILE_CALLBACK_W pFileCallback;
254     LPWSTR szDestFilename;
255     LPCWSTR szPath;
256     WCHAR szRootPath[ROOT_LENGTH];
257     DWORD dwLen, dwLastError;
258     HSPFILEQ fileQueue;
259     PVOID pContext;
260 
261     TRACE("(%p, %s, %s, %s, %s, %d, %d)\n", hwnd, debugstr_w(lpszSourceDir),
262           debugstr_w(lpszSourceFile), debugstr_w(lpszDestDir),
263           debugstr_w(lpszDestFile), dwFlags, dwReserved);
264 
265     if (!lpszSourceDir || !lpszSourceFile || !lpszDestDir)
266         return E_INVALIDARG;
267 
268     fileQueue = SetupOpenFileQueue();
269     if (fileQueue == INVALID_HANDLE_VALUE)
270         return HRESULT_FROM_WIN32(GetLastError());
271 
272     pContext = NULL;
273     dwLastError = ERROR_SUCCESS;
274 
275     lstrcpynW(szRootPath, lpszSourceDir, ROOT_LENGTH);
276     szPath = lpszSourceDir + ROOT_LENGTH;
277 
278     /* use lpszSourceFile as destination filename if lpszDestFile is NULL */
279     if (lpszDestFile)
280     {
281         dwLen = lstrlenW(lpszDestFile);
282         szDestFilename = HeapAlloc(GetProcessHeap(), 0, (dwLen+1) * sizeof(WCHAR));
283         lstrcpyW(szDestFilename, lpszDestFile);
284     }
285     else
286     {
287         dwLen = lstrlenW(lpszSourceFile);
288         szDestFilename = HeapAlloc(GetProcessHeap(), 0, (dwLen+1) * sizeof(WCHAR));
289         lstrcpyW(szDestFilename, lpszSourceFile);
290     }
291 
292     /* add the file copy operation to the setup queue */
293     if (!SetupQueueCopyW(fileQueue, szRootPath, szPath, lpszSourceFile, NULL,
294                          NULL, lpszDestDir, szDestFilename, dwFlags))
295     {
296         dwLastError = GetLastError();
297         goto done;
298     }
299 
300     pContext = SetupInitDefaultQueueCallbackEx(hwnd, INVALID_HANDLE_VALUE,
301                                                0, 0, NULL);
302     if (!pContext)
303     {
304         dwLastError = GetLastError();
305         goto done;
306     }
307 
308     /* don't output anything for AIF_QUIET */
309     if (dwFlags & AIF_QUIET)
310         pFileCallback = pQuietQueueCallback;
311     else
312         pFileCallback = pQueueCallback;
313 
314     /* perform the file copy */
315     if (!SetupCommitFileQueueW(hwnd, fileQueue, pFileCallback, pContext))
316     {
317         dwLastError = GetLastError();
318         goto done;
319     }
320 
321 done:
322     SetupTermDefaultQueueCallback(pContext);
323     SetupCloseFileQueue(fileQueue);
324 
325     HeapFree(GetProcessHeap(), 0, szDestFilename);
326 
327     return HRESULT_FROM_WIN32(dwLastError);
328 }
329 
330 static HRESULT DELNODE_recurse_dirtree(LPWSTR fname, DWORD flags)
331 {
332     DWORD fattrs = GetFileAttributesW(fname);
333     HRESULT ret = E_FAIL;
334 
335     static const WCHAR asterisk[] = {'*',0};
336     static const WCHAR dot[] = {'.',0};
337     static const WCHAR dotdot[] = {'.','.',0};
338 
339     if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
340     {
341         HANDLE hFindFile;
342         WIN32_FIND_DATAW w32fd;
343         BOOL done = TRUE;
344         int fname_len;
345 
346 #ifdef __REACTOS__
347         if (flags & ADN_DEL_IF_EMPTY)
348         {
349             goto deleteinitialdirectory;
350         }
351 #endif
352 
353         /* Generate a path with wildcard suitable for iterating */
354         fname_len = lstrlenW(fname);
355         if (fname_len && fname[fname_len-1] != '\\') fname[fname_len++] = '\\';
356         lstrcpyW(fname + fname_len, asterisk);
357 
358         if ((hFindFile = FindFirstFileW(fname, &w32fd)) != INVALID_HANDLE_VALUE)
359         {
360             /* Iterate through the files in the directory */
361             for (done = FALSE; !done; done = !FindNextFileW(hFindFile, &w32fd))
362             {
363                 TRACE("%s\n", debugstr_w(w32fd.cFileName));
364                 if (lstrcmpW(dot, w32fd.cFileName) != 0 &&
365                     lstrcmpW(dotdot, w32fd.cFileName) != 0)
366                 {
367                     lstrcpyW(fname + fname_len, w32fd.cFileName);
368                     if (DELNODE_recurse_dirtree(fname, flags) != S_OK)
369                     {
370                         break; /* Failure */
371                     }
372                 }
373             }
374             FindClose(hFindFile);
375         }
376 
377         /* We're done with this directory, so restore the old path without wildcard */
378         *(fname + fname_len) = '\0';
379 
380         if (done)
381         {
382 #ifdef __REACTOS__
383 deleteinitialdirectory:
384             TRACE("%s: directory\n", debugstr_w(fname));
385             SetFileAttributesW(fname, FILE_ATTRIBUTE_NORMAL);
386             if (RemoveDirectoryW(fname))
387 #else
388             if (SetFileAttributesW(fname, FILE_ATTRIBUTE_NORMAL) && RemoveDirectoryW(fname))
389 #endif
390             {
391                 ret = S_OK;
392             }
393         }
394     }
395     else
396     {
397         TRACE("%s: file\n", debugstr_w(fname));
398 #ifdef __REACTOS__
399         SetFileAttributesW(fname, FILE_ATTRIBUTE_NORMAL);
400         if (DeleteFileW(fname))
401 #else
402         if (SetFileAttributesW(fname, FILE_ATTRIBUTE_NORMAL) && DeleteFileW(fname))
403 #endif
404         {
405             ret = S_OK;
406         }
407     }
408 
409     return ret;
410 }
411 
412 /***********************************************************************
413  *              DelNodeA   (ADVPACK.@)
414  *
415  * See DelNodeW.
416  */
417 HRESULT WINAPI DelNodeA(LPCSTR pszFileOrDirName, DWORD dwFlags)
418 {
419     UNICODE_STRING fileordirname;
420     HRESULT res;
421 
422     TRACE("(%s, %d)\n", debugstr_a(pszFileOrDirName), dwFlags);
423 
424     RtlCreateUnicodeStringFromAsciiz(&fileordirname, pszFileOrDirName);
425 
426     res = DelNodeW(fileordirname.Buffer, dwFlags);
427 
428     RtlFreeUnicodeString(&fileordirname);
429 
430     return res;
431 }
432 
433 /***********************************************************************
434  *              DelNodeW   (ADVPACK.@)
435  *
436  * Deletes a file or directory
437  *
438  * PARAMS
439  *   pszFileOrDirName   [I] Name of file or directory to delete
440  *   dwFlags            [I] Flags; see include/advpub.h
441  *
442  * RETURNS
443  *   Success: S_OK
444  *   Failure: E_FAIL
445  *
446  * BUGS
447  *   - Ignores flags
448  *   - Native version apparently does a lot of checking to make sure
449  *     we're not trying to delete a system directory etc.
450  */
451 HRESULT WINAPI DelNodeW(LPCWSTR pszFileOrDirName, DWORD dwFlags)
452 {
453     WCHAR fname[MAX_PATH];
454     HRESULT ret = E_FAIL;
455 
456     TRACE("(%s, %d)\n", debugstr_w(pszFileOrDirName), dwFlags);
457 
458 #ifdef __REACTOS__
459     if (dwFlags & ~ADN_DEL_IF_EMPTY)
460         FIXME("Flags %#x ignored!\n", dwFlags & ~ADN_DEL_IF_EMPTY);
461 #else
462     if (dwFlags)
463         FIXME("Flags ignored!\n");
464 #endif
465 
466     if (pszFileOrDirName && *pszFileOrDirName)
467     {
468         lstrcpyW(fname, pszFileOrDirName);
469 
470         /* TODO: Should check for system directory deletion etc. here */
471 
472         ret = DELNODE_recurse_dirtree(fname, dwFlags);
473     }
474 
475     return ret;
476 }
477 
478 /***********************************************************************
479  *             DelNodeRunDLL32A   (ADVPACK.@)
480  *
481  * See DelNodeRunDLL32W.
482  */
483 HRESULT WINAPI DelNodeRunDLL32A(HWND hWnd, HINSTANCE hInst, LPSTR cmdline, INT show)
484 {
485     UNICODE_STRING params;
486     HRESULT hr;
487 
488     TRACE("(%p, %p, %s, %i)\n", hWnd, hInst, debugstr_a(cmdline), show);
489 
490     RtlCreateUnicodeStringFromAsciiz(&params, cmdline);
491 
492     hr = DelNodeRunDLL32W(hWnd, hInst, params.Buffer, show);
493 
494     RtlFreeUnicodeString(&params);
495 
496     return hr;
497 }
498 
499 /***********************************************************************
500  *             DelNodeRunDLL32W   (ADVPACK.@)
501  *
502  * Deletes a file or directory, WinMain style.
503  *
504  * PARAMS
505  *   hWnd    [I] Handle to the window used for the display.
506  *   hInst   [I] Instance of the process.
507  *   cmdline [I] Contains parameters in the order FileOrDirName,Flags.
508  *   show    [I] How the window should be shown.
509  *
510  * RETURNS
511  *   Success: S_OK.
512  *   Failure: E_FAIL.
513  */
514 HRESULT WINAPI DelNodeRunDLL32W(HWND hWnd, HINSTANCE hInst, LPWSTR cmdline, INT show)
515 {
516     LPWSTR szFilename, szFlags;
517     LPWSTR cmdline_copy, cmdline_ptr;
518     DWORD dwFlags = 0;
519     HRESULT res;
520 
521     TRACE("(%p, %p, %s, %i)\n", hWnd, hInst, debugstr_w(cmdline), show);
522 
523     cmdline_copy = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(cmdline) + 1) * sizeof(WCHAR));
524     cmdline_ptr = cmdline_copy;
525     lstrcpyW(cmdline_copy, cmdline);
526 
527     /* get the parameters at indexes 0 and 1 respectively */
528     szFilename = get_parameter(&cmdline_ptr, ',', TRUE);
529     szFlags = get_parameter(&cmdline_ptr, ',', TRUE);
530 
531     if (szFlags)
532         dwFlags = wcstol(szFlags, NULL, 10);
533 
534     res = DelNodeW(szFilename, dwFlags);
535 
536     HeapFree(GetProcessHeap(), 0, cmdline_copy);
537 
538     return res;
539 }
540 
541 /* The following definitions were copied from dlls/cabinet/cabinet.h */
542 
543 /* SESSION Operation */
544 #define EXTRACT_FILLFILELIST  0x00000001
545 #define EXTRACT_EXTRACTFILES  0x00000002
546 
547 struct FILELIST{
548     LPSTR FileName;
549     struct FILELIST *next;
550     BOOL DoExtract;
551 };
552 
553 typedef struct {
554     INT FileSize;
555     ERF Error;
556     struct FILELIST *FileList;
557     INT FileCount;
558     INT Operation;
559     CHAR Destination[MAX_PATH];
560     CHAR CurrentFile[MAX_PATH];
561     CHAR Reserved[MAX_PATH];
562     struct FILELIST *FilterList;
563 } SESSION;
564 
565 static HRESULT (WINAPI *pExtract)(SESSION*, LPCSTR);
566 
567 /* removes legal characters before and after file list, and
568  * converts the file list to a NULL-separated list
569  */
570 static LPSTR convert_file_list(LPCSTR FileList, DWORD *dwNumFiles)
571 {
572     DWORD dwLen;
573     const char *first = FileList;
574     const char *last = FileList + strlen(FileList) - 1;
575     LPSTR szConvertedList, temp;
576 
577     /* any number of these chars before the list is OK */
578     while (first < last && (*first == ' ' || *first == '\t' || *first == ':'))
579         first++;
580 
581     /* any number of these chars after the list is OK */
582     while (last > first && (*last == ' ' || *last == '\t' || *last == ':'))
583         last--;
584 
585     if (first == last)
586         return NULL;
587 
588     dwLen = last - first + 3; /* room for double-null termination */
589     szConvertedList = HeapAlloc(GetProcessHeap(), 0, dwLen);
590     lstrcpynA(szConvertedList, first, dwLen - 1);
591     szConvertedList[dwLen - 1] = '\0';
592 
593     /* empty list */
594     if (!szConvertedList[0])
595     {
596         HeapFree(GetProcessHeap(), 0, szConvertedList);
597         return NULL;
598     }
599 
600     *dwNumFiles = 1;
601 
602     /* convert the colons to double-null termination */
603     temp = szConvertedList;
604     while (*temp)
605     {
606         if (*temp == ':')
607         {
608             *temp = '\0';
609             (*dwNumFiles)++;
610         }
611 
612         temp++;
613     }
614 
615     return szConvertedList;
616 }
617 
618 static void free_file_node(struct FILELIST *pNode)
619 {
620     HeapFree(GetProcessHeap(), 0, pNode->FileName);
621     HeapFree(GetProcessHeap(), 0, pNode);
622 }
623 
624 /* determines whether szFile is in the NULL-separated szFileList */
625 static BOOL file_in_list(LPCSTR szFile, LPCSTR szFileList)
626 {
627     DWORD dwLen = lstrlenA(szFile);
628     DWORD dwTestLen;
629 
630     while (*szFileList)
631     {
632         dwTestLen = lstrlenA(szFileList);
633 
634         if (dwTestLen == dwLen)
635         {
636             if (!lstrcmpiA(szFile, szFileList))
637                 return TRUE;
638         }
639 
640         szFileList += dwTestLen + 1;
641     }
642 
643     return FALSE;
644 }
645 
646 
647 /* returns the number of files that are in both the linked list and szFileList */
648 static DWORD fill_file_list(SESSION *session, LPCSTR szCabName, LPCSTR szFileList)
649 {
650     DWORD dwNumFound = 0;
651     struct FILELIST *pNode;
652 
653     session->Operation |= EXTRACT_FILLFILELIST;
654     if (pExtract(session, szCabName) != S_OK)
655     {
656         session->Operation &= ~EXTRACT_FILLFILELIST;
657         return -1;
658     }
659 
660     pNode = session->FileList;
661     while (pNode)
662     {
663         if (!file_in_list(pNode->FileName, szFileList))
664             pNode->DoExtract = FALSE;
665         else
666             dwNumFound++;
667 
668         pNode = pNode->next;
669     }
670 
671     session->Operation &= ~EXTRACT_FILLFILELIST;
672     return dwNumFound;
673 }
674 
675 static void free_file_list(SESSION* session)
676 {
677     struct FILELIST *next, *curr = session->FileList;
678 
679     while (curr)
680     {
681         next = curr->next;
682         free_file_node(curr);
683         curr = next;
684     }
685 }
686 
687 /***********************************************************************
688  *             ExtractFilesA    (ADVPACK.@)
689  *
690  * Extracts the specified files from a cab archive into
691  * a destination directory.
692  *
693  * PARAMS
694  *   CabName   [I] Filename of the cab archive.
695  *   ExpandDir [I] Destination directory for the extracted files.
696  *   Flags     [I] Reserved.
697  *   FileList  [I] Optional list of files to extract.  See NOTES.
698  *   LReserved [I] Reserved.  Must be NULL.
699  *   Reserved  [I] Reserved.  Must be 0.
700  *
701  * RETURNS
702  *   Success: S_OK.
703  *   Failure: E_FAIL.
704  *
705  * NOTES
706  *   FileList is a colon-separated list of filenames.  If FileList is
707  *   non-NULL, only the files in the list will be extracted from the
708  *   cab file, otherwise all files will be extracted.  Any number of
709  *   spaces, tabs, or colons can be before or after the list, but
710  *   the list itself must only be separated by colons.
711  */
712 HRESULT WINAPI ExtractFilesA(LPCSTR CabName, LPCSTR ExpandDir, DWORD Flags,
713                              LPCSTR FileList, LPVOID LReserved, DWORD Reserved)
714 {
715     SESSION session;
716     HMODULE hCabinet;
717     HRESULT res = S_OK;
718     DWORD dwFileCount = 0;
719     DWORD dwFilesFound = 0;
720     LPSTR szConvertedList = NULL;
721 
722     TRACE("(%s, %s, %d, %s, %p, %d)\n", debugstr_a(CabName), debugstr_a(ExpandDir),
723           Flags, debugstr_a(FileList), LReserved, Reserved);
724 
725     if (!CabName || !ExpandDir)
726         return E_INVALIDARG;
727 
728     if (GetFileAttributesA(ExpandDir) == INVALID_FILE_ATTRIBUTES)
729         return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
730 
731     hCabinet = LoadLibraryA("cabinet.dll");
732     if (!hCabinet)
733         return E_FAIL;
734 
735     ZeroMemory(&session, sizeof(SESSION));
736 
737     pExtract = (void *)GetProcAddress(hCabinet, "Extract");
738     if (!pExtract)
739     {
740         res = E_FAIL;
741         goto done;
742     }
743 
744     lstrcpyA(session.Destination, ExpandDir);
745 
746     if (FileList)
747     {
748         szConvertedList = convert_file_list(FileList, &dwFileCount);
749         if (!szConvertedList)
750         {
751             res = E_FAIL;
752             goto done;
753         }
754 
755         dwFilesFound = fill_file_list(&session, CabName, szConvertedList);
756         if (dwFilesFound != dwFileCount)
757         {
758             res = E_FAIL;
759             goto done;
760         }
761     }
762     else
763         session.Operation |= EXTRACT_FILLFILELIST;
764 
765     session.Operation |= EXTRACT_EXTRACTFILES;
766     res = pExtract(&session, CabName);
767 
768 done:
769     free_file_list(&session);
770     FreeLibrary(hCabinet);
771     HeapFree(GetProcessHeap(), 0, szConvertedList);
772 
773     return res;
774 }
775 
776 /***********************************************************************
777  *             ExtractFilesW    (ADVPACK.@)
778  *
779  * Extracts the specified files from a cab archive into
780  * a destination directory.
781  *
782  * PARAMS
783  *   CabName   [I] Filename of the cab archive.
784  *   ExpandDir [I] Destination directory for the extracted files.
785  *   Flags     [I] Reserved.
786  *   FileList  [I] Optional list of files to extract.  See NOTES.
787  *   LReserved [I] Reserved.  Must be NULL.
788  *   Reserved  [I] Reserved.  Must be 0.
789  *
790  * RETURNS
791  *   Success: S_OK.
792  *   Failure: E_FAIL.
793  *
794  * NOTES
795  *   FileList is a colon-separated list of filenames.  If FileList is
796  *   non-NULL, only the files in the list will be extracted from the
797  *   cab file, otherwise all files will be extracted.  Any number of
798  *   spaces, tabs, or colons can be before or after the list, but
799  *   the list itself must only be separated by colons.
800  *
801  * BUGS
802  *   Unimplemented.
803  */
804 HRESULT WINAPI ExtractFilesW(LPCWSTR CabName, LPCWSTR ExpandDir, DWORD Flags,
805                              LPCWSTR FileList, LPVOID LReserved, DWORD Reserved)
806 {
807     char *cab_name = NULL, *expand_dir = NULL, *file_list = NULL;
808     HRESULT hres = S_OK;
809 
810     TRACE("(%s, %s, %d, %s, %p, %d)\n", debugstr_w(CabName), debugstr_w(ExpandDir),
811           Flags, debugstr_w(FileList), LReserved, Reserved);
812 
813     if(CabName) {
814         cab_name = heap_strdupWtoA(CabName);
815         if(!cab_name)
816             return E_OUTOFMEMORY;
817     }
818 
819     if(ExpandDir) {
820         expand_dir = heap_strdupWtoA(ExpandDir);
821         if(!expand_dir)
822             hres = E_OUTOFMEMORY;
823     }
824 
825     if(SUCCEEDED(hres) && FileList) {
826         file_list = heap_strdupWtoA(FileList);
827         if(!file_list)
828             hres = E_OUTOFMEMORY;
829     }
830 
831     /* cabinet.dll, which does the real job of extracting files, doesn't have UNICODE API,
832        so we need W->A conversion at some point anyway. */
833     if(SUCCEEDED(hres))
834         hres = ExtractFilesA(cab_name, expand_dir, Flags, file_list, LReserved, Reserved);
835 
836     heap_free(cab_name);
837     heap_free(expand_dir);
838     heap_free(file_list);
839     return hres;
840 }
841 
842 /***********************************************************************
843  *      FileSaveMarkNotExistA (ADVPACK.@)
844  *
845  * See FileSaveMarkNotExistW.
846  */
847 HRESULT WINAPI FileSaveMarkNotExistA(LPSTR pszFileList, LPSTR pszDir, LPSTR pszBaseName)
848 {
849     TRACE("(%s, %s, %s)\n", debugstr_a(pszFileList),
850           debugstr_a(pszDir), debugstr_a(pszBaseName));
851 
852     return AddDelBackupEntryA(pszFileList, pszDir, pszBaseName, AADBE_DEL_ENTRY);
853 }
854 
855 /***********************************************************************
856  *      FileSaveMarkNotExistW (ADVPACK.@)
857  *
858  * Marks the files in the file list as not existing so they won't be
859  * backed up during a save.
860  *
861  * PARAMS
862  *   pszFileList [I] NULL-separated list of filenames.
863  *   pszDir      [I] Path of the backup directory.
864  *   pszBaseName [I] Basename of the INI file.
865  *
866  * RETURNS
867  *   Success: S_OK.
868  *   Failure: E_FAIL.
869  */
870 HRESULT WINAPI FileSaveMarkNotExistW(LPWSTR pszFileList, LPWSTR pszDir, LPWSTR pszBaseName)
871 {
872     TRACE("(%s, %s, %s)\n", debugstr_w(pszFileList),
873           debugstr_w(pszDir), debugstr_w(pszBaseName));
874 
875     return AddDelBackupEntryW(pszFileList, pszDir, pszBaseName, AADBE_DEL_ENTRY);
876 }
877 
878 /***********************************************************************
879  *      FileSaveRestoreA (ADVPACK.@)
880  *
881  * See FileSaveRestoreW.
882  */
883 HRESULT WINAPI FileSaveRestoreA(HWND hDlg, LPSTR pszFileList, LPSTR pszDir,
884                                 LPSTR pszBaseName, DWORD dwFlags)
885 {
886     UNICODE_STRING filelist, dir, basename;
887     HRESULT hr;
888 
889     TRACE("(%p, %s, %s, %s, %d)\n", hDlg, debugstr_a(pszFileList),
890           debugstr_a(pszDir), debugstr_a(pszBaseName), dwFlags);
891 
892     RtlCreateUnicodeStringFromAsciiz(&filelist, pszFileList);
893     RtlCreateUnicodeStringFromAsciiz(&dir, pszDir);
894     RtlCreateUnicodeStringFromAsciiz(&basename, pszBaseName);
895 
896     hr = FileSaveRestoreW(hDlg, filelist.Buffer, dir.Buffer,
897                           basename.Buffer, dwFlags);
898 
899     RtlFreeUnicodeString(&filelist);
900     RtlFreeUnicodeString(&dir);
901     RtlFreeUnicodeString(&basename);
902 
903     return hr;
904 }
905 
906 /***********************************************************************
907  *      FileSaveRestoreW (ADVPACK.@)
908  *
909  * Saves or restores the files in the specified file list.
910  *
911  * PARAMS
912  *   hDlg        [I] Handle to the dialog used for the display.
913  *   pszFileList [I] NULL-separated list of filenames.
914  *   pszDir      [I] Path of the backup directory.
915  *   pszBaseName [I] Basename of the backup files.
916  *   dwFlags     [I] See advpub.h.
917  *
918  * RETURNS
919  *   Success: S_OK.
920  *   Failure: E_FAIL.
921  *
922  * NOTES
923  *   If pszFileList is NULL on restore, all files will be restored.
924  *
925  * BUGS
926  *   Unimplemented.
927  */
928 HRESULT WINAPI FileSaveRestoreW(HWND hDlg, LPWSTR pszFileList, LPWSTR pszDir,
929                                 LPWSTR pszBaseName, DWORD dwFlags)
930 {
931     FIXME("(%p, %s, %s, %s, %d) stub\n", hDlg, debugstr_w(pszFileList),
932           debugstr_w(pszDir), debugstr_w(pszBaseName), dwFlags);
933 
934     return E_FAIL;
935 }
936 
937 /***********************************************************************
938  *      FileSaveRestoreOnINFA (ADVPACK.@)
939  *
940  * See FileSaveRestoreOnINFW.
941  */
942 HRESULT WINAPI FileSaveRestoreOnINFA(HWND hWnd, LPCSTR pszTitle, LPCSTR pszINF,
943                                     LPCSTR pszSection, LPCSTR pszBackupDir,
944                                     LPCSTR pszBaseBackupFile, DWORD dwFlags)
945 {
946     UNICODE_STRING title, inf, section;
947     UNICODE_STRING backupdir, backupfile;
948     HRESULT hr;
949 
950     TRACE("(%p, %s, %s, %s, %s, %s, %d)\n", hWnd, debugstr_a(pszTitle),
951           debugstr_a(pszINF), debugstr_a(pszSection), debugstr_a(pszBackupDir),
952           debugstr_a(pszBaseBackupFile), dwFlags);
953 
954     RtlCreateUnicodeStringFromAsciiz(&title, pszTitle);
955     RtlCreateUnicodeStringFromAsciiz(&inf, pszINF);
956     RtlCreateUnicodeStringFromAsciiz(&section, pszSection);
957     RtlCreateUnicodeStringFromAsciiz(&backupdir, pszBackupDir);
958     RtlCreateUnicodeStringFromAsciiz(&backupfile, pszBaseBackupFile);
959 
960     hr = FileSaveRestoreOnINFW(hWnd, title.Buffer, inf.Buffer, section.Buffer,
961                                backupdir.Buffer, backupfile.Buffer, dwFlags);
962 
963     RtlFreeUnicodeString(&title);
964     RtlFreeUnicodeString(&inf);
965     RtlFreeUnicodeString(&section);
966     RtlFreeUnicodeString(&backupdir);
967     RtlFreeUnicodeString(&backupfile);
968 
969     return hr;
970 }
971 
972 /***********************************************************************
973  *      FileSaveRestoreOnINFW (ADVPACK.@)
974  *
975  *
976  * PARAMS
977  *   hWnd              [I] Handle to the window used for the display.
978  *   pszTitle          [I] Title of the window.
979  *   pszINF            [I] Fully-qualified INF filename.
980  *   pszSection        [I] GenInstall INF section name.
981  *   pszBackupDir      [I] Directory to store the backup file.
982  *   pszBaseBackupFile [I] Basename of the backup files.
983  *   dwFlags           [I] See advpub.h
984  *
985  * RETURNS
986  *   Success: S_OK.
987  *   Failure: E_FAIL.
988  *
989  * NOTES
990  *   If pszSection is NULL, the default section will be used.
991  *
992  * BUGS
993  *   Unimplemented.
994  */
995 HRESULT WINAPI FileSaveRestoreOnINFW(HWND hWnd, LPCWSTR pszTitle, LPCWSTR pszINF,
996                                      LPCWSTR pszSection, LPCWSTR pszBackupDir,
997                                      LPCWSTR pszBaseBackupFile, DWORD dwFlags)
998 {
999     FIXME("(%p, %s, %s, %s, %s, %s, %d): stub\n", hWnd, debugstr_w(pszTitle),
1000           debugstr_w(pszINF), debugstr_w(pszSection), debugstr_w(pszBackupDir),
1001           debugstr_w(pszBaseBackupFile), dwFlags);
1002 
1003     return E_FAIL;
1004 }
1005 
1006 /***********************************************************************
1007  *             GetVersionFromFileA     (ADVPACK.@)
1008  *
1009  * See GetVersionFromFileExW.
1010  */
1011 HRESULT WINAPI GetVersionFromFileA(LPCSTR Filename, LPDWORD MajorVer,
1012                                    LPDWORD MinorVer, BOOL Version )
1013 {
1014     TRACE("(%s, %p, %p, %d)\n", debugstr_a(Filename), MajorVer, MinorVer, Version);
1015     return GetVersionFromFileExA(Filename, MajorVer, MinorVer, Version);
1016 }
1017 
1018 /***********************************************************************
1019  *             GetVersionFromFileW     (ADVPACK.@)
1020  *
1021  * See GetVersionFromFileExW.
1022  */
1023 HRESULT WINAPI GetVersionFromFileW(LPCWSTR Filename, LPDWORD MajorVer,
1024                                    LPDWORD MinorVer, BOOL Version )
1025 {
1026     TRACE("(%s, %p, %p, %d)\n", debugstr_w(Filename), MajorVer, MinorVer, Version);
1027     return GetVersionFromFileExW(Filename, MajorVer, MinorVer, Version);
1028 }
1029 
1030 /* data for GetVersionFromFileEx */
1031 typedef struct tagLANGANDCODEPAGE
1032 {
1033     WORD wLanguage;
1034     WORD wCodePage;
1035 } LANGANDCODEPAGE;
1036 
1037 /***********************************************************************
1038  *             GetVersionFromFileExA   (ADVPACK.@)
1039  *
1040  * See GetVersionFromFileExW.
1041  */
1042 HRESULT WINAPI GetVersionFromFileExA(LPCSTR lpszFilename, LPDWORD pdwMSVer,
1043                                      LPDWORD pdwLSVer, BOOL bVersion )
1044 {
1045     UNICODE_STRING filename;
1046     HRESULT res;
1047 
1048     TRACE("(%s, %p, %p, %d)\n", debugstr_a(lpszFilename),
1049           pdwMSVer, pdwLSVer, bVersion);
1050 
1051     RtlCreateUnicodeStringFromAsciiz(&filename, lpszFilename);
1052 
1053     res = GetVersionFromFileExW(filename.Buffer, pdwMSVer, pdwLSVer, bVersion);
1054 
1055     RtlFreeUnicodeString(&filename);
1056 
1057     return res;
1058 }
1059 
1060 /***********************************************************************
1061  *             GetVersionFromFileExW   (ADVPACK.@)
1062  *
1063  * Gets the files version or language information.
1064  *
1065  * PARAMS
1066  *   lpszFilename [I] The file to get the info from.
1067  *   pdwMSVer     [O] Major version.
1068  *   pdwLSVer     [O] Minor version.
1069  *   bVersion     [I] Whether to retrieve version or language info.
1070  *
1071  * RETURNS
1072  *   Always returns S_OK.
1073  *
1074  * NOTES
1075  *   If bVersion is TRUE, version information is retrieved, else
1076  *   pdwMSVer gets the language ID and pdwLSVer gets the codepage ID.
1077  */
1078 HRESULT WINAPI GetVersionFromFileExW(LPCWSTR lpszFilename, LPDWORD pdwMSVer,
1079                                      LPDWORD pdwLSVer, BOOL bVersion )
1080 {
1081     VS_FIXEDFILEINFO *pFixedVersionInfo;
1082     LANGANDCODEPAGE *pLangAndCodePage;
1083     DWORD dwHandle, dwInfoSize;
1084     WCHAR szWinDir[MAX_PATH];
1085     WCHAR szFile[MAX_PATH];
1086     LPVOID pVersionInfo = NULL;
1087     BOOL bFileCopied = FALSE;
1088     UINT uValueLen;
1089 
1090     static const WCHAR backslash[] = {'\\',0};
1091     static const WCHAR translation[] = {
1092         '\\','V','a','r','F','i','l','e','I','n','f','o',
1093         '\\','T','r','a','n','s','l','a','t','i','o','n',0
1094     };
1095 
1096     TRACE("(%s, %p, %p, %d)\n", debugstr_w(lpszFilename),
1097           pdwMSVer, pdwLSVer, bVersion);
1098 
1099     *pdwLSVer = 0;
1100     *pdwMSVer = 0;
1101 
1102     lstrcpynW(szFile, lpszFilename, MAX_PATH);
1103 
1104     dwInfoSize = GetFileVersionInfoSizeW(szFile, &dwHandle);
1105     if (!dwInfoSize)
1106     {
1107         /* check that the file exists */
1108         if (GetFileAttributesW(szFile) == INVALID_FILE_ATTRIBUTES)
1109             return S_OK;
1110 
1111         /* file exists, but won't be found by GetFileVersionInfoSize,
1112         * so copy it to the temp dir where it will be found.
1113         */
1114         GetWindowsDirectoryW(szWinDir, MAX_PATH);
1115         GetTempFileNameW(szWinDir, NULL, 0, szFile);
1116         CopyFileW(lpszFilename, szFile, FALSE);
1117         bFileCopied = TRUE;
1118 
1119         dwInfoSize = GetFileVersionInfoSizeW(szFile, &dwHandle);
1120         if (!dwInfoSize)
1121             goto done;
1122     }
1123 
1124     pVersionInfo = HeapAlloc(GetProcessHeap(), 0, dwInfoSize);
1125     if (!pVersionInfo)
1126         goto done;
1127 
1128     if (!GetFileVersionInfoW(szFile, dwHandle, dwInfoSize, pVersionInfo))
1129         goto done;
1130 
1131     if (bVersion)
1132     {
1133         if (!VerQueryValueW(pVersionInfo, backslash,
1134             (LPVOID *)&pFixedVersionInfo, &uValueLen))
1135             goto done;
1136 
1137         if (!uValueLen)
1138             goto done;
1139 
1140         *pdwMSVer = pFixedVersionInfo->dwFileVersionMS;
1141         *pdwLSVer = pFixedVersionInfo->dwFileVersionLS;
1142     }
1143     else
1144     {
1145         if (!VerQueryValueW(pVersionInfo, translation,
1146              (LPVOID *)&pLangAndCodePage, &uValueLen))
1147             goto done;
1148 
1149         if (!uValueLen)
1150             goto done;
1151 
1152         *pdwMSVer = pLangAndCodePage->wLanguage;
1153         *pdwLSVer = pLangAndCodePage->wCodePage;
1154     }
1155 
1156 done:
1157     HeapFree(GetProcessHeap(), 0, pVersionInfo);
1158 
1159     if (bFileCopied)
1160         DeleteFileW(szFile);
1161 
1162     return S_OK;
1163 }
1164