xref: /reactos/dll/win32/msi/custom.c (revision 3d6aaff2)
1 /*
2  * Custom Action processing for the Microsoft Installer (msi.dll)
3  *
4  * Copyright 2005 Aric Stewart for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20 
21 #define COBJMACROS
22 
23 #include <stdarg.h>
24 #include <stdio.h>
25 
26 #include "ntstatus.h"
27 #define WIN32_NO_STATUS
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winerror.h"
31 #include "msidefs.h"
32 #include "winuser.h"
33 #include "objbase.h"
34 #include "oleauto.h"
35 
36 #include "msipriv.h"
37 #include "winemsi_s.h"
38 #include "wine/asm.h"
39 #include "wine/heap.h"
40 #include "wine/debug.h"
41 #include "wine/unicode.h"
42 #include "wine/exception.h"
43 
44 #ifdef __REACTOS__
45 #undef WIN32_NO_STATUS
46 #include <psdk/ntstatus.h>
47 #include <ndk/mmfuncs.h>
48 #endif
49 
50 WINE_DEFAULT_DEBUG_CHANNEL(msi);
51 
52 #define CUSTOM_ACTION_TYPE_MASK 0x3F
53 
54 typedef struct tagMSIRUNNINGACTION
55 {
56     struct list entry;
57     HANDLE handle;
58     BOOL   process;
59     LPWSTR name;
60 } MSIRUNNINGACTION;
61 
62 typedef UINT (WINAPI *MsiCustomActionEntryPoint)( MSIHANDLE );
63 
64 static CRITICAL_SECTION msi_custom_action_cs;
65 static CRITICAL_SECTION_DEBUG msi_custom_action_cs_debug =
66 {
67     0, 0, &msi_custom_action_cs,
68     { &msi_custom_action_cs_debug.ProcessLocksList,
69       &msi_custom_action_cs_debug.ProcessLocksList },
70       0, 0, { (DWORD_PTR)(__FILE__ ": msi_custom_action_cs") }
71 };
72 static CRITICAL_SECTION msi_custom_action_cs = { &msi_custom_action_cs_debug, -1, 0, 0, 0, 0 };
73 
74 static struct list msi_pending_custom_actions = LIST_INIT( msi_pending_custom_actions );
75 
76 void  __RPC_FAR * __RPC_USER MIDL_user_allocate(SIZE_T len)
77 {
78     return heap_alloc(len);
79 }
80 
81 void __RPC_USER MIDL_user_free(void __RPC_FAR * ptr)
82 {
83     heap_free(ptr);
84 }
85 
86 LONG WINAPI rpc_filter(EXCEPTION_POINTERS *eptr)
87 {
88     return I_RpcExceptionFilter(eptr->ExceptionRecord->ExceptionCode);
89 }
90 
91 UINT msi_schedule_action( MSIPACKAGE *package, UINT script, const WCHAR *action )
92 {
93     UINT count;
94     WCHAR **newbuf = NULL;
95 
96     if (script >= SCRIPT_MAX)
97     {
98         FIXME("Unknown script requested %u\n", script);
99         return ERROR_FUNCTION_FAILED;
100     }
101     TRACE("Scheduling action %s in script %u\n", debugstr_w(action), script);
102 
103     count = package->script_actions_count[script];
104     package->script_actions_count[script]++;
105     if (count != 0) newbuf = msi_realloc( package->script_actions[script],
106                                           package->script_actions_count[script] * sizeof(WCHAR *) );
107     else newbuf = msi_alloc( sizeof(WCHAR *) );
108 
109     newbuf[count] = strdupW( action );
110     package->script_actions[script] = newbuf;
111     return ERROR_SUCCESS;
112 }
113 
114 UINT msi_register_unique_action( MSIPACKAGE *package, const WCHAR *action )
115 {
116     UINT count;
117     WCHAR **newbuf = NULL;
118 
119     TRACE("Registering %s as unique action\n", debugstr_w(action));
120 
121     count = package->unique_actions_count;
122     package->unique_actions_count++;
123     if (count != 0) newbuf = msi_realloc( package->unique_actions,
124                                           package->unique_actions_count * sizeof(WCHAR *) );
125     else newbuf = msi_alloc( sizeof(WCHAR *) );
126 
127     newbuf[count] = strdupW( action );
128     package->unique_actions = newbuf;
129     return ERROR_SUCCESS;
130 }
131 
132 BOOL msi_action_is_unique( const MSIPACKAGE *package, const WCHAR *action )
133 {
134     UINT i;
135 
136     for (i = 0; i < package->unique_actions_count; i++)
137     {
138         if (!wcscmp( package->unique_actions[i], action )) return TRUE;
139     }
140     return FALSE;
141 }
142 
143 static BOOL check_execution_scheduling_options(MSIPACKAGE *package, LPCWSTR action, UINT options)
144 {
145     if ((options & msidbCustomActionTypeClientRepeat) ==
146             msidbCustomActionTypeClientRepeat)
147     {
148         if (!(package->InWhatSequence & SEQUENCE_UI &&
149             package->InWhatSequence & SEQUENCE_EXEC))
150         {
151             TRACE("Skipping action due to dbCustomActionTypeClientRepeat option.\n");
152             return FALSE;
153         }
154     }
155     else if (options & msidbCustomActionTypeFirstSequence)
156     {
157         if (package->InWhatSequence & SEQUENCE_UI &&
158             package->InWhatSequence & SEQUENCE_EXEC )
159         {
160             TRACE("Skipping action due to msidbCustomActionTypeFirstSequence option.\n");
161             return FALSE;
162         }
163     }
164     else if (options & msidbCustomActionTypeOncePerProcess)
165     {
166         if (msi_action_is_unique(package, action))
167         {
168             TRACE("Skipping action due to msidbCustomActionTypeOncePerProcess option.\n");
169             return FALSE;
170         }
171         else
172             msi_register_unique_action(package, action);
173     }
174 
175     return TRUE;
176 }
177 
178 /* stores the following properties before the action:
179  *
180  *    [CustomActionData<=>UserSID<=>ProductCode]Action
181  */
182 static LPWSTR msi_get_deferred_action(LPCWSTR action, LPCWSTR actiondata,
183                                       LPCWSTR usersid, LPCWSTR prodcode)
184 {
185     LPWSTR deferred;
186     DWORD len;
187 
188     if (!actiondata)
189         return strdupW(action);
190 
191     len = lstrlenW(action) + lstrlenW(actiondata) +
192           lstrlenW(usersid) + lstrlenW(prodcode) +
193           lstrlenW(L"[%s<=>%s<=>%s]%s") - 7;
194     deferred = msi_alloc(len * sizeof(WCHAR));
195 
196     swprintf(deferred, len, L"[%s<=>%s<=>%s]%s", actiondata, usersid, prodcode, action);
197     return deferred;
198 }
199 
200 static void set_deferred_action_props( MSIPACKAGE *package, const WCHAR *deferred_data )
201 {
202     const WCHAR *end, *beg = deferred_data + 1;
203 
204     end = wcsstr(beg, L"<=>");
205     msi_set_property( package->db, L"CustomActionData", beg, end - beg );
206     beg = end + 3;
207 
208     end = wcsstr(beg, L"<=>");
209     msi_set_property( package->db, L"UserSID", beg, end - beg );
210     beg = end + 3;
211 
212     end = wcschr(beg, ']');
213     msi_set_property( package->db, L"ProductCode", beg, end - beg );
214 }
215 
216 WCHAR *msi_create_temp_file( MSIDATABASE *db )
217 {
218     WCHAR *ret;
219 
220     if (!db->tempfolder)
221     {
222         WCHAR tmp[MAX_PATH];
223         UINT len = ARRAY_SIZE( tmp );
224 
225         if (msi_get_property( db, L"TempFolder", tmp, &len ) ||
226             GetFileAttributesW( tmp ) != FILE_ATTRIBUTE_DIRECTORY)
227         {
228             GetTempPathW( MAX_PATH, tmp );
229         }
230         if (!(db->tempfolder = strdupW( tmp ))) return NULL;
231     }
232 
233     if ((ret = msi_alloc( (lstrlenW( db->tempfolder ) + 20) * sizeof(WCHAR) )))
234     {
235         if (!GetTempFileNameW( db->tempfolder, L"msi", 0, ret ))
236         {
237             msi_free( ret );
238             return NULL;
239         }
240     }
241 
242     return ret;
243 }
244 
245 static MSIBINARY *create_temp_binary(MSIPACKAGE *package, LPCWSTR source)
246 {
247     MSIRECORD *row;
248     MSIBINARY *binary = NULL;
249     HANDLE file;
250     CHAR buffer[1024];
251     WCHAR *tmpfile;
252     DWORD sz, write;
253     UINT r;
254 
255     if (!(tmpfile = msi_create_temp_file( package->db ))) return NULL;
256 
257     if (!(row = MSI_QueryGetRecord( package->db, L"SELECT * FROM `Binary` WHERE `Name` = '%s'", source ))) goto error;
258     if (!(binary = msi_alloc_zero( sizeof(MSIBINARY) ))) goto error;
259 
260     file = CreateFileW( tmpfile, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
261     if (file == INVALID_HANDLE_VALUE) goto error;
262 
263     do
264     {
265         sz = sizeof(buffer);
266         r = MSI_RecordReadStream( row, 2, buffer, &sz );
267         if (r != ERROR_SUCCESS)
268         {
269             ERR("Failed to get stream\n");
270             break;
271         }
272         WriteFile( file, buffer, sz, &write, NULL );
273     } while (sz == sizeof buffer);
274 
275     CloseHandle( file );
276     if (r != ERROR_SUCCESS) goto error;
277 
278     binary->source = strdupW( source );
279     binary->tmpfile = tmpfile;
280     list_add_tail( &package->binaries, &binary->entry );
281 
282     msiobj_release( &row->hdr );
283     return binary;
284 
285 error:
286     if (row) msiobj_release( &row->hdr );
287     DeleteFileW( tmpfile );
288     msi_free( tmpfile );
289     msi_free( binary );
290     return NULL;
291 }
292 
293 static MSIBINARY *get_temp_binary(MSIPACKAGE *package, LPCWSTR source)
294 {
295     MSIBINARY *binary;
296 
297     LIST_FOR_EACH_ENTRY( binary, &package->binaries, MSIBINARY, entry )
298     {
299         if (!wcscmp( binary->source, source ))
300             return binary;
301     }
302 
303     return create_temp_binary(package, source);
304 }
305 
306 static void file_running_action(MSIPACKAGE* package, HANDLE Handle,
307                                 BOOL process, LPCWSTR name)
308 {
309     MSIRUNNINGACTION *action;
310 
311     action = msi_alloc( sizeof(MSIRUNNINGACTION) );
312 
313     action->handle = Handle;
314     action->process = process;
315     action->name = strdupW(name);
316 
317     list_add_tail( &package->RunningActions, &action->entry );
318 }
319 
320 static UINT custom_get_process_return( HANDLE process )
321 {
322     DWORD rc = 0;
323 
324     GetExitCodeProcess( process, &rc );
325     TRACE("exit code is %u\n", rc);
326     if (rc != 0)
327         return ERROR_FUNCTION_FAILED;
328     return ERROR_SUCCESS;
329 }
330 
331 static UINT custom_get_thread_return( MSIPACKAGE *package, HANDLE thread )
332 {
333     DWORD rc = 0;
334 
335     GetExitCodeThread( thread, &rc );
336 
337     switch (rc)
338     {
339     case ERROR_FUNCTION_NOT_CALLED:
340     case ERROR_SUCCESS:
341     case ERROR_INSTALL_USEREXIT:
342     case ERROR_INSTALL_FAILURE:
343         return rc;
344     case ERROR_NO_MORE_ITEMS:
345         return ERROR_SUCCESS;
346     case ERROR_INSTALL_SUSPEND:
347         ACTION_ForceReboot( package );
348         return ERROR_SUCCESS;
349     default:
350         ERR("Invalid Return Code %d\n",rc);
351         return ERROR_INSTALL_FAILURE;
352     }
353 }
354 
355 static UINT wait_process_handle(MSIPACKAGE* package, UINT type,
356                            HANDLE ProcessHandle, LPCWSTR name)
357 {
358     UINT rc = ERROR_SUCCESS;
359 
360     if (!(type & msidbCustomActionTypeAsync))
361     {
362         TRACE("waiting for %s\n", debugstr_w(name));
363 
364         msi_dialog_check_messages(ProcessHandle);
365 
366         if (!(type & msidbCustomActionTypeContinue))
367             rc = custom_get_process_return(ProcessHandle);
368 
369         CloseHandle(ProcessHandle);
370     }
371     else
372     {
373         TRACE("%s running in background\n", debugstr_w(name));
374 
375         if (!(type & msidbCustomActionTypeContinue))
376             file_running_action(package, ProcessHandle, TRUE, name);
377         else
378             CloseHandle(ProcessHandle);
379     }
380 
381     return rc;
382 }
383 
384 typedef struct _msi_custom_action_info {
385     struct list entry;
386     MSIPACKAGE *package;
387     LPWSTR source;
388     LPWSTR target;
389     HANDLE handle;
390     LPWSTR action;
391     INT type;
392     GUID guid;
393     DWORD arch;
394 } msi_custom_action_info;
395 
396 static void free_custom_action_data( msi_custom_action_info *info )
397 {
398     EnterCriticalSection( &msi_custom_action_cs );
399 
400     list_remove( &info->entry );
401     if (info->handle)
402         CloseHandle( info->handle );
403     msi_free( info->action );
404     msi_free( info->source );
405     msi_free( info->target );
406     msiobj_release( &info->package->hdr );
407     msi_free( info );
408 
409     LeaveCriticalSection( &msi_custom_action_cs );
410 }
411 
412 static UINT wait_thread_handle( msi_custom_action_info *info )
413 {
414     UINT rc = ERROR_SUCCESS;
415 
416     if (!(info->type & msidbCustomActionTypeAsync))
417     {
418         TRACE("waiting for %s\n", debugstr_w( info->action ));
419 
420         msi_dialog_check_messages( info->handle );
421 
422         if (!(info->type & msidbCustomActionTypeContinue))
423             rc = custom_get_thread_return( info->package, info->handle );
424 
425         free_custom_action_data( info );
426     }
427     else
428     {
429         TRACE("%s running in background\n", debugstr_w( info->action ));
430     }
431 
432     return rc;
433 }
434 
435 static msi_custom_action_info *find_action_by_guid( const GUID *guid )
436 {
437     msi_custom_action_info *info;
438     BOOL found = FALSE;
439 
440     EnterCriticalSection( &msi_custom_action_cs );
441 
442     LIST_FOR_EACH_ENTRY( info, &msi_pending_custom_actions, msi_custom_action_info, entry )
443     {
444         if (IsEqualGUID( &info->guid, guid ))
445         {
446             found = TRUE;
447             break;
448         }
449     }
450 
451     LeaveCriticalSection( &msi_custom_action_cs );
452 
453     if (!found)
454         return NULL;
455 
456     return info;
457 }
458 
459 static void handle_msi_break(LPCSTR target)
460 {
461     char format[] = "To debug your custom action, attach your debugger to "
462                     "process %i (0x%X) and press OK";
463     char val[MAX_PATH];
464     char msg[100];
465 
466     if (!GetEnvironmentVariableA("MsiBreak", val, MAX_PATH))
467         return;
468 
469     if (strcmp(val, target))
470         return;
471 
472     sprintf(msg, format, GetCurrentProcessId(), GetCurrentProcessId());
473     MessageBoxA(NULL, msg, "Windows Installer", MB_OK);
474     DebugBreak();
475 }
476 
477 #if defined __i386__ && defined _MSC_VER
478 __declspec(naked) UINT custom_proc_wrapper(MsiCustomActionEntryPoint entry, MSIHANDLE hinst)
479 {
480     __asm
481     {
482         push ebp
483         mov ebp, esp
484         sub esp, 4
485         push [ebp+12]
486         call [ebp+8]
487         leave
488         ret
489     }
490 }
491 #elif defined __i386__ && defined __GNUC__
492 /* wrapper for apps that don't declare the thread function correctly */
493 extern UINT custom_proc_wrapper( MsiCustomActionEntryPoint entry, MSIHANDLE hinst );
494 __ASM_GLOBAL_FUNC(custom_proc_wrapper,
495                   "pushl %ebp\n\t"
496                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
497                   __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
498                   "movl %esp,%ebp\n\t"
499                   __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
500                   "subl $4,%esp\n\t"
501                   "pushl 12(%ebp)\n\t"
502                   "call *8(%ebp)\n\t"
503                   "leave\n\t"
504                   __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
505                   __ASM_CFI(".cfi_same_value %ebp\n\t")
506                   "ret" )
507 #else
508 static UINT custom_proc_wrapper( MsiCustomActionEntryPoint entry, MSIHANDLE hinst )
509 {
510     return entry(hinst);
511 }
512 #endif
513 
514 UINT CDECL __wine_msi_call_dll_function(DWORD client_pid, const GUID *guid)
515 {
516     MsiCustomActionEntryPoint fn;
517     MSIHANDLE remote_package = 0;
518     RPC_WSTR binding_str;
519     MSIHANDLE hPackage;
520     RPC_STATUS status;
521     LPWSTR dll = NULL;
522     LPSTR proc = NULL;
523     HANDLE hModule;
524     INT type;
525     UINT r;
526 
527     TRACE("%s\n", debugstr_guid( guid ));
528 
529     if (!rpc_handle)
530     {
531         WCHAR endpoint[12];
532 
533         swprintf(endpoint, ARRAY_SIZE(endpoint), L"msi%x", client_pid);
534         status = RpcStringBindingComposeW(NULL, (WCHAR *)L"ncalrpc", NULL, endpoint, NULL, &binding_str);
535         if (status != RPC_S_OK)
536         {
537             ERR("RpcStringBindingCompose failed: %#x\n", status);
538             return status;
539         }
540         status = RpcBindingFromStringBindingW(binding_str, &rpc_handle);
541         if (status != RPC_S_OK)
542         {
543             ERR("RpcBindingFromStringBinding failed: %#x\n", status);
544             return status;
545         }
546         RpcStringFreeW(&binding_str);
547     }
548 
549     r = remote_GetActionInfo(guid, &type, &dll, &proc, &remote_package);
550     if (r != ERROR_SUCCESS)
551         return r;
552 
553     hPackage = alloc_msi_remote_handle( remote_package );
554     if (!hPackage)
555     {
556         ERR( "failed to create handle for %x\n", remote_package );
557         midl_user_free( dll );
558         midl_user_free( proc );
559         return ERROR_INSTALL_FAILURE;
560     }
561 
562     hModule = LoadLibraryW( dll );
563     if (!hModule)
564     {
565         ERR( "failed to load dll %s (%u)\n", debugstr_w( dll ), GetLastError() );
566         midl_user_free( dll );
567         midl_user_free( proc );
568         MsiCloseHandle( hPackage );
569         return ERROR_SUCCESS;
570     }
571 
572     fn = (MsiCustomActionEntryPoint) GetProcAddress( hModule, proc );
573     if (!fn) WARN( "GetProcAddress(%s) failed\n", debugstr_a(proc) );
574     else
575     {
576         handle_msi_break(proc);
577 
578         __TRY
579         {
580             r = custom_proc_wrapper( fn, hPackage );
581         }
582         __EXCEPT_PAGE_FAULT
583         {
584             ERR( "Custom action (%s:%s) caused a page fault: %08x\n",
585                  debugstr_w(dll), debugstr_a(proc), GetExceptionCode() );
586             r = ERROR_SUCCESS;
587         }
588         __ENDTRY;
589     }
590 
591     FreeLibrary(hModule);
592 
593     midl_user_free(dll);
594     midl_user_free(proc);
595 
596     MsiCloseAllHandles();
597 
598     return r;
599 }
600 
601 static DWORD custom_start_server(MSIPACKAGE *package, DWORD arch)
602 {
603     WCHAR path[MAX_PATH], cmdline[MAX_PATH + 23];
604     PROCESS_INFORMATION pi = {0};
605     STARTUPINFOW si = {0};
606     WCHAR buffer[24];
607     void *cookie;
608     HANDLE pipe;
609 
610     if ((arch == SCS_32BIT_BINARY && package->custom_server_32_process) ||
611         (arch == SCS_64BIT_BINARY && package->custom_server_64_process))
612         return ERROR_SUCCESS;
613 
614     swprintf(buffer, ARRAY_SIZE(buffer), L"\\\\.\\pipe\\msica_%x_%d",
615              GetCurrentProcessId(), arch == SCS_32BIT_BINARY ? 32 : 64);
616     pipe = CreateNamedPipeW(buffer, PIPE_ACCESS_DUPLEX, 0, 1, sizeof(DWORD64),
617         sizeof(GUID), 0, NULL);
618     if (pipe == INVALID_HANDLE_VALUE)
619         ERR("Failed to create custom action client pipe: %u\n", GetLastError());
620 
621     if ((sizeof(void *) == 8 || is_wow64) && arch == SCS_32BIT_BINARY)
622         GetSystemWow64DirectoryW(path, MAX_PATH - ARRAY_SIZE(L"\\msiexec.exe"));
623     else
624         GetSystemDirectoryW(path, MAX_PATH - ARRAY_SIZE(L"\\msiexec.exe"));
625     lstrcatW(path, L"\\msiexec.exe");
626     swprintf(cmdline, ARRAY_SIZE(cmdline), L"%s -Embedding %d", path, GetCurrentProcessId());
627 
628     if (is_wow64 && arch == SCS_64BIT_BINARY)
629     {
630         Wow64DisableWow64FsRedirection(&cookie);
631         CreateProcessW(path, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
632         Wow64RevertWow64FsRedirection(cookie);
633     }
634     else
635         CreateProcessW(path, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
636 
637     CloseHandle(pi.hThread);
638 
639     if (arch == SCS_32BIT_BINARY)
640     {
641         package->custom_server_32_process = pi.hProcess;
642         package->custom_server_32_pipe = pipe;
643     }
644     else
645     {
646         package->custom_server_64_process = pi.hProcess;
647         package->custom_server_64_pipe = pipe;
648     }
649 
650     if (!ConnectNamedPipe(pipe, NULL))
651     {
652         ERR("Failed to connect to custom action server: %u\n", GetLastError());
653         return GetLastError();
654     }
655 
656     return ERROR_SUCCESS;
657 }
658 
659 void custom_stop_server(HANDLE process, HANDLE pipe)
660 {
661     DWORD size;
662 
663     WriteFile(pipe, &GUID_NULL, sizeof(GUID_NULL), &size, NULL);
664     WaitForSingleObject(process, INFINITE);
665     CloseHandle(process);
666     CloseHandle(pipe);
667 }
668 
669 static DWORD WINAPI custom_client_thread(void *arg)
670 {
671     msi_custom_action_info *info = arg;
672     DWORD64 thread64;
673     HANDLE process;
674     HANDLE thread;
675     HANDLE pipe;
676     DWORD size;
677     UINT rc;
678 
679     CoInitializeEx(NULL, COINIT_MULTITHREADED); /* needed to marshal streams */
680 
681     if (info->arch == SCS_32BIT_BINARY)
682     {
683         process = info->package->custom_server_32_process;
684         pipe = info->package->custom_server_32_pipe;
685     }
686     else
687     {
688         process = info->package->custom_server_64_process;
689         pipe = info->package->custom_server_64_pipe;
690     }
691 
692     EnterCriticalSection(&msi_custom_action_cs);
693 
694     if (!WriteFile(pipe, &info->guid, sizeof(info->guid), &size, NULL) ||
695         size != sizeof(info->guid))
696     {
697         ERR("Failed to write to custom action client pipe: %u\n", GetLastError());
698         LeaveCriticalSection(&msi_custom_action_cs);
699         return GetLastError();
700     }
701     if (!ReadFile(pipe, &thread64, sizeof(thread64), &size, NULL) || size != sizeof(thread64))
702     {
703         ERR("Failed to read from custom action client pipe: %u\n", GetLastError());
704         LeaveCriticalSection(&msi_custom_action_cs);
705         return GetLastError();
706     }
707 
708     LeaveCriticalSection(&msi_custom_action_cs);
709 
710     if (DuplicateHandle(process, (HANDLE)(DWORD_PTR)thread64, GetCurrentProcess(),
711         &thread, 0, FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE))
712     {
713         WaitForSingleObject(thread, INFINITE);
714         GetExitCodeThread(thread, &rc);
715         CloseHandle(thread);
716     }
717     else
718         rc = GetLastError();
719 
720     CoUninitialize();
721     return rc;
722 }
723 
724 /* based on kernel32.GetBinaryTypeW() */
725 static BOOL get_binary_type( const WCHAR *name, DWORD *type )
726 {
727     HANDLE hfile, mapping;
728     NTSTATUS status;
729 
730     hfile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
731     if (hfile == INVALID_HANDLE_VALUE)
732         return FALSE;
733 
734     status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY, NULL, NULL, PAGE_READONLY,
735                               SEC_IMAGE, hfile );
736     CloseHandle( hfile );
737 
738     switch (status)
739     {
740     case STATUS_SUCCESS:
741         {
742             SECTION_IMAGE_INFORMATION info;
743 
744             status = NtQuerySection( mapping, SectionImageInformation, &info, sizeof(info), NULL );
745             CloseHandle( mapping );
746             if (status) return FALSE;
747             switch (info.Machine)
748             {
749             case IMAGE_FILE_MACHINE_I386:
750             case IMAGE_FILE_MACHINE_ARMNT:
751                 *type = SCS_32BIT_BINARY;
752                 return TRUE;
753             case IMAGE_FILE_MACHINE_AMD64:
754             case IMAGE_FILE_MACHINE_ARM64:
755                 *type = SCS_64BIT_BINARY;
756                 return TRUE;
757             default:
758                 return FALSE;
759             }
760         }
761     case STATUS_INVALID_IMAGE_WIN_64:
762         *type = SCS_64BIT_BINARY;
763         return TRUE;
764     default:
765         return FALSE;
766     }
767 }
768 
769 static msi_custom_action_info *do_msidbCustomActionTypeDll(
770     MSIPACKAGE *package, INT type, LPCWSTR source, LPCWSTR target, LPCWSTR action )
771 {
772     msi_custom_action_info *info;
773     RPC_STATUS status;
774     BOOL ret;
775 
776     info = msi_alloc( sizeof *info );
777     if (!info)
778         return NULL;
779 
780     msiobj_addref( &package->hdr );
781     info->package = package;
782     info->type = type;
783     info->target = strdupW( target );
784     info->source = strdupW( source );
785     info->action = strdupW( action );
786     CoCreateGuid( &info->guid );
787 
788     EnterCriticalSection( &msi_custom_action_cs );
789     list_add_tail( &msi_pending_custom_actions, &info->entry );
790     LeaveCriticalSection( &msi_custom_action_cs );
791 
792     if (!package->rpc_server_started)
793     {
794         WCHAR endpoint[12];
795 
796         swprintf(endpoint, ARRAY_SIZE(endpoint), L"msi%x", GetCurrentProcessId());
797         status = RpcServerUseProtseqEpW((WCHAR *)L"ncalrpc", RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
798             endpoint, NULL);
799         if (status != RPC_S_OK)
800         {
801             ERR("RpcServerUseProtseqEp failed: %#x\n", status);
802             return NULL;
803         }
804 
805         status = RpcServerRegisterIfEx(s_IWineMsiRemote_v0_0_s_ifspec, NULL, NULL,
806             RPC_IF_AUTOLISTEN, RPC_C_LISTEN_MAX_CALLS_DEFAULT, NULL);
807         if (status != RPC_S_OK)
808         {
809             ERR("RpcServerRegisterIfEx failed: %#x\n", status);
810             return NULL;
811         }
812 
813         info->package->rpc_server_started = 1;
814     }
815 
816     ret = get_binary_type(source, &info->arch);
817     if (!ret)
818         info->arch = (sizeof(void *) == 8 ? SCS_64BIT_BINARY : SCS_32BIT_BINARY);
819 
820     if (info->arch == SCS_64BIT_BINARY && sizeof(void *) == 4 && !is_wow64)
821     {
822         ERR("Attempt to run a 64-bit custom action inside a 32-bit WINEPREFIX.\n");
823         free_custom_action_data( info );
824         return NULL;
825     }
826 
827     custom_start_server(package, info->arch);
828 
829     info->handle = CreateThread(NULL, 0, custom_client_thread, info, 0, NULL);
830     if (!info->handle)
831     {
832         free_custom_action_data( info );
833         return NULL;
834     }
835 
836     return info;
837 }
838 
839 static UINT HANDLE_CustomType1( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
840                                 INT type, const WCHAR *action )
841 {
842     msi_custom_action_info *info;
843     MSIBINARY *binary;
844 
845     if (!(binary = get_temp_binary(package, source)))
846         return ERROR_FUNCTION_FAILED;
847 
848     TRACE("Calling function %s from %s\n", debugstr_w(target), debugstr_w(binary->tmpfile));
849 
850     if (!(info = do_msidbCustomActionTypeDll( package, type, binary->tmpfile, target, action )))
851         return ERROR_FUNCTION_FAILED;
852     return wait_thread_handle( info );
853 }
854 
855 static HANDLE execute_command( const WCHAR *app, WCHAR *arg, const WCHAR *dir )
856 {
857     STARTUPINFOW si;
858     PROCESS_INFORMATION info;
859     WCHAR *exe = NULL, *cmd = NULL, *p;
860     BOOL ret;
861 
862     if (app)
863     {
864         int len_arg = 0;
865         DWORD len_exe;
866 
867         if (!(exe = msi_alloc( MAX_PATH * sizeof(WCHAR) ))) return INVALID_HANDLE_VALUE;
868         len_exe = SearchPathW( NULL, app, L".exe", MAX_PATH, exe, NULL );
869         if (len_exe >= MAX_PATH)
870         {
871             msi_free( exe );
872             if (!(exe = msi_alloc( len_exe * sizeof(WCHAR) ))) return INVALID_HANDLE_VALUE;
873             len_exe = SearchPathW( NULL, app, L".exe", len_exe, exe, NULL );
874         }
875         if (!len_exe)
876         {
877             ERR("can't find executable %u\n", GetLastError());
878             msi_free( exe );
879             return INVALID_HANDLE_VALUE;
880         }
881 
882         if (arg) len_arg = lstrlenW( arg );
883         if (!(cmd = msi_alloc( (len_exe + len_arg + 4) * sizeof(WCHAR) )))
884         {
885             msi_free( exe );
886             return INVALID_HANDLE_VALUE;
887         }
888         p = cmd;
889         if (wcschr( exe, ' ' ))
890         {
891             *p++ = '\"';
892             memcpy( p, exe, len_exe * sizeof(WCHAR) );
893             p += len_exe;
894             *p++ = '\"';
895             *p = 0;
896         }
897         else
898         {
899             lstrcpyW( p, exe );
900             p += len_exe;
901         }
902         if (arg)
903         {
904             *p++ = ' ';
905             memcpy( p, arg, len_arg * sizeof(WCHAR) );
906             p[len_arg] = 0;
907         }
908     }
909     memset( &si, 0, sizeof(STARTUPINFOW) );
910     ret = CreateProcessW( exe, exe ? cmd : arg, NULL, NULL, FALSE, 0, NULL, dir, &si, &info );
911     msi_free( cmd );
912     msi_free( exe );
913     if (!ret)
914     {
915         ERR("unable to execute command %u\n", GetLastError());
916         return INVALID_HANDLE_VALUE;
917     }
918     CloseHandle( info.hThread );
919     return info.hProcess;
920 }
921 
922 static UINT HANDLE_CustomType2( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
923                                 INT type, const WCHAR *action )
924 {
925     MSIBINARY *binary;
926     HANDLE handle;
927     WCHAR *arg;
928 
929     if (!(binary = get_temp_binary(package, source)))
930         return ERROR_FUNCTION_FAILED;
931 
932     deformat_string( package, target, &arg );
933     TRACE("exe %s arg %s\n", debugstr_w(binary->tmpfile), debugstr_w(arg));
934 
935     handle = execute_command( binary->tmpfile, arg, L"C:\\" );
936     msi_free( arg );
937     if (handle == INVALID_HANDLE_VALUE) return ERROR_SUCCESS;
938     return wait_process_handle( package, type, handle, action );
939 }
940 
941 static UINT HANDLE_CustomType17( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
942                                  INT type, const WCHAR *action )
943 {
944     msi_custom_action_info *info;
945     MSIFILE *file;
946 
947     TRACE("%s %s\n", debugstr_w(source), debugstr_w(target));
948 
949     file = msi_get_loaded_file( package, source );
950     if (!file)
951     {
952         ERR("invalid file key %s\n", debugstr_w( source ));
953         return ERROR_FUNCTION_FAILED;
954     }
955 
956     if (!(info = do_msidbCustomActionTypeDll( package, type, file->TargetPath, target, action )))
957         return ERROR_FUNCTION_FAILED;
958     return wait_thread_handle( info );
959 }
960 
961 static UINT HANDLE_CustomType18( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
962                                  INT type, const WCHAR *action )
963 {
964     MSIFILE *file;
965     HANDLE handle;
966     WCHAR *arg;
967 
968     if (!(file = msi_get_loaded_file( package, source ))) return ERROR_FUNCTION_FAILED;
969 
970     deformat_string( package, target, &arg );
971     TRACE("exe %s arg %s\n", debugstr_w(file->TargetPath), debugstr_w(arg));
972 
973     handle = execute_command( file->TargetPath, arg, L"C:\\" );
974     msi_free( arg );
975     if (handle == INVALID_HANDLE_VALUE) return ERROR_SUCCESS;
976     return wait_process_handle( package, type, handle, action );
977 }
978 
979 static UINT HANDLE_CustomType19( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
980                                  INT type, const WCHAR *action )
981 {
982     MSIRECORD *row = 0;
983     LPWSTR deformated = NULL;
984 
985     deformat_string( package, target, &deformated );
986 
987     /* first try treat the error as a number */
988     row = MSI_QueryGetRecord( package->db, L"SELECT `Message` FROM `Error` WHERE `Error` = '%s'", deformated );
989     if( row )
990     {
991         LPCWSTR error = MSI_RecordGetString( row, 1 );
992         if ((package->ui_level & INSTALLUILEVEL_MASK) != INSTALLUILEVEL_NONE)
993             MessageBoxW( NULL, error, NULL, MB_OK );
994         msiobj_release( &row->hdr );
995     }
996     else if ((package->ui_level & INSTALLUILEVEL_MASK) != INSTALLUILEVEL_NONE)
997         MessageBoxW( NULL, deformated, NULL, MB_OK );
998 
999     msi_free( deformated );
1000 
1001     return ERROR_INSTALL_FAILURE;
1002 }
1003 
1004 static WCHAR *build_msiexec_args( const WCHAR *filename, const WCHAR *params )
1005 {
1006     UINT len_filename = lstrlenW( filename ), len_params = lstrlenW( params );
1007     UINT len = ARRAY_SIZE(L"/qb /i ") - 1;
1008     WCHAR *ret;
1009 
1010     if (!(ret = msi_alloc( (len + len_filename + len_params + 4) * sizeof(WCHAR) ))) return NULL;
1011     memcpy( ret, L"/qb /i ", sizeof(L"/qb /i ") );
1012     ret[len++] = '"';
1013     memcpy( ret + len, filename, len_filename * sizeof(WCHAR) );
1014     len += len_filename;
1015     ret[len++] = '"';
1016     ret[len++] = ' ';
1017     lstrcpyW( ret + len, params );
1018     return ret;
1019 }
1020 
1021 static UINT HANDLE_CustomType23( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
1022                                  INT type, const WCHAR *action )
1023 {
1024     WCHAR *dir, *filename, *args, *p;
1025     UINT len_dir, len_source = lstrlenW( source );
1026     HANDLE handle;
1027 
1028     if (!(dir = msi_dup_property( package->db, L"OriginalDatabase" ))) return ERROR_OUTOFMEMORY;
1029     if (!(p = wcsrchr( dir, '\\' )) && !(p = wcsrchr( dir, '/' )))
1030     {
1031         msi_free( dir );
1032         return ERROR_FUNCTION_FAILED;
1033     }
1034     *p = 0;
1035     len_dir = p - dir;
1036     if (!(filename = msi_alloc( (len_dir + len_source + 2) * sizeof(WCHAR) )))
1037     {
1038         msi_free( dir );
1039         return ERROR_OUTOFMEMORY;
1040     }
1041     memcpy( filename, dir, len_dir * sizeof(WCHAR) );
1042     filename[len_dir++] = '\\';
1043     memcpy( filename + len_dir, source, len_source * sizeof(WCHAR) );
1044     filename[len_dir + len_source] = 0;
1045 
1046     if (!(args = build_msiexec_args( filename, target )))
1047     {
1048         msi_free( dir );
1049         return ERROR_OUTOFMEMORY;
1050     }
1051 
1052     TRACE("installing %s concurrently\n", debugstr_w(source));
1053 
1054     handle = execute_command( L"msiexec", args, dir );
1055     msi_free( dir );
1056     msi_free( args );
1057     if (handle == INVALID_HANDLE_VALUE) return ERROR_SUCCESS;
1058     return wait_process_handle( package, type, handle, action );
1059 }
1060 
1061 static UINT write_substorage_to_file( MSIPACKAGE *package, const WCHAR *source, const WCHAR *filename )
1062 {
1063     IStorage *src = NULL, *dst = NULL;
1064     UINT r = ERROR_FUNCTION_FAILED;
1065     HRESULT hr;
1066 
1067     hr = StgCreateDocfile( filename, STGM_CREATE|STGM_TRANSACTED|STGM_WRITE|STGM_SHARE_EXCLUSIVE, 0, &dst );
1068     if (FAILED( hr ))
1069     {
1070         WARN( "can't open destination storage %s (%08x)\n", debugstr_w(filename), hr );
1071         goto done;
1072     }
1073 
1074     hr = IStorage_OpenStorage( package->db->storage, source, NULL, STGM_SHARE_EXCLUSIVE, NULL, 0, &src );
1075     if (FAILED( hr ))
1076     {
1077         WARN( "can't open source storage %s (%08x)\n", debugstr_w(source), hr );
1078         goto done;
1079     }
1080 
1081     hr = IStorage_CopyTo( src, 0, NULL, NULL, dst );
1082     if (FAILED( hr ))
1083     {
1084         ERR( "failed to copy storage %s (%08x)\n", debugstr_w(source), hr );
1085         goto done;
1086     }
1087 
1088     hr = IStorage_Commit( dst, 0 );
1089     if (FAILED( hr ))
1090         ERR( "failed to commit storage (%08x)\n", hr );
1091     else
1092         r = ERROR_SUCCESS;
1093 
1094 done:
1095     if (src) IStorage_Release( src );
1096     if (dst) IStorage_Release( dst );
1097     return r;
1098 }
1099 
1100 static UINT HANDLE_CustomType7( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
1101                                 INT type, const WCHAR *action )
1102 {
1103     WCHAR *tmpfile, *args;
1104     MSIBINARY *binary = NULL;
1105     HANDLE handle;
1106     UINT r;
1107 
1108     if (!(tmpfile = msi_create_temp_file( package->db ))) return ERROR_FUNCTION_FAILED;
1109 
1110     r = write_substorage_to_file( package, source, tmpfile );
1111     if (r != ERROR_SUCCESS)
1112         goto error;
1113 
1114     if (!(binary = msi_alloc( sizeof(*binary) ))) goto error;
1115     binary->source  = NULL;
1116     binary->tmpfile = tmpfile;
1117     list_add_tail( &package->binaries, &binary->entry );
1118 
1119     if (!(args = build_msiexec_args( tmpfile, target ))) return ERROR_OUTOFMEMORY;
1120 
1121     TRACE("installing %s concurrently\n", debugstr_w(source));
1122 
1123     handle = execute_command( L"msiexec", args, L"C:\\" );
1124     msi_free( args );
1125     if (handle == INVALID_HANDLE_VALUE) return ERROR_SUCCESS;
1126     return wait_process_handle( package, type, handle, action );
1127 
1128 error:
1129     DeleteFileW( tmpfile );
1130     msi_free( tmpfile );
1131     return ERROR_FUNCTION_FAILED;
1132 }
1133 
1134 static UINT HANDLE_CustomType50( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
1135                                  INT type, const WCHAR *action )
1136 {
1137     WCHAR *exe, *arg;
1138     HANDLE handle;
1139 
1140     if (!(exe = msi_dup_property( package->db, source ))) return ERROR_SUCCESS;
1141 
1142     deformat_string( package, target, &arg );
1143     TRACE("exe %s arg %s\n", debugstr_w(exe), debugstr_w(arg));
1144 
1145     handle = execute_command( exe, arg, L"C:\\" );
1146     msi_free( exe );
1147     msi_free( arg );
1148     if (handle == INVALID_HANDLE_VALUE) return ERROR_SUCCESS;
1149     return wait_process_handle( package, type, handle, action );
1150 }
1151 
1152 static UINT HANDLE_CustomType34( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
1153                                  INT type, const WCHAR *action )
1154 {
1155     const WCHAR *workingdir = NULL;
1156     HANDLE handle;
1157     WCHAR *cmd;
1158 
1159     if (source)
1160     {
1161         workingdir = msi_get_target_folder( package, source );
1162         if (!workingdir) return ERROR_FUNCTION_FAILED;
1163     }
1164     deformat_string( package, target, &cmd );
1165     if (!cmd) return ERROR_FUNCTION_FAILED;
1166 
1167     TRACE("cmd %s dir %s\n", debugstr_w(cmd), debugstr_w(workingdir));
1168 
1169     handle = execute_command( NULL, cmd, workingdir );
1170     msi_free( cmd );
1171     if (handle == INVALID_HANDLE_VALUE) return ERROR_SUCCESS;
1172     return wait_process_handle( package, type, handle, action );
1173 }
1174 
1175 static DWORD ACTION_CallScript( const GUID *guid )
1176 {
1177     msi_custom_action_info *info;
1178     MSIHANDLE hPackage;
1179     UINT r = ERROR_FUNCTION_FAILED;
1180 
1181     info = find_action_by_guid( guid );
1182     if (!info)
1183     {
1184         ERR("failed to find action %s\n", debugstr_guid( guid) );
1185         return ERROR_FUNCTION_FAILED;
1186     }
1187 
1188     TRACE("function %s, script %s\n", debugstr_w( info->target ), debugstr_w( info->source ) );
1189 
1190     hPackage = alloc_msihandle( &info->package->hdr );
1191     if (hPackage)
1192     {
1193         r = call_script( hPackage, info->type, info->source, info->target, info->action );
1194         TRACE("script returned %u\n", r);
1195         MsiCloseHandle( hPackage );
1196     }
1197     else
1198         ERR("failed to create handle for %p\n", info->package );
1199 
1200     return r;
1201 }
1202 
1203 static DWORD WINAPI ScriptThread( LPVOID arg )
1204 {
1205     LPGUID guid = arg;
1206     DWORD rc;
1207 
1208     TRACE("custom action (%x) started\n", GetCurrentThreadId() );
1209 
1210     rc = ACTION_CallScript( guid );
1211 
1212     TRACE("custom action (%x) returned %i\n", GetCurrentThreadId(), rc );
1213 
1214     MsiCloseAllHandles();
1215     return rc;
1216 }
1217 
1218 static msi_custom_action_info *do_msidbCustomActionTypeScript(
1219     MSIPACKAGE *package, INT type, LPCWSTR script, LPCWSTR function, LPCWSTR action )
1220 {
1221     msi_custom_action_info *info;
1222 
1223     info = msi_alloc( sizeof *info );
1224     if (!info)
1225         return NULL;
1226 
1227     msiobj_addref( &package->hdr );
1228     info->package = package;
1229     info->type = type;
1230     info->target = strdupW( function );
1231     info->source = strdupW( script );
1232     info->action = strdupW( action );
1233     CoCreateGuid( &info->guid );
1234 
1235     EnterCriticalSection( &msi_custom_action_cs );
1236     list_add_tail( &msi_pending_custom_actions, &info->entry );
1237     LeaveCriticalSection( &msi_custom_action_cs );
1238 
1239     info->handle = CreateThread( NULL, 0, ScriptThread, &info->guid, 0, NULL );
1240     if (!info->handle)
1241     {
1242         free_custom_action_data( info );
1243         return NULL;
1244     }
1245 
1246     return info;
1247 }
1248 
1249 static UINT HANDLE_CustomType37_38( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
1250                                     INT type, const WCHAR *action )
1251 {
1252     msi_custom_action_info *info;
1253 
1254     TRACE("%s %s\n", debugstr_w(source), debugstr_w(target));
1255 
1256     info = do_msidbCustomActionTypeScript( package, type, target, NULL, action );
1257     return wait_thread_handle( info );
1258 }
1259 
1260 static UINT HANDLE_CustomType5_6( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
1261                                   INT type, const WCHAR *action )
1262 {
1263     MSIRECORD *row = NULL;
1264     msi_custom_action_info *info;
1265     CHAR *buffer = NULL;
1266     WCHAR *bufferw = NULL;
1267     DWORD sz = 0;
1268     UINT r;
1269 
1270     TRACE("%s %s\n", debugstr_w(source), debugstr_w(target));
1271 
1272     row = MSI_QueryGetRecord(package->db, L"SELECT * FROM `Binary` WHERE `Name` = '%s'", source);
1273     if (!row)
1274         return ERROR_FUNCTION_FAILED;
1275 
1276     r = MSI_RecordReadStream(row, 2, NULL, &sz);
1277     if (r != ERROR_SUCCESS) goto done;
1278 
1279     buffer = msi_alloc( sz + 1 );
1280     if (!buffer)
1281     {
1282        r = ERROR_FUNCTION_FAILED;
1283        goto done;
1284     }
1285 
1286     r = MSI_RecordReadStream(row, 2, buffer, &sz);
1287     if (r != ERROR_SUCCESS)
1288         goto done;
1289 
1290     buffer[sz] = 0;
1291     bufferw = strdupAtoW(buffer);
1292     if (!bufferw)
1293     {
1294         r = ERROR_FUNCTION_FAILED;
1295         goto done;
1296     }
1297 
1298     info = do_msidbCustomActionTypeScript( package, type, bufferw, target, action );
1299     r = wait_thread_handle( info );
1300 
1301 done:
1302     msi_free(bufferw);
1303     msi_free(buffer);
1304     msiobj_release(&row->hdr);
1305     return r;
1306 }
1307 
1308 static UINT HANDLE_CustomType21_22( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
1309                                     INT type, const WCHAR *action )
1310 {
1311     msi_custom_action_info *info;
1312     MSIFILE *file;
1313     HANDLE hFile;
1314     DWORD sz, szHighWord = 0, read;
1315     CHAR *buffer=NULL;
1316     WCHAR *bufferw=NULL;
1317     BOOL bRet;
1318     UINT r;
1319 
1320     TRACE("%s %s\n", debugstr_w(source), debugstr_w(target));
1321 
1322     file = msi_get_loaded_file(package, source);
1323     if (!file)
1324     {
1325         ERR("invalid file key %s\n", debugstr_w(source));
1326         return ERROR_FUNCTION_FAILED;
1327     }
1328 
1329     hFile = msi_create_file( package, file->TargetPath, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, 0 );
1330     if (hFile == INVALID_HANDLE_VALUE) return ERROR_FUNCTION_FAILED;
1331 
1332     sz = GetFileSize(hFile, &szHighWord);
1333     if (sz == INVALID_FILE_SIZE || szHighWord != 0)
1334     {
1335         CloseHandle(hFile);
1336         return ERROR_FUNCTION_FAILED;
1337     }
1338     buffer = msi_alloc( sz + 1 );
1339     if (!buffer)
1340     {
1341         CloseHandle(hFile);
1342         return ERROR_FUNCTION_FAILED;
1343     }
1344     bRet = ReadFile(hFile, buffer, sz, &read, NULL);
1345     CloseHandle(hFile);
1346     if (!bRet)
1347     {
1348         r = ERROR_FUNCTION_FAILED;
1349         goto done;
1350     }
1351     buffer[read] = 0;
1352     bufferw = strdupAtoW(buffer);
1353     if (!bufferw)
1354     {
1355         r = ERROR_FUNCTION_FAILED;
1356         goto done;
1357     }
1358     info = do_msidbCustomActionTypeScript( package, type, bufferw, target, action );
1359     r = wait_thread_handle( info );
1360 
1361 done:
1362     msi_free(bufferw);
1363     msi_free(buffer);
1364     return r;
1365 }
1366 
1367 static UINT HANDLE_CustomType53_54( MSIPACKAGE *package, const WCHAR *source, const WCHAR *target,
1368                                     INT type, const WCHAR *action )
1369 {
1370     msi_custom_action_info *info;
1371     WCHAR *prop;
1372 
1373     TRACE("%s %s\n", debugstr_w(source), debugstr_w(target));
1374 
1375     prop = msi_dup_property( package->db, source );
1376     if (!prop) return ERROR_SUCCESS;
1377 
1378     info = do_msidbCustomActionTypeScript( package, type, prop, NULL, action );
1379     msi_free(prop);
1380     return wait_thread_handle( info );
1381 }
1382 
1383 static BOOL action_type_matches_script( UINT type, UINT script )
1384 {
1385     switch (script)
1386     {
1387     case SCRIPT_NONE:
1388         return FALSE;
1389     case SCRIPT_INSTALL:
1390         return !(type & msidbCustomActionTypeCommit) && !(type & msidbCustomActionTypeRollback);
1391     case SCRIPT_COMMIT:
1392         return (type & msidbCustomActionTypeCommit);
1393     case SCRIPT_ROLLBACK:
1394         return (type & msidbCustomActionTypeRollback);
1395     default:
1396         ERR("unhandled script %u\n", script);
1397     }
1398     return FALSE;
1399 }
1400 
1401 static UINT defer_custom_action( MSIPACKAGE *package, const WCHAR *action, UINT type )
1402 {
1403     WCHAR *actiondata = msi_dup_property( package->db, action );
1404     WCHAR *usersid = msi_dup_property( package->db, L"UserSID" );
1405     WCHAR *prodcode = msi_dup_property( package->db, L"ProductCode" );
1406     WCHAR *deferred = msi_get_deferred_action( action, actiondata, usersid, prodcode );
1407 
1408     if (!deferred)
1409     {
1410         msi_free( actiondata );
1411         msi_free( usersid );
1412         msi_free( prodcode );
1413         return ERROR_OUTOFMEMORY;
1414     }
1415     if (type & msidbCustomActionTypeCommit)
1416     {
1417         TRACE("deferring commit action\n");
1418         msi_schedule_action( package, SCRIPT_COMMIT, deferred );
1419     }
1420     else if (type & msidbCustomActionTypeRollback)
1421     {
1422         TRACE("deferring rollback action\n");
1423         msi_schedule_action( package, SCRIPT_ROLLBACK, deferred );
1424     }
1425     else
1426     {
1427         TRACE("deferring install action\n");
1428         msi_schedule_action( package, SCRIPT_INSTALL, deferred );
1429     }
1430 
1431     msi_free( actiondata );
1432     msi_free( usersid );
1433     msi_free( prodcode );
1434     msi_free( deferred );
1435     return ERROR_SUCCESS;
1436 }
1437 
1438 UINT ACTION_CustomAction(MSIPACKAGE *package, const WCHAR *action)
1439 {
1440     UINT rc = ERROR_SUCCESS;
1441     MSIRECORD *row;
1442     UINT type;
1443     const WCHAR *source, *target, *ptr, *deferred_data = NULL;
1444     WCHAR *deformated = NULL;
1445     int len;
1446 
1447     /* deferred action: [properties]Action */
1448     if ((ptr = wcsrchr(action, ']')))
1449     {
1450         deferred_data = action;
1451         action = ptr + 1;
1452     }
1453 
1454     row = MSI_QueryGetRecord( package->db, L"SELECT * FROM `CustomAction` WHERE `Action` = '%s'", action );
1455     if (!row)
1456         return ERROR_FUNCTION_NOT_CALLED;
1457 
1458     type = MSI_RecordGetInteger(row,2);
1459     source = MSI_RecordGetString(row,3);
1460     target = MSI_RecordGetString(row,4);
1461 
1462     TRACE("Handling custom action %s (%x %s %s)\n",debugstr_w(action),type,
1463           debugstr_w(source), debugstr_w(target));
1464 
1465     /* handle some of the deferred actions */
1466     if (type & msidbCustomActionTypeTSAware)
1467         FIXME("msidbCustomActionTypeTSAware not handled\n");
1468 
1469     if (type & msidbCustomActionTypeInScript)
1470     {
1471         if (type & msidbCustomActionTypeNoImpersonate)
1472             WARN("msidbCustomActionTypeNoImpersonate not handled\n");
1473 
1474         if (!action_type_matches_script(type, package->script))
1475         {
1476             rc = defer_custom_action( package, action, type );
1477             goto end;
1478         }
1479         else
1480         {
1481             LPWSTR actiondata = msi_dup_property( package->db, action );
1482 
1483             if (type & msidbCustomActionTypeInScript)
1484                 package->scheduled_action_running = TRUE;
1485 
1486             if (type & msidbCustomActionTypeCommit)
1487                 package->commit_action_running = TRUE;
1488 
1489             if (type & msidbCustomActionTypeRollback)
1490                 package->rollback_action_running = TRUE;
1491 
1492             if (deferred_data)
1493                 set_deferred_action_props(package, deferred_data);
1494             else if (actiondata)
1495                 msi_set_property( package->db, L"CustomActionData", actiondata, -1 );
1496             else
1497                 msi_set_property( package->db, L"CustomActionData", L"", -1 );
1498 
1499             msi_free(actiondata);
1500         }
1501     }
1502     else if (!check_execution_scheduling_options(package,action,type))
1503     {
1504         rc = ERROR_SUCCESS;
1505         goto end;
1506     }
1507 
1508     switch (type & CUSTOM_ACTION_TYPE_MASK)
1509     {
1510     case 1: /* DLL file stored in a Binary table stream */
1511         rc = HANDLE_CustomType1( package, source, target, type, action );
1512         break;
1513     case 2: /* EXE file stored in a Binary table stream */
1514         rc = HANDLE_CustomType2( package, source, target, type, action );
1515         break;
1516     case 5:
1517     case 6: /* JScript/VBScript file stored in a Binary table stream */
1518         rc = HANDLE_CustomType5_6( package, source, target, type, action );
1519         break;
1520     case 7: /* Concurrent install from substorage */
1521         deformat_string( package, target, &deformated );
1522         rc = HANDLE_CustomType7( package, source, target, type, action );
1523         msi_free( deformated );
1524         break;
1525     case 17:
1526         rc = HANDLE_CustomType17( package, source, target, type, action );
1527         break;
1528     case 18: /* EXE file installed with package */
1529         rc = HANDLE_CustomType18( package, source, target, type, action );
1530         break;
1531     case 19: /* Error that halts install */
1532         rc = HANDLE_CustomType19( package, source, target, type, action );
1533         break;
1534     case 21: /* JScript/VBScript file installed with the product */
1535     case 22:
1536         rc = HANDLE_CustomType21_22( package, source, target, type, action );
1537         break;
1538     case 23: /* Installs another package in the source tree */
1539         deformat_string( package, target, &deformated );
1540         rc = HANDLE_CustomType23( package, source, deformated, type, action );
1541         msi_free( deformated );
1542         break;
1543     case 34: /* EXE to be run in specified directory */
1544         rc = HANDLE_CustomType34( package, source, target, type, action );
1545         break;
1546     case 35: /* Directory set with formatted text */
1547         deformat_string( package, target, &deformated );
1548         MSI_SetTargetPathW( package, source, deformated );
1549         msi_free( deformated );
1550         break;
1551     case 37: /* JScript/VBScript text stored in target column */
1552     case 38:
1553         rc = HANDLE_CustomType37_38( package, source, target, type, action );
1554         break;
1555     case 50: /* EXE file specified by a property value */
1556         rc = HANDLE_CustomType50( package, source, target, type, action );
1557         break;
1558     case 51: /* Property set with formatted text */
1559         if (!source) break;
1560         len = deformat_string( package, target, &deformated );
1561         rc = msi_set_property( package->db, source, deformated, len );
1562         if (rc == ERROR_SUCCESS && !wcscmp( source, L"SourceDir" )) msi_reset_source_folders( package );
1563         msi_free( deformated );
1564         break;
1565     case 53: /* JScript/VBScript text specified by a property value */
1566     case 54:
1567         rc = HANDLE_CustomType53_54( package, source, target, type, action );
1568         break;
1569     default:
1570         FIXME( "unhandled action type %u (%s %s)\n", type & CUSTOM_ACTION_TYPE_MASK, debugstr_w(source),
1571                debugstr_w(target) );
1572     }
1573 
1574 end:
1575     package->scheduled_action_running = FALSE;
1576     package->commit_action_running = FALSE;
1577     package->rollback_action_running = FALSE;
1578     msiobj_release(&row->hdr);
1579     return rc;
1580 }
1581 
1582 void ACTION_FinishCustomActions(const MSIPACKAGE* package)
1583 {
1584     struct list *item;
1585     HANDLE *wait_handles;
1586     unsigned int handle_count, i;
1587     msi_custom_action_info *info, *cursor;
1588 
1589     while ((item = list_head( &package->RunningActions )))
1590     {
1591         MSIRUNNINGACTION *action = LIST_ENTRY( item, MSIRUNNINGACTION, entry );
1592 
1593         list_remove( &action->entry );
1594 
1595         TRACE("waiting for %s\n", debugstr_w( action->name ) );
1596         msi_dialog_check_messages( action->handle );
1597 
1598         CloseHandle( action->handle );
1599         msi_free( action->name );
1600         msi_free( action );
1601     }
1602 
1603     EnterCriticalSection( &msi_custom_action_cs );
1604 
1605     handle_count = list_count( &msi_pending_custom_actions );
1606     wait_handles = msi_alloc( handle_count * sizeof(HANDLE) );
1607 
1608     handle_count = 0;
1609     LIST_FOR_EACH_ENTRY_SAFE( info, cursor, &msi_pending_custom_actions, msi_custom_action_info, entry )
1610     {
1611         if (info->package == package )
1612         {
1613             if (DuplicateHandle(GetCurrentProcess(), info->handle, GetCurrentProcess(), &wait_handles[handle_count], SYNCHRONIZE, FALSE, 0))
1614                 handle_count++;
1615         }
1616     }
1617 
1618     LeaveCriticalSection( &msi_custom_action_cs );
1619 
1620     for (i = 0; i < handle_count; i++)
1621     {
1622         msi_dialog_check_messages( wait_handles[i] );
1623         CloseHandle( wait_handles[i] );
1624     }
1625     msi_free( wait_handles );
1626 
1627     EnterCriticalSection( &msi_custom_action_cs );
1628     LIST_FOR_EACH_ENTRY_SAFE( info, cursor, &msi_pending_custom_actions, msi_custom_action_info, entry )
1629     {
1630         if (info->package == package)
1631             free_custom_action_data( info );
1632     }
1633     LeaveCriticalSection( &msi_custom_action_cs );
1634 }
1635 
1636 UINT __cdecl s_remote_GetActionInfo(const GUID *guid, int *type, LPWSTR *dll, LPSTR *func, MSIHANDLE *hinst)
1637 {
1638     msi_custom_action_info *info;
1639 
1640     info = find_action_by_guid(guid);
1641     if (!info)
1642         return ERROR_INVALID_DATA;
1643 
1644     *type = info->type;
1645     *hinst = alloc_msihandle(&info->package->hdr);
1646     *dll = strdupW(info->source);
1647     *func = strdupWtoA(info->target);
1648 
1649     return ERROR_SUCCESS;
1650 }
1651