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