msi: Improve parsing of the package platform.
[wine] / dlls / msi / appsearch.c
1 /*
2  * Implementation of the AppSearch action of the Microsoft Installer (msi.dll)
3  *
4  * Copyright 2005 Juan Lang
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 #include <stdarg.h>
21
22 #define COBJMACROS
23
24 #include "windef.h"
25 #include "winbase.h"
26 #include "winreg.h"
27 #include "msi.h"
28 #include "msiquery.h"
29 #include "msidefs.h"
30 #include "winver.h"
31 #include "shlwapi.h"
32 #include "wine/unicode.h"
33 #include "wine/debug.h"
34 #include "msipriv.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(msi);
37
38 typedef struct tagMSISIGNATURE
39 {
40     LPCWSTR  Name;     /* NOT owned by this structure */
41     LPWSTR   File;
42     DWORD    MinVersionMS;
43     DWORD    MinVersionLS;
44     DWORD    MaxVersionMS;
45     DWORD    MaxVersionLS;
46     DWORD    MinSize;
47     DWORD    MaxSize;
48     FILETIME MinTime;
49     FILETIME MaxTime;
50     LPWSTR   Languages;
51 }MSISIGNATURE;
52
53 void msi_parse_version_string(LPCWSTR verStr, PDWORD ms, PDWORD ls)
54 {
55     const WCHAR *ptr;
56     int x1 = 0, x2 = 0, x3 = 0, x4 = 0;
57
58     x1 = atoiW(verStr);
59     ptr = strchrW(verStr, '.');
60     if (ptr)
61     {
62         x2 = atoiW(ptr + 1);
63         ptr = strchrW(ptr + 1, '.');
64     }
65     if (ptr)
66     {
67         x3 = atoiW(ptr + 1);
68         ptr = strchrW(ptr + 1, '.');
69     }
70     if (ptr)
71         x4 = atoiW(ptr + 1);
72     /* FIXME: byte-order dependent? */
73     *ms = x1 << 16 | x2;
74     if (ls) *ls = x3 << 16 | x4;
75 }
76
77 /* Fills in sig with the values from the Signature table, where name is the
78  * signature to find.  Upon return, sig->File will be NULL if the record is not
79  * found, and not NULL if it is found.
80  * Warning: clears all fields in sig!
81  * Returns ERROR_SUCCESS upon success (where not finding the record counts as
82  * success), something else on error.
83  */
84 static UINT ACTION_AppSearchGetSignature(MSIPACKAGE *package, MSISIGNATURE *sig, LPCWSTR name)
85 {
86     static const WCHAR query[] = {
87         's','e','l','e','c','t',' ','*',' ',
88         'f','r','o','m',' ',
89         'S','i','g','n','a','t','u','r','e',' ',
90         'w','h','e','r','e',' ','S','i','g','n','a','t','u','r','e',' ','=',' ',
91         '\'','%','s','\'',0};
92     LPWSTR minVersion, maxVersion, p;
93     MSIRECORD *row;
94     DWORD time;
95
96     TRACE("package %p, sig %p\n", package, sig);
97
98     memset(sig, 0, sizeof(*sig));
99     sig->Name = name;
100     row = MSI_QueryGetRecord( package->db, query, name );
101     if (!row)
102     {
103         TRACE("failed to query signature for %s\n", debugstr_w(name));
104         return ERROR_SUCCESS;
105     }
106
107     /* get properties */
108     sig->File = msi_dup_record_field(row,2);
109     if ((p = strchrW(sig->File, '|')))
110     {
111         p++;
112         memmove(sig->File, p, (strlenW(p) + 1) * sizeof(WCHAR));
113     }
114
115     minVersion = msi_dup_record_field(row,3);
116     if (minVersion)
117     {
118         msi_parse_version_string( minVersion, &sig->MinVersionMS, &sig->MinVersionLS );
119         msi_free( minVersion );
120     }
121     maxVersion = msi_dup_record_field(row,4);
122     if (maxVersion)
123     {
124         msi_parse_version_string( maxVersion, &sig->MaxVersionMS, &sig->MaxVersionLS );
125         msi_free( maxVersion );
126     }
127     sig->MinSize = MSI_RecordGetInteger(row,5);
128     if (sig->MinSize == MSI_NULL_INTEGER)
129         sig->MinSize = 0;
130     sig->MaxSize = MSI_RecordGetInteger(row,6);
131     if (sig->MaxSize == MSI_NULL_INTEGER)
132         sig->MaxSize = 0;
133     sig->Languages = msi_dup_record_field(row,9);
134     time = MSI_RecordGetInteger(row,7);
135     if (time != MSI_NULL_INTEGER)
136         DosDateTimeToFileTime(HIWORD(time), LOWORD(time), &sig->MinTime);
137     time = MSI_RecordGetInteger(row,8);
138     if (time != MSI_NULL_INTEGER)
139         DosDateTimeToFileTime(HIWORD(time), LOWORD(time), &sig->MaxTime);
140
141     TRACE("Found file name %s for Signature_ %s;\n",
142           debugstr_w(sig->File), debugstr_w(name));
143     TRACE("MinVersion is %d.%d.%d.%d\n", HIWORD(sig->MinVersionMS),
144           LOWORD(sig->MinVersionMS), HIWORD(sig->MinVersionLS),
145           LOWORD(sig->MinVersionLS));
146     TRACE("MaxVersion is %d.%d.%d.%d\n", HIWORD(sig->MaxVersionMS),
147           LOWORD(sig->MaxVersionMS), HIWORD(sig->MaxVersionLS),
148           LOWORD(sig->MaxVersionLS));
149     TRACE("MinSize is %d, MaxSize is %d;\n", sig->MinSize, sig->MaxSize);
150     TRACE("Languages is %s\n", debugstr_w(sig->Languages));
151
152     msiobj_release( &row->hdr );
153
154     return ERROR_SUCCESS;
155 }
156
157 /* Frees any memory allocated in sig */
158 static void ACTION_FreeSignature(MSISIGNATURE *sig)
159 {
160     msi_free(sig->File);
161     msi_free(sig->Languages);
162 }
163
164 static LPWSTR app_search_file(LPWSTR path, MSISIGNATURE *sig)
165 {
166     VS_FIXEDFILEINFO *info;
167     DWORD attr, handle, size;
168     LPWSTR val = NULL;
169     LPBYTE buffer;
170
171     if (!sig->File)
172     {
173         PathRemoveFileSpecW(path);
174         PathAddBackslashW(path);
175
176         attr = GetFileAttributesW(path);
177         if (attr != INVALID_FILE_ATTRIBUTES &&
178             (attr & FILE_ATTRIBUTE_DIRECTORY))
179             return strdupW(path);
180
181         return NULL;
182     }
183
184     attr = GetFileAttributesW(path);
185     if (attr == INVALID_FILE_ATTRIBUTES ||
186         (attr & FILE_ATTRIBUTE_DIRECTORY))
187         return NULL;
188
189     size = GetFileVersionInfoSizeW(path, &handle);
190     if (!size)
191         return strdupW(path);
192
193     buffer = msi_alloc(size);
194     if (!buffer)
195         return NULL;
196
197     if (!GetFileVersionInfoW(path, 0, size, buffer))
198         goto done;
199
200     if (!VerQueryValueW(buffer, szBackSlash, (LPVOID)&info, &size) || !info)
201         goto done;
202
203     if (sig->MinVersionLS || sig->MinVersionMS)
204     {
205         if (info->dwFileVersionMS < sig->MinVersionMS)
206             goto done;
207
208         if (info->dwFileVersionMS == sig->MinVersionMS &&
209             info->dwFileVersionLS < sig->MinVersionLS)
210             goto done;
211     }
212
213     if (sig->MaxVersionLS || sig->MaxVersionMS)
214     {
215         if (info->dwFileVersionMS > sig->MaxVersionMS)
216             goto done;
217
218         if (info->dwFileVersionMS == sig->MaxVersionMS &&
219             info->dwFileVersionLS > sig->MaxVersionLS)
220             goto done;
221     }
222
223     val = strdupW(path);
224
225 done:
226     msi_free(buffer);
227     return val;
228 }
229
230 static UINT ACTION_AppSearchComponents(MSIPACKAGE *package, LPWSTR *appValue, MSISIGNATURE *sig)
231 {
232     static const WCHAR query[] =  {
233         'S','E','L','E','C','T',' ','*',' ',
234         'F','R','O','M',' ',
235         '`','C','o','m','p','L','o','c','a','t','o','r','`',' ',
236         'W','H','E','R','E',' ','`','S','i','g','n','a','t','u','r','e','_','`',' ','=',' ',
237         '\'','%','s','\'',0};
238     static const WCHAR sigquery[] = {
239         'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
240         '`','S','i','g','n','a','t','u','r','e','`',' ',
241         'W','H','E','R','E',' ','`','S','i','g','n','a','t','u','r','e','`',' ','=',' ',
242         '\'','%','s','\'',0};
243
244     MSIRECORD *row, *rec;
245     LPCWSTR signature, guid;
246     BOOL sigpresent = TRUE;
247     BOOL isdir;
248     UINT type;
249     WCHAR path[MAX_PATH];
250     DWORD size = MAX_PATH;
251     LPWSTR ptr;
252     DWORD attr;
253
254     TRACE("%s\n", debugstr_w(sig->Name));
255
256     *appValue = NULL;
257
258     row = MSI_QueryGetRecord(package->db, query, sig->Name);
259     if (!row)
260     {
261         TRACE("failed to query CompLocator for %s\n", debugstr_w(sig->Name));
262         return ERROR_SUCCESS;
263     }
264
265     signature = MSI_RecordGetString(row, 1);
266     guid = MSI_RecordGetString(row, 2);
267     type = MSI_RecordGetInteger(row, 3);
268
269     rec = MSI_QueryGetRecord(package->db, sigquery, signature);
270     if (!rec)
271         sigpresent = FALSE;
272
273     *path = '\0';
274     MsiLocateComponentW(guid, path, &size);
275     if (!*path)
276         goto done;
277
278     attr = GetFileAttributesW(path);
279     if (attr == INVALID_FILE_ATTRIBUTES)
280         goto done;
281
282     isdir = (attr & FILE_ATTRIBUTE_DIRECTORY);
283
284     if (type != msidbLocatorTypeDirectory && sigpresent && !isdir)
285     {
286         *appValue = app_search_file(path, sig);
287     }
288     else if (!sigpresent && (type != msidbLocatorTypeDirectory || isdir))
289     {
290         if (type == msidbLocatorTypeFileName)
291         {
292             ptr = strrchrW(path, '\\');
293             *(ptr + 1) = '\0';
294         }
295         else
296             PathAddBackslashW(path);
297
298         *appValue = strdupW(path);
299     }
300     else if (sigpresent)
301     {
302         PathAddBackslashW(path);
303         lstrcatW(path, MSI_RecordGetString(rec, 2));
304
305         attr = GetFileAttributesW(path);
306         if (attr != INVALID_FILE_ATTRIBUTES &&
307             !(attr & FILE_ATTRIBUTE_DIRECTORY))
308             *appValue = strdupW(path);
309     }
310
311 done:
312     if (rec) msiobj_release(&rec->hdr);
313     msiobj_release(&row->hdr);
314     return ERROR_SUCCESS;
315 }
316
317 static void ACTION_ConvertRegValue(DWORD regType, const BYTE *value, DWORD sz,
318  LPWSTR *appValue)
319 {
320     static const WCHAR dwordFmt[] = { '#','%','d','\0' };
321     static const WCHAR binPre[] = { '#','x','\0' };
322     static const WCHAR binFmt[] = { '%','0','2','X','\0' };
323     LPWSTR ptr;
324     DWORD i;
325
326     switch (regType)
327     {
328         case REG_SZ:
329             if (*(LPCWSTR)value == '#')
330             {
331                 /* escape leading pound with another */
332                 *appValue = msi_alloc(sz + sizeof(WCHAR));
333                 (*appValue)[0] = '#';
334                 strcpyW(*appValue + 1, (LPCWSTR)value);
335             }
336             else
337             {
338                 *appValue = msi_alloc(sz);
339                 strcpyW(*appValue, (LPCWSTR)value);
340             }
341             break;
342         case REG_DWORD:
343             /* 7 chars for digits, 1 for NULL, 1 for #, and 1 for sign
344              * char if needed
345              */
346             *appValue = msi_alloc(10 * sizeof(WCHAR));
347             sprintfW(*appValue, dwordFmt, *(const DWORD *)value);
348             break;
349         case REG_EXPAND_SZ:
350             sz = ExpandEnvironmentStringsW((LPCWSTR)value, NULL, 0);
351             *appValue = msi_alloc(sz * sizeof(WCHAR));
352             ExpandEnvironmentStringsW((LPCWSTR)value, *appValue, sz);
353             break;
354         case REG_BINARY:
355             /* #x<nibbles>\0 */
356             *appValue = msi_alloc((sz * 2 + 3) * sizeof(WCHAR));
357             lstrcpyW(*appValue, binPre);
358             ptr = *appValue + lstrlenW(binPre);
359             for (i = 0; i < sz; i++, ptr += 2)
360                 sprintfW(ptr, binFmt, value[i]);
361             break;
362         default:
363             WARN("unimplemented for values of type %d\n", regType);
364             *appValue = NULL;
365     }
366 }
367
368 static UINT ACTION_SearchDirectory(MSIPACKAGE *package, MSISIGNATURE *sig,
369  LPCWSTR path, int depth, LPWSTR *appValue);
370
371 static UINT ACTION_AppSearchReg(MSIPACKAGE *package, LPWSTR *appValue, MSISIGNATURE *sig)
372 {
373     static const WCHAR query[] =  {
374         's','e','l','e','c','t',' ','*',' ',
375         'f','r','o','m',' ',
376         'R','e','g','L','o','c','a','t','o','r',' ',
377         'w','h','e','r','e',' ',
378         'S','i','g','n','a','t','u','r','e','_',' ','=',' ', '\'','%','s','\'',0};
379     LPWSTR keyPath = NULL, valueName = NULL;
380     LPWSTR deformatted = NULL;
381     LPWSTR ptr = NULL, end;
382     int root, type;
383     HKEY rootKey, key = NULL;
384     DWORD sz = 0, regType;
385     LPBYTE value = NULL;
386     MSIRECORD *row;
387     UINT rc;
388
389     TRACE("%s\n", debugstr_w(sig->Name));
390
391     *appValue = NULL;
392
393     row = MSI_QueryGetRecord( package->db, query, sig->Name );
394     if (!row)
395     {
396         TRACE("failed to query RegLocator for %s\n", debugstr_w(sig->Name));
397         return ERROR_SUCCESS;
398     }
399
400     root = MSI_RecordGetInteger(row,2);
401     keyPath = msi_dup_record_field(row,3);
402     valueName = msi_dup_record_field(row,4);
403     type = MSI_RecordGetInteger(row,5);
404
405     deformat_string(package, keyPath, &deformatted);
406
407     switch (root)
408     {
409     case msidbRegistryRootClassesRoot:
410         rootKey = HKEY_CLASSES_ROOT;
411         break;
412     case msidbRegistryRootCurrentUser:
413         rootKey = HKEY_CURRENT_USER;
414         break;
415     case msidbRegistryRootLocalMachine:
416         rootKey = HKEY_LOCAL_MACHINE;
417         break;
418     case msidbRegistryRootUsers:
419         rootKey = HKEY_USERS;
420         break;
421     default:
422         WARN("Unknown root key %d\n", root);
423         goto end;
424     }
425
426     rc = RegOpenKeyW(rootKey, deformatted, &key);
427     if (rc)
428     {
429         TRACE("RegOpenKeyW returned %d\n", rc);
430         goto end;
431     }
432
433     rc = RegQueryValueExW(key, valueName, NULL, NULL, NULL, &sz);
434     if (rc)
435     {
436         TRACE("RegQueryValueExW returned %d\n", rc);
437         goto end;
438     }
439     /* FIXME: sanity-check sz before allocating (is there an upper-limit
440      * on the value of a property?)
441      */
442     value = msi_alloc( sz );
443     rc = RegQueryValueExW(key, valueName, NULL, &regType, value, &sz);
444     if (rc)
445     {
446         TRACE("RegQueryValueExW returned %d\n", rc);
447         goto end;
448     }
449
450     /* bail out if the registry key is empty */
451     if (sz == 0)
452         goto end;
453
454     if ((regType == REG_SZ || regType == REG_EXPAND_SZ) &&
455         (ptr = strchrW((LPWSTR)value, '"')) && (end = strchrW(++ptr, '"')))
456         *end = '\0';
457     else
458         ptr = (LPWSTR)value;
459
460     switch (type & 0x0f)
461     {
462     case msidbLocatorTypeDirectory:
463         ACTION_SearchDirectory(package, sig, ptr, 0, appValue);
464         break;
465     case msidbLocatorTypeFileName:
466         *appValue = app_search_file(ptr, sig);
467         break;
468     case msidbLocatorTypeRawValue:
469         ACTION_ConvertRegValue(regType, value, sz, appValue);
470         break;
471     default:
472         FIXME("unimplemented for type %d (key path %s, value %s)\n",
473               type, debugstr_w(keyPath), debugstr_w(valueName));
474     }
475 end:
476     msi_free( value );
477     RegCloseKey( key );
478
479     msi_free( keyPath );
480     msi_free( valueName );
481     msi_free( deformatted );
482
483     msiobj_release(&row->hdr);
484     return ERROR_SUCCESS;
485 }
486
487 static LPWSTR get_ini_field(LPWSTR buf, int field)
488 {
489     LPWSTR beg, end;
490     int i = 1;
491
492     if (field == 0)
493         return strdupW(buf);
494
495     beg = buf;
496     while ((end = strchrW(beg, ',')) && i < field)
497     {
498         beg = end + 1;
499         while (*beg && *beg == ' ')
500             beg++;
501
502         i++;
503     }
504
505     end = strchrW(beg, ',');
506     if (!end)
507         end = beg + lstrlenW(beg);
508
509     *end = '\0';
510     return strdupW(beg);
511 }
512
513 static UINT ACTION_AppSearchIni(MSIPACKAGE *package, LPWSTR *appValue,
514  MSISIGNATURE *sig)
515 {
516     static const WCHAR query[] =  {
517         's','e','l','e','c','t',' ','*',' ',
518         'f','r','o','m',' ',
519         'I','n','i','L','o','c','a','t','o','r',' ',
520         'w','h','e','r','e',' ',
521         'S','i','g','n','a','t','u','r','e','_',' ','=',' ','\'','%','s','\'',0};
522     MSIRECORD *row;
523     LPWSTR fileName, section, key;
524     int field, type;
525     WCHAR buf[MAX_PATH];
526
527     TRACE("%s\n", debugstr_w(sig->Name));
528
529     *appValue = NULL;
530
531     row = MSI_QueryGetRecord( package->db, query, sig->Name );
532     if (!row)
533     {
534         TRACE("failed to query IniLocator for %s\n", debugstr_w(sig->Name));
535         return ERROR_SUCCESS;
536     }
537
538     fileName = msi_dup_record_field(row, 2);
539     section = msi_dup_record_field(row, 3);
540     key = msi_dup_record_field(row, 4);
541     field = MSI_RecordGetInteger(row, 5);
542     type = MSI_RecordGetInteger(row, 6);
543     if (field == MSI_NULL_INTEGER)
544         field = 0;
545     if (type == MSI_NULL_INTEGER)
546         type = 0;
547
548     GetPrivateProfileStringW(section, key, NULL, buf, MAX_PATH, fileName);
549     if (buf[0])
550     {
551         switch (type & 0x0f)
552         {
553         case msidbLocatorTypeDirectory:
554             ACTION_SearchDirectory(package, sig, buf, 0, appValue);
555             break;
556         case msidbLocatorTypeFileName:
557             *appValue = app_search_file(buf, sig);
558             break;
559         case msidbLocatorTypeRawValue:
560             *appValue = get_ini_field(buf, field);
561             break;
562         }
563     }
564
565     msi_free(fileName);
566     msi_free(section);
567     msi_free(key);
568
569     msiobj_release(&row->hdr);
570
571     return ERROR_SUCCESS;
572 }
573
574 /* Expands the value in src into a path without property names and only
575  * containing long path names into dst.  Replaces at most len characters of dst,
576  * and always NULL-terminates dst if dst is not NULL and len >= 1.
577  * May modify src.
578  * Assumes src and dst are non-overlapping.
579  * FIXME: return code probably needed:
580  * - what does AppSearch return if the table values are invalid?
581  * - what if dst is too small?
582  */
583 static void ACTION_ExpandAnyPath(MSIPACKAGE *package, WCHAR *src, WCHAR *dst,
584  size_t len)
585 {
586     WCHAR *ptr, *deformatted;
587
588     if (!src || !dst || !len)
589     {
590         if (dst) *dst = '\0';
591         return;
592     }
593
594     dst[0] = '\0';
595
596     /* Ignore the short portion of the path */
597     if ((ptr = strchrW(src, '|')))
598         ptr++;
599     else
600         ptr = src;
601
602     deformat_string(package, ptr, &deformatted);
603     if (!deformatted || strlenW(deformatted) > len - 1)
604     {
605         msi_free(deformatted);
606         return;
607     }
608
609     lstrcpyW(dst, deformatted);
610     dst[lstrlenW(deformatted)] = '\0';
611     msi_free(deformatted);
612 }
613
614 /* Sets *matches to whether the file (whose path is filePath) matches the
615  * versions set in sig.
616  * Return ERROR_SUCCESS in case of success (whether or not the file matches),
617  * something else if an install-halting error occurs.
618  */
619 static UINT ACTION_FileVersionMatches(const MSISIGNATURE *sig, LPCWSTR filePath,
620  BOOL *matches)
621 {
622     UINT rc = ERROR_SUCCESS;
623
624     *matches = FALSE;
625     if (sig->Languages)
626     {
627         FIXME(": need to check version for languages %s\n",
628          debugstr_w(sig->Languages));
629     }
630     else
631     {
632         DWORD zero, size = GetFileVersionInfoSizeW(filePath, &zero);
633
634         if (size)
635         {
636             LPVOID buf = msi_alloc( size);
637
638             if (buf)
639             {
640                 UINT versionLen;
641                 LPVOID subBlock = NULL;
642
643                 if (GetFileVersionInfoW(filePath, 0, size, buf))
644                     VerQueryValueW(buf, szBackSlash, &subBlock, &versionLen);
645                 if (subBlock)
646                 {
647                     VS_FIXEDFILEINFO *info = subBlock;
648
649                     TRACE("Comparing file version %d.%d.%d.%d:\n",
650                      HIWORD(info->dwFileVersionMS),
651                      LOWORD(info->dwFileVersionMS),
652                      HIWORD(info->dwFileVersionLS),
653                      LOWORD(info->dwFileVersionLS));
654                     if (info->dwFileVersionMS < sig->MinVersionMS
655                      || (info->dwFileVersionMS == sig->MinVersionMS &&
656                      info->dwFileVersionLS < sig->MinVersionLS))
657                     {
658                         TRACE("Less than minimum version %d.%d.%d.%d\n",
659                          HIWORD(sig->MinVersionMS),
660                          LOWORD(sig->MinVersionMS),
661                          HIWORD(sig->MinVersionLS),
662                          LOWORD(sig->MinVersionLS));
663                     }
664                     else if ((sig->MaxVersionMS || sig->MaxVersionLS) &&
665                              (info->dwFileVersionMS > sig->MaxVersionMS ||
666                               (info->dwFileVersionMS == sig->MaxVersionMS &&
667                                info->dwFileVersionLS > sig->MaxVersionLS)))
668                     {
669                         TRACE("Greater than maximum version %d.%d.%d.%d\n",
670                          HIWORD(sig->MaxVersionMS),
671                          LOWORD(sig->MaxVersionMS),
672                          HIWORD(sig->MaxVersionLS),
673                          LOWORD(sig->MaxVersionLS));
674                     }
675                     else
676                         *matches = TRUE;
677                 }
678                 msi_free( buf);
679             }
680             else
681                 rc = ERROR_OUTOFMEMORY;
682         }
683     }
684     return rc;
685 }
686
687 /* Sets *matches to whether the file in findData matches that in sig.
688  * fullFilePath is assumed to be the full path of the file specified in
689  * findData, which may be necessary to compare the version.
690  * Return ERROR_SUCCESS in case of success (whether or not the file matches),
691  * something else if an install-halting error occurs.
692  */
693 static UINT ACTION_FileMatchesSig(const MSISIGNATURE *sig,
694  const WIN32_FIND_DATAW *findData, LPCWSTR fullFilePath, BOOL *matches)
695 {
696     UINT rc = ERROR_SUCCESS;
697
698     *matches = TRUE;
699     /* assumes the caller has already ensured the filenames match, so check
700      * the other fields..
701      */
702     if (sig->MinTime.dwLowDateTime || sig->MinTime.dwHighDateTime)
703     {
704         if (findData->ftCreationTime.dwHighDateTime <
705          sig->MinTime.dwHighDateTime ||
706          (findData->ftCreationTime.dwHighDateTime == sig->MinTime.dwHighDateTime
707          && findData->ftCreationTime.dwLowDateTime <
708          sig->MinTime.dwLowDateTime))
709             *matches = FALSE;
710     }
711     if (*matches && (sig->MaxTime.dwLowDateTime || sig->MaxTime.dwHighDateTime))
712     {
713         if (findData->ftCreationTime.dwHighDateTime >
714          sig->MaxTime.dwHighDateTime ||
715          (findData->ftCreationTime.dwHighDateTime == sig->MaxTime.dwHighDateTime
716          && findData->ftCreationTime.dwLowDateTime >
717          sig->MaxTime.dwLowDateTime))
718             *matches = FALSE;
719     }
720     if (*matches && sig->MinSize && findData->nFileSizeLow < sig->MinSize)
721         *matches = FALSE;
722     if (*matches && sig->MaxSize && findData->nFileSizeLow > sig->MaxSize)
723         *matches = FALSE;
724     if (*matches && (sig->MinVersionMS || sig->MinVersionLS ||
725      sig->MaxVersionMS || sig->MaxVersionLS))
726         rc = ACTION_FileVersionMatches(sig, fullFilePath, matches);
727     return rc;
728 }
729
730 /* Recursively searches the directory dir for files that match the signature
731  * sig, up to (depth + 1) levels deep.  That is, if depth is 0, it searches dir
732  * (and only dir).  If depth is 1, searches dir and its immediate
733  * subdirectories.
734  * Assumes sig->File is not NULL.
735  * Returns ERROR_SUCCESS on success (which may include non-critical errors),
736  * something else on failures which should halt the install.
737  */
738 static UINT ACTION_RecurseSearchDirectory(MSIPACKAGE *package, LPWSTR *appValue,
739  MSISIGNATURE *sig, LPCWSTR dir, int depth)
740 {
741     HANDLE hFind;
742     WIN32_FIND_DATAW findData;
743     UINT rc = ERROR_SUCCESS;
744     size_t dirLen = lstrlenW(dir), fileLen = lstrlenW(sig->File);
745     WCHAR subpath[MAX_PATH];
746     WCHAR *buf;
747     DWORD len;
748
749     static const WCHAR starDotStarW[] = { '*','.','*',0 };
750
751     TRACE("Searching directory %s for file %s, depth %d\n", debugstr_w(dir),
752           debugstr_w(sig->File), depth);
753
754     if (depth < 0)
755         return ERROR_SUCCESS;
756
757     *appValue = NULL;
758     /* We need the buffer in both paths below, so go ahead and allocate it
759      * here.  Add two because we might need to add a backslash if the dir name
760      * isn't backslash-terminated.
761      */
762     len = dirLen + max(fileLen, strlenW(starDotStarW)) + 2;
763     buf = msi_alloc(len * sizeof(WCHAR));
764     if (!buf)
765         return ERROR_OUTOFMEMORY;
766
767     lstrcpyW(buf, dir);
768     PathAddBackslashW(buf);
769     lstrcatW(buf, sig->File);
770
771     hFind = FindFirstFileW(buf, &findData);
772     if (hFind != INVALID_HANDLE_VALUE)
773     {
774         if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
775         {
776             BOOL matches;
777
778             rc = ACTION_FileMatchesSig(sig, &findData, buf, &matches);
779             if (rc == ERROR_SUCCESS && matches)
780             {
781                 TRACE("found file, returning %s\n", debugstr_w(buf));
782                 *appValue = buf;
783             }
784         }
785         FindClose(hFind);
786     }
787
788     if (rc == ERROR_SUCCESS && !*appValue)
789     {
790         lstrcpyW(buf, dir);
791         PathAddBackslashW(buf);
792         lstrcatW(buf, starDotStarW);
793
794         hFind = FindFirstFileW(buf, &findData);
795         if (hFind != INVALID_HANDLE_VALUE)
796         {
797             if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
798                 strcmpW( findData.cFileName, szDot ) &&
799                 strcmpW( findData.cFileName, szDotDot ))
800             {
801                 lstrcpyW(subpath, dir);
802                 PathAppendW(subpath, findData.cFileName);
803                 rc = ACTION_RecurseSearchDirectory(package, appValue, sig,
804                                                    subpath, depth - 1);
805             }
806
807             while (rc == ERROR_SUCCESS && !*appValue &&
808                    FindNextFileW(hFind, &findData) != 0)
809             {
810                 if (!strcmpW( findData.cFileName, szDot ) ||
811                     !strcmpW( findData.cFileName, szDotDot ))
812                     continue;
813
814                 lstrcpyW(subpath, dir);
815                 PathAppendW(subpath, findData.cFileName);
816                 if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
817                     rc = ACTION_RecurseSearchDirectory(package, appValue,
818                                                        sig, subpath, depth - 1);
819             }
820
821             FindClose(hFind);
822         }
823     }
824
825     if (*appValue != buf)
826         msi_free(buf);
827
828     return rc;
829 }
830
831 static UINT ACTION_CheckDirectory(MSIPACKAGE *package, LPCWSTR dir,
832  LPWSTR *appValue)
833 {
834     DWORD attr = GetFileAttributesW(dir);
835
836     if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY))
837     {
838         TRACE("directory exists, returning %s\n", debugstr_w(dir));
839         *appValue = strdupW(dir);
840     }
841
842     return ERROR_SUCCESS;
843 }
844
845 static BOOL ACTION_IsFullPath(LPCWSTR path)
846 {
847     WCHAR first = toupperW(path[0]);
848     BOOL ret;
849
850     if (first >= 'A' && first <= 'Z' && path[1] == ':')
851         ret = TRUE;
852     else if (path[0] == '\\' && path[1] == '\\')
853         ret = TRUE;
854     else
855         ret = FALSE;
856     return ret;
857 }
858
859 static UINT ACTION_SearchDirectory(MSIPACKAGE *package, MSISIGNATURE *sig,
860  LPCWSTR path, int depth, LPWSTR *appValue)
861 {
862     UINT rc;
863     DWORD attr;
864     LPWSTR val = NULL;
865
866     TRACE("%p, %p, %s, %d, %p\n", package, sig, debugstr_w(path), depth,
867      appValue);
868
869     if (ACTION_IsFullPath(path))
870     {
871         if (sig->File)
872             rc = ACTION_RecurseSearchDirectory(package, &val, sig, path, depth);
873         else
874         {
875             /* Recursively searching a directory makes no sense when the
876              * directory to search is the thing you're trying to find.
877              */
878             rc = ACTION_CheckDirectory(package, path, &val);
879         }
880     }
881     else
882     {
883         WCHAR pathWithDrive[MAX_PATH] = { 'C',':','\\',0 };
884         DWORD drives = GetLogicalDrives();
885         int i;
886
887         rc = ERROR_SUCCESS;
888         for (i = 0; rc == ERROR_SUCCESS && !val && i < 26; i++)
889         {
890             if (!(drives & (1 << i)))
891                 continue;
892
893             pathWithDrive[0] = 'A' + i;
894             if (GetDriveTypeW(pathWithDrive) != DRIVE_FIXED)
895                 continue;
896
897             lstrcpynW(pathWithDrive + 3, path,
898                       sizeof(pathWithDrive) / sizeof(pathWithDrive[0]) - 3);
899
900             if (sig->File)
901                 rc = ACTION_RecurseSearchDirectory(package, &val, sig,
902                                                    pathWithDrive, depth);
903             else
904                 rc = ACTION_CheckDirectory(package, pathWithDrive, &val);
905         }
906     }
907
908     attr = GetFileAttributesW(val);
909     if (attr != INVALID_FILE_ATTRIBUTES &&
910         (attr & FILE_ATTRIBUTE_DIRECTORY) &&
911         val && val[lstrlenW(val) - 1] != '\\')
912     {
913         val = msi_realloc(val, (lstrlenW(val) + 2) * sizeof(WCHAR));
914         if (!val)
915             rc = ERROR_OUTOFMEMORY;
916         else
917             PathAddBackslashW(val);
918     }
919
920     *appValue = val;
921
922     TRACE("returning %d\n", rc);
923     return rc;
924 }
925
926 static UINT ACTION_AppSearchSigName(MSIPACKAGE *package, LPCWSTR sigName,
927  MSISIGNATURE *sig, LPWSTR *appValue);
928
929 static UINT ACTION_AppSearchDr(MSIPACKAGE *package, LPWSTR *appValue, MSISIGNATURE *sig)
930 {
931     static const WCHAR query[] =  {
932         's','e','l','e','c','t',' ','*',' ',
933         'f','r','o','m',' ',
934         'D','r','L','o','c','a','t','o','r',' ',
935         'w','h','e','r','e',' ',
936         'S','i','g','n','a','t','u','r','e','_',' ','=',' ', '\'','%','s','\'',0};
937     LPWSTR parent = NULL;
938     LPCWSTR parentName;
939     WCHAR path[MAX_PATH];
940     WCHAR expanded[MAX_PATH];
941     MSIRECORD *row;
942     int depth;
943     DWORD sz, attr;
944     UINT rc;
945
946     TRACE("%s\n", debugstr_w(sig->Name));
947
948     *appValue = NULL;
949
950     row = MSI_QueryGetRecord( package->db, query, sig->Name );
951     if (!row)
952     {
953         TRACE("failed to query DrLocator for %s\n", debugstr_w(sig->Name));
954         return ERROR_SUCCESS;
955     }
956
957     /* check whether parent is set */
958     parentName = MSI_RecordGetString(row, 2);
959     if (parentName)
960     {
961         MSISIGNATURE parentSig;
962
963         ACTION_AppSearchSigName(package, parentName, &parentSig, &parent);
964         ACTION_FreeSignature(&parentSig);
965         if (!parent)
966         {
967             msiobj_release(&row->hdr);
968             return ERROR_SUCCESS;
969         }
970     }
971
972     sz = MAX_PATH;
973     MSI_RecordGetStringW(row, 3, path, &sz);
974
975     if (MSI_RecordIsNull(row,4))
976         depth = 0;
977     else
978         depth = MSI_RecordGetInteger(row,4);
979
980     if (sz)
981         ACTION_ExpandAnyPath(package, path, expanded, MAX_PATH);
982     else
983         strcpyW(expanded, path);
984
985     if (parent)
986     {
987         attr = GetFileAttributesW(parent);
988         if (attr != INVALID_FILE_ATTRIBUTES &&
989             !(attr & FILE_ATTRIBUTE_DIRECTORY))
990         {
991             PathRemoveFileSpecW(parent);
992             PathAddBackslashW(parent);
993         }
994
995         strcpyW(path, parent);
996         strcatW(path, expanded);
997     }
998     else if (sz)
999         strcpyW(path, expanded);
1000
1001     PathAddBackslashW(path);
1002
1003     rc = ACTION_SearchDirectory(package, sig, path, depth, appValue);
1004
1005     msi_free(parent);
1006     msiobj_release(&row->hdr);
1007
1008     TRACE("returning %d\n", rc);
1009     return rc;
1010 }
1011
1012 static UINT ACTION_AppSearchSigName(MSIPACKAGE *package, LPCWSTR sigName,
1013  MSISIGNATURE *sig, LPWSTR *appValue)
1014 {
1015     UINT rc;
1016
1017     *appValue = NULL;
1018     rc = ACTION_AppSearchGetSignature(package, sig, sigName);
1019     if (rc == ERROR_SUCCESS)
1020     {
1021         rc = ACTION_AppSearchComponents(package, appValue, sig);
1022         if (rc == ERROR_SUCCESS && !*appValue)
1023         {
1024             rc = ACTION_AppSearchReg(package, appValue, sig);
1025             if (rc == ERROR_SUCCESS && !*appValue)
1026             {
1027                 rc = ACTION_AppSearchIni(package, appValue, sig);
1028                 if (rc == ERROR_SUCCESS && !*appValue)
1029                     rc = ACTION_AppSearchDr(package, appValue, sig);
1030             }
1031         }
1032     }
1033     return rc;
1034 }
1035
1036 static UINT iterate_appsearch(MSIRECORD *row, LPVOID param)
1037 {
1038     MSIPACKAGE *package = param;
1039     LPCWSTR propName, sigName;
1040     LPWSTR value = NULL;
1041     MSISIGNATURE sig;
1042     MSIRECORD *uirow;
1043     UINT r;
1044
1045     /* get property and signature */
1046     propName = MSI_RecordGetString(row, 1);
1047     sigName = MSI_RecordGetString(row, 2);
1048
1049     TRACE("%s %s\n", debugstr_w(propName), debugstr_w(sigName));
1050
1051     r = ACTION_AppSearchSigName(package, sigName, &sig, &value);
1052     if (value)
1053     {
1054         r = msi_set_property( package->db, propName, value );
1055         if (r == ERROR_SUCCESS && !strcmpW( propName, szSourceDir ))
1056             msi_reset_folders( package, TRUE );
1057
1058         msi_free(value);
1059     }
1060     ACTION_FreeSignature(&sig);
1061
1062     uirow = MSI_CreateRecord( 2 );
1063     MSI_RecordSetStringW( uirow, 1, propName );
1064     MSI_RecordSetStringW( uirow, 2, sigName );
1065     msi_ui_actiondata( package, szAppSearch, uirow );
1066     msiobj_release( &uirow->hdr );
1067
1068     return r;
1069 }
1070
1071 UINT ACTION_AppSearch(MSIPACKAGE *package)
1072 {
1073     static const WCHAR query[] =  {
1074         'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1075         'A','p','p','S','e','a','r','c','h',0};
1076     MSIQUERY *view;
1077     UINT r;
1078
1079     if (msi_action_is_unique(package, szAppSearch))
1080     {
1081         TRACE("Skipping AppSearch action: already done in UI sequence\n");
1082         return ERROR_SUCCESS;
1083     }
1084     else
1085         msi_register_unique_action(package, szAppSearch);
1086
1087     r = MSI_OpenQuery( package->db, &view, query );
1088     if (r != ERROR_SUCCESS)
1089         return ERROR_SUCCESS;
1090
1091     r = MSI_IterateRecords( view, NULL, iterate_appsearch, package );
1092     msiobj_release( &view->hdr );
1093     return r;
1094 }
1095
1096 static UINT ITERATE_CCPSearch(MSIRECORD *row, LPVOID param)
1097 {
1098     MSIPACKAGE *package = param;
1099     LPCWSTR signature;
1100     LPWSTR value = NULL;
1101     MSISIGNATURE sig;
1102     UINT r = ERROR_SUCCESS;
1103
1104     static const WCHAR success[] = {'C','C','P','_','S','u','c','c','e','s','s',0};
1105
1106     signature = MSI_RecordGetString(row, 1);
1107
1108     TRACE("%s\n", debugstr_w(signature));
1109
1110     ACTION_AppSearchSigName(package, signature, &sig, &value);
1111     if (value)
1112     {
1113         TRACE("Found signature %s\n", debugstr_w(signature));
1114         msi_set_property(package->db, success, szOne);
1115         msi_free(value);
1116         r = ERROR_NO_MORE_ITEMS;
1117     }
1118
1119     ACTION_FreeSignature(&sig);
1120
1121     return r;
1122 }
1123
1124 UINT ACTION_CCPSearch(MSIPACKAGE *package)
1125 {
1126     static const WCHAR query[] =  {
1127         'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1128         'C','C','P','S','e','a','r','c','h',0};
1129     MSIQUERY *view;
1130     UINT r;
1131
1132     if (msi_action_is_unique(package, szCCPSearch))
1133     {
1134         TRACE("Skipping AppSearch action: already done in UI sequence\n");
1135         return ERROR_SUCCESS;
1136     }
1137     else
1138         msi_register_unique_action(package, szCCPSearch);
1139
1140     r = MSI_OpenQuery(package->db, &view, query);
1141     if (r != ERROR_SUCCESS)
1142         return ERROR_SUCCESS;
1143
1144     r = MSI_IterateRecords(view, NULL, ITERATE_CCPSearch, package);
1145     msiobj_release(&view->hdr);
1146     return r;
1147 }