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