Debian Codegraph @

win/packaging/ca/CustomAction.cpp

raw
1 /* Copyright 2010, Oracle and/or its affiliates. All rights reserved.
2
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; version 2 of the License.
6
7 This program is distributed in the hope that it will be useful,
8 but WITHOUT ANY WARRANTY; without even the implied warranty of
9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 GNU General Public License for more details.
11
12 You should have received a copy of the GNU General Public License
13 along with this program; if not, write to the Free Software
14 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */
15
16 #ifndef UNICODE
17 #define UNICODE
18 #endif
19
20 #undef NOMINMAX
21
22 #include <winsock2.h>
23 #include <ws2tcpip.h>
24 #include <windows.h>
25 #include <winreg.h>
26 #include <msi.h>
27 #include <msiquery.h>
28 #include <wcautil.h>
29 #include <strutil.h>
30 #include <string.h>
31 #include <strsafe.h>
32 #include <assert.h>
33 #include <shellapi.h>
34 #include <stdlib.h>
35 #include <winservice.h>
36 #include <string>
37 #include <iostream>
38 #include <fstream>
39 #include <sstream>
40 #include <vector>
41 #include <map>
42
43 using namespace std;
44
45
46 #define ONE_MB 1048576
47 UINT ExecRemoveDataDirectory(wchar_t *dir)
48 {
49 /* Strip stray backslash */
50 DWORD len = (DWORD)wcslen(dir);
51 if(len > 0 && dir[len-1]==L'\\')
52 dir[len-1] = 0;
53
54 SHFILEOPSTRUCTW fileop;
55 fileop.hwnd= NULL; /* no status display */
56 fileop.wFunc= FO_DELETE; /* delete operation */
57 fileop.pFrom= dir; /* source file name as double null terminated string */
58 fileop.pTo= NULL; /* no destination needed */
59 fileop.fFlags= FOF_NOCONFIRMATION|FOF_SILENT; /* do not prompt the user */
60
61 fileop.fAnyOperationsAborted= FALSE;
62 fileop.lpszProgressTitle= NULL;
63 fileop.hNameMappings= NULL;
64
65 return SHFileOperationW(&fileop);
66 }
67
68
69 extern "C" UINT __stdcall RemoveDataDirectory(MSIHANDLE hInstall)
70 {
71 HRESULT hr = S_OK;
72 UINT er = ERROR_SUCCESS;
73 wchar_t dir[MAX_PATH];
74 DWORD len = MAX_PATH;
75
76 hr = WcaInitialize(hInstall, __FUNCTION__);
77 ExitOnFailure(hr, "Failed to initialize");
78 WcaLog(LOGMSG_STANDARD, "Initialized.");
79
80 MsiGetPropertyW(hInstall, L"CustomActionData", dir, &len);
81
82 er= ExecRemoveDataDirectory(dir);
83 WcaLog(LOGMSG_STANDARD, "SHFileOperation returned %d", er);
84 LExit:
85 return WcaFinalize(er);
86 }
87
88 /*
89 Escape command line parameter fpr pass to CreateProcess().
90
91 We assume out has enough space to include encoded string
92 2*wcslen(in) is enough.
93
94 It is assumed that called will add double quotation marks before and after
95 the string.
96 */
97 static void EscapeCommandLine(const wchar_t *in, wchar_t *out, size_t buflen)
98 {
99 const wchar_t special_chars[]=L" \t\n\v\"";
100 bool needs_escaping= false;
101 size_t pos;
102
103 for(size_t i=0; i< sizeof(special_chars) -1; i++)
104 {
105 if (wcschr(in, special_chars[i]))
106 {
107 needs_escaping = true;
108 break;
109 }
110 }
111
112 if(!needs_escaping)
113 {
114 wcscpy_s(out, buflen, in);
115 return;
116 }
117
118 pos= 0;
119 for(int i = 0 ; ; i++)
120 {
121 size_t n_backslashes = 0;
122 wchar_t c;
123 while (in[i] == L'\\')
124 {
125 i++;
126 n_backslashes++;
127 }
128
129 c= in[i];
130 if (c == 0)
131 {
132 /*
133 Escape all backslashes, but let the terminating double quotation mark
134 that caller adds be interpreted as a metacharacter.
135 */
136 for(size_t j= 0; j < 2*n_backslashes;j++)
137 {
138 out[pos++]=L'\\';
139 }
140 break;
141 }
142 else if (c == L'"')
143 {
144 /*
145 Escape all backslashes and the following double quotation mark.
146 */
147 for(size_t j= 0; j < 2*n_backslashes + 1; j++)
148 {
149 out[pos++]=L'\\';
150 }
151 out[pos++]= L'"';
152 }
153 else
154 {
155 /* Backslashes aren't special here. */
156 for (size_t j=0; j < n_backslashes; j++)
157 out[pos++] = L'\\';
158
159 out[pos++]= c;
160 }
161 }
162 out[pos++]= 0;
163 }
164
165 bool IsDirectoryEmptyOrNonExisting(const wchar_t *dir) {
166 wchar_t wildcard[MAX_PATH+3];
167 WIN32_FIND_DATAW data;
168 HANDLE h;
169 wcscpy_s(wildcard, MAX_PATH, dir);
170 wcscat_s(wildcard, MAX_PATH, L"*.*");
171 bool empty= true;
172 h= FindFirstFile(wildcard, &data);
173 if (h != INVALID_HANDLE_VALUE)
174 {
175 for (;;)
176 {
177 if (wcscmp(data.cFileName, L".") && wcscmp(data.cFileName, L".."))
178 {
179 empty= false;
180 break;
181 }
182 if (!FindNextFile(h, &data))
183 break;
184 }
185 FindClose(h);
186 }
187 return empty;
188 }
189
190 extern "C" UINT __stdcall CheckInstallDirectory(MSIHANDLE hInstall)
191 {
192 HRESULT hr= S_OK;
193 UINT er= ERROR_SUCCESS;
194 wchar_t *path= 0;
195
196 hr= WcaInitialize(hInstall, __FUNCTION__);
197 ExitOnFailure(hr, "Failed to initialize");
198 WcaGetFormattedString(L"[INSTALLDIR]", &path);
199 if (!IsDirectoryEmptyOrNonExisting(path))
200 {
201 wchar_t msg[2*MAX_PATH];
202 swprintf(msg,countof(msg), L"Installation directory '%s' exists and is not empty. Choose a "
203 "different install directory",path);
204 WcaSetProperty(L"INSTALLDIRERROR", msg);
205 goto LExit;
206 }
207
208 WcaSetProperty(L"INSTALLDIRERROR", L"");
209
210 LExit:
211 ReleaseStr(path);
212 return WcaFinalize(er);
213 }
214
215 /*
216 Check for valid data directory is empty during install
217 A valid data directory is non-existing, or empty.
218
219 In addition, it must be different from any directories that
220 are going to be installed. This is required. because the full
221 directory is removed on a feature uninstall, and we do not want
222 it to be lib or bin.
223 */
224 extern "C" UINT __stdcall CheckDataDirectory(MSIHANDLE hInstall)
225 {
226 HRESULT hr= S_OK;
227 UINT er= ERROR_SUCCESS;
228 wchar_t datadir[MAX_PATH];
229 DWORD len= MAX_PATH;
230 bool empty;
231 wchar_t *path= 0;
232
233 MsiGetPropertyW(hInstall, L"DATADIR", datadir, &len);
234 hr= WcaInitialize(hInstall, __FUNCTION__);
235 ExitOnFailure(hr, "Failed to initialize");
236 WcaLog(LOGMSG_STANDARD, "Initialized.");
237
238 WcaLog(LOGMSG_STANDARD, "Checking files in %S", datadir);
239 empty= IsDirectoryEmptyOrNonExisting(datadir);
240 if (empty)
241 WcaLog(LOGMSG_STANDARD, "DATADIR is empty or non-existent");
242 else
243 WcaLog(LOGMSG_STANDARD, "DATADIR is NOT empty");
244
245 if (!empty)
246 {
247 WcaSetProperty(L"DATADIRERROR", L"data directory exist and not empty");
248 goto LExit;
249 }
250 WcaSetProperty(L"DATADIRERROR", L"");
251
252
253 WcaGetFormattedString(L"[INSTALLDIR]",&path);
254 if (path && !wcsicmp(datadir, path))
255 {
256 WcaSetProperty(L"DATADIRERROR", L"data directory can not be "
257 L"installation root directory");
258 ReleaseStr(path);
259 goto LExit;
260 }
261 for (auto dir :
262 {L"[INSTALLDIR]bin\\", L"[INSTALLDIR]include\\",
263 L"[INSTALLDIR]lib\\", L"[INSTALLDIR]share\\"})
264 {
265 WcaGetFormattedString(dir, &path);
266 if (path && !wcsnicmp(datadir, path, wcslen(path)))
267 {
268 const wchar_t *subdir= dir + sizeof("[INSTALLDIR]") - 1;
269 wchar_t msg[MAX_PATH]= L"data directory conflicts with '";
270 wcsncat_s(msg, subdir, wcslen(subdir) - 1);
271 wcscat_s(msg, L"' directory, which is part of this installation");
272 WcaSetProperty(L"DATADIRERROR", msg);
273 ReleaseStr(path);
274 goto LExit;
275 }
276 ReleaseStr(path);
277 path= 0;
278 }
279 LExit:
280 return WcaFinalize(er);
281 }
282
283
284 bool CheckServiceExists(const wchar_t *name)
285 {
286 SC_HANDLE manager =0, service=0;
287 manager = OpenSCManager( NULL, NULL, SC_MANAGER_CONNECT);
288 if (!manager)
289 {
290 return false;
291 }
292
293 service = OpenService(manager, name, SC_MANAGER_CONNECT);
294 if(service)
295 CloseServiceHandle(service);
296 CloseServiceHandle(manager);
297
298 return service?true:false;
299 }
300
301 /* User in rollback of create database custom action */
302 bool ExecRemoveService(const wchar_t *name)
303 {
304 SC_HANDLE manager =0, service=0;
305 manager = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS);
306 bool ret;
307 if (!manager)
308 {
309 return false;
310 }
311 service = OpenService(manager, name, DELETE);
312 if(service)
313 {
314 ret= DeleteService(service);
315 }
316 else
317 {
318 ret= false;
319 }
320 CloseServiceHandle(manager);
321 return ret;
322 }
323
324 /* Find whether TCP port is in use by trying to bind to the port. */
325 static bool IsPortInUse(unsigned short port)
326 {
327 struct addrinfo* ai, * a;
328 struct addrinfo hints {};
329
330 char port_buf[NI_MAXSERV];
331 SOCKET ip_sock = INVALID_SOCKET;
332 hints.ai_flags = AI_PASSIVE;
333 hints.ai_socktype = SOCK_STREAM;
334 hints.ai_family = AF_UNSPEC;
335 snprintf(port_buf, NI_MAXSERV, "%u", (unsigned)port);
336
337 if (getaddrinfo(NULL, port_buf, &hints, &ai))
338 {
339 return false;
340 }
341
342 /*
343 Prefer IPv6 socket to IPv4, since we'll use IPv6 dual socket,
344 which coveres both IP versions.
345 */
346 for (a = ai; a; a = a->ai_next)
347 {
348 if (a->ai_family == AF_INET6 &&
349 (ip_sock = socket(a->ai_family, a->ai_socktype, a->ai_protocol)) != INVALID_SOCKET)
350 {
351 break;
352 }
353 }
354
355 if (ip_sock == INVALID_SOCKET)
356 {
357 for (a = ai; a; a = a->ai_next)
358 {
359 if (ai->ai_family == AF_INET &&
360 (ip_sock = socket(a->ai_family, a->ai_socktype, a->ai_protocol)) != INVALID_SOCKET)
361 {
362 break;
363 }
364 }
365 }
366
367 if (ip_sock == INVALID_SOCKET)
368 {
369 return false;
370 }
371
372 /* Use SO_EXCLUSIVEADDRUSE to prevent multiple binding. */
373 int arg = 1;
374 setsockopt(ip_sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&arg, sizeof(arg));
375
376 /* Allow dual socket, so that IPv4 and IPv6 are both covered.*/
377 if (a->ai_family == AF_INET6)
378 {
379 arg = 0;
380 setsockopt(ip_sock, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&arg, sizeof(arg));
381 }
382
383 bool in_use = false;
384 if (bind(ip_sock, a->ai_addr, (int)a->ai_addrlen) == SOCKET_ERROR)
385 {
386 DWORD last_error = WSAGetLastError();
387 in_use = (last_error == WSAEADDRINUSE || last_error == WSAEACCES);
388 }
389
390 freeaddrinfo(ai);
391 closesocket(ip_sock);
392 return in_use;
393 }
394
395
396 /*
397 Check if TCP port is free
398 */
399 bool IsPortFree(unsigned short port)
400 {
401 WORD wVersionRequested = MAKEWORD(2, 2);
402 WSADATA wsaData;
403 WSAStartup(wVersionRequested, &wsaData);
404 bool in_use = IsPortInUse(port);
405 WSACleanup();
406 return !in_use;
407 }
408
409
410 /*
411 Helper function used in filename normalization.
412 Removes leading quote and terminates string at the position of the next one
413 (if applicable, does not change string otherwise). Returns modified string
414 */
415 wchar_t *strip_quotes(wchar_t *s)
416 {
417 if (s && (*s == L'"'))
418 {
419 s++;
420 wchar_t *p = wcschr(s, L'"');
421 if(p)
422 *p = 0;
423 }
424 return s;
425 }
426
427
428 /*
429 Checks for consistency of service configuration.
430
431 It can happen that SERVICENAME or DATADIR
432 MSI properties are in inconsistent state after somebody upgraded database
433 We catch this case during uninstall. In particular, either service is not
434 removed even if SERVICENAME was set (but this name is reused by someone else)
435 or data directory is not removed (if it is used by someone else). To find out
436 whether service name and datadirectory are in use For every service,
437 configuration is read and checked as follows:
438
439 - look if a service has to do something with mysql
440 - If so, check its name against SERVICENAME. if match, check binary path
441 against INSTALLDIR\bin. If binary path does not match, then service runs
442 under different installation and won't be removed.
443 - Check options file for datadir and look if this is inside this
444 installation's datadir don't remove datadir if this is the case.
445
446 "Don't remove" in this context means that custom action is removing
447 SERVICENAME property or CLEANUPDATA property, which later on in course of
448 installation mean, that either datadir or service is kept.
449 */
450
451 void CheckServiceConfig(
452 wchar_t *my_servicename, /* SERVICENAME property in this installation*/
453 wchar_t *datadir, /* DATADIR property in this installation*/
454 wchar_t *bindir, /* INSTALLDIR\bin */
455 wchar_t *other_servicename, /* Service to check against */
456 QUERY_SERVICE_CONFIGW * config /* Other service's config */
457 )
458 {
459
460 bool same_bindir = false;
461 wchar_t * commandline= config->lpBinaryPathName;
462 int numargs;
463 wchar_t **argv= CommandLineToArgvW(commandline, &numargs);
464 wchar_t current_datadir_buf[MAX_PATH]={0};
465 wchar_t normalized_current_datadir[MAX_PATH+1];
466 wchar_t *current_datadir;
467 wchar_t *defaults_file;
468 bool is_my_service;
469
470 WcaLog(LOGMSG_VERBOSE, "CommandLine= %S", commandline);
471 if(!argv || !argv[0] || ! wcsstr(argv[0], L"mysqld"))
472 {
473 goto end;
474 }
475
476 WcaLog(LOGMSG_STANDARD, "MySQL/MariaDB service %S found: CommandLine= %S",
477 other_servicename, commandline);
478 if (wcsstr(argv[0], bindir))
479 {
480 WcaLog(LOGMSG_STANDARD, "executable under bin directory");
481 same_bindir = true;
482 }
483
484 is_my_service = (_wcsicmp(my_servicename, other_servicename) == 0);
485 if(!is_my_service)
486 {
487 WcaLog(LOGMSG_STANDARD, "service does not match current service");
488 /*
489 TODO probably the best thing possible would be to add temporary
490 row to MSI ServiceConfig table with remove on uninstall
491 */
492 }
493 else if (!same_bindir)
494 {
495 WcaLog(LOGMSG_STANDARD,
496 "Service name matches, but not the executable path directory, mine is %S",
497 bindir);
498 WcaSetProperty(L"SERVICENAME", L"");
499 }
500
501 /* Check if data directory is used */
502 if(!datadir || numargs <= 1 || wcsncmp(argv[1],L"--defaults-file=",16) != 0)
503 {
504 goto end;
505 }
506
507 current_datadir= current_datadir_buf;
508 defaults_file= argv[1]+16;
509 defaults_file= strip_quotes(defaults_file);
510
511 WcaLog(LOGMSG_STANDARD, "parsed defaults file is %S", defaults_file);
512
513 if (GetPrivateProfileStringW(L"mysqld", L"datadir", NULL, current_datadir,
514 MAX_PATH, defaults_file) == 0)
515 {
516 WcaLog(LOGMSG_STANDARD,
517 "Cannot find datadir in ini file '%S'", defaults_file);
518 goto end;
519 }
520
521 WcaLog(LOGMSG_STANDARD, "datadir from defaults-file is %S", current_datadir);
522 strip_quotes(current_datadir);
523
524 /* Convert to Windows path */
525 if (GetFullPathNameW(current_datadir, MAX_PATH, normalized_current_datadir,
526 NULL))
527 {
528 /* Add backslash to be compatible with directory formats in MSI */
529 wcsncat(normalized_current_datadir, L"\\", MAX_PATH+1);
530 WcaLog(LOGMSG_STANDARD, "normalized current datadir is '%S'",
531 normalized_current_datadir);
532 }
533
534 if (_wcsicmp(datadir, normalized_current_datadir) == 0 && !same_bindir)
535 {
536 WcaLog(LOGMSG_STANDARD,
537 "database directory from current installation, but different mysqld.exe");
538 WcaSetProperty(L"CLEANUPDATA", L"");
539 }
540
541 end:
542 LocalFree((HLOCAL)argv);
543 }
544
545 /*
546 Checks if database directory or service are modified by user
547 For example, service may point to different mysqld.exe that it was originally
548 installed, or some different service might use this database directory. This
549 would normally mean user has done an upgrade of the database and in this case
550 uninstall should neither delete service nor database directory.
551
552 If this function find that service is modified by user (mysqld.exe used by
553 service does not point to the installation bin directory), MSI public variable
554 SERVICENAME is removed, if DATADIR is used by some other service, variables
555 DATADIR and CLEANUPDATA are removed.
556
557 The effect of variable removal is that service does not get uninstalled and
558 datadir is not touched by uninstallation.
559
560 Note that this function is running without elevation and does not use anything
561 that would require special privileges.
562
563 */
564 extern "C" UINT CheckDBInUse(MSIHANDLE hInstall)
565 {
566 static BYTE buf[256*1024]; /* largest possible buffer for EnumServices */
567 static char config_buffer[8*1024]; /*largest buffer for QueryServiceConfig */
568 HRESULT hr = S_OK;
569 UINT er = ERROR_SUCCESS;
570 wchar_t *servicename= NULL;
571 wchar_t *datadir= NULL;
572 wchar_t *bindir=NULL;
573
574 SC_HANDLE scm = NULL;
575 ULONG bufsize = sizeof(buf);
576 ULONG bufneed = 0x00;
577 ULONG num_services = 0x00;
578 LPENUM_SERVICE_STATUS_PROCESS info = NULL;
579 BOOL ok;
580
581 hr = WcaInitialize(hInstall, __FUNCTION__);
582 ExitOnFailure(hr, "Failed to initialize");
583 WcaLog(LOGMSG_STANDARD, "Initialized.");
584
585 WcaGetProperty(L"SERVICENAME", &servicename);
586 WcaGetProperty(L"DATADIR", &datadir);
587 WcaGetFormattedString(L"[INSTALLDIR]bin\\", &bindir);
588
589 WcaLog(LOGMSG_STANDARD,"SERVICENAME=%S, DATADIR=%S, bindir=%S",
590 servicename, datadir, bindir);
591
592 scm = OpenSCManager(NULL, NULL,
593 SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_CONNECT);
594 if (scm == NULL)
595 {
596 ExitOnFailure(E_FAIL, "OpenSCManager failed");
597 }
598
599 ok = EnumServicesStatusExW( scm,
600 SC_ENUM_PROCESS_INFO,
601 SERVICE_WIN32,
602 SERVICE_STATE_ALL,
603 buf,
604 bufsize,
605 &bufneed,
606 &num_services,
607 NULL,
608 NULL);
609 if(!ok)
610 {
611 WcaLog(LOGMSG_STANDARD, "last error %d", GetLastError());
612 ExitOnFailure(E_FAIL, "EnumServicesStatusExW failed");
613 }
614 info = (LPENUM_SERVICE_STATUS_PROCESS)buf;
615 for (ULONG i=0; i < num_services; i++)
616 {
617 SC_HANDLE service= OpenServiceW(scm, info[i].lpServiceName,
618 SERVICE_QUERY_CONFIG);
619 if (!service)
620 continue;
621 WcaLog(LOGMSG_VERBOSE, "Checking Service %S", info[i].lpServiceName);
622 QUERY_SERVICE_CONFIGW *config=
623 (QUERY_SERVICE_CONFIGW *)(void *)config_buffer;
624 DWORD needed;
625 BOOL ok= QueryServiceConfigW(service, config,sizeof(config_buffer),
626 &needed);
627 CloseServiceHandle(service);
628 if (ok)
629 {
630 CheckServiceConfig(servicename, datadir, bindir, info[i].lpServiceName,
631 config);
632 }
633 }
634
635 LExit:
636 if(scm)
637 CloseServiceHandle(scm);
638
639 ReleaseStr(servicename);
640 ReleaseStr(datadir);
641 ReleaseStr(bindir);
642 return WcaFinalize(er);
643 }
644
645 /*
646 Get maximum size of the buffer process can allocate.
647 this is calculated as min(RAM,virtualmemorylimit)
648 For 32bit processes, virtual address memory is 2GB (x86 OS)
649 or 4GB(x64 OS).
650
651 Fragmentation due to loaded modules, heap and stack
652 limit maximum size of continuous memory block further,
653 so that limit for 32 bit process is about 1200 on 32 bit OS
654 or 2000 MB on 64 bit OS(found experimentally).
655 */
656 unsigned long long GetMaxBufferSize(unsigned long long totalPhys)
657 {
658 #ifdef _M_IX86
659 BOOL wow64;
660 if (IsWow64Process(GetCurrentProcess(), &wow64))
661 return min(totalPhys, 2000ULL*ONE_MB);
662 else
663 return min(totalPhys, 1200ULL*ONE_MB);
664 #else
665 return totalPhys;
666 #endif
667 }
668
669
670 /*
671 Magic undocumented number for bufferpool minimum,
672 allows innodb to start also for all page sizes.
673 */
674 static constexpr unsigned long long minBufferpoolMB= 20;
675
676 /*
677 Checks SERVICENAME, PORT and BUFFERSIZE parameters
678 */
679 extern "C" UINT __stdcall CheckDatabaseProperties (MSIHANDLE hInstall)
680 {
681 wchar_t ServiceName[MAX_PATH]={0};
682 wchar_t SkipNetworking[MAX_PATH]={0};
683 wchar_t QuickConfig[MAX_PATH]={0};
684 wchar_t Password[MAX_PATH]={0};
685 wchar_t EscapedPassword[2*MAX_PATH+2];
686 wchar_t Port[6];
687 wchar_t BufferPoolSize[16];
688 DWORD PortLen=6;
689 bool haveInvalidPort=false;
690 const wchar_t *ErrorMsg=0;
691 HRESULT hr= S_OK;
692 UINT er= ERROR_SUCCESS;
693 DWORD ServiceNameLen = MAX_PATH;
694 DWORD QuickConfigLen = MAX_PATH;
695 DWORD PasswordLen= MAX_PATH;
696 DWORD SkipNetworkingLen= MAX_PATH;
697
698 hr = WcaInitialize(hInstall, __FUNCTION__);
699 ExitOnFailure(hr, "Failed to initialize");
700 WcaLog(LOGMSG_STANDARD, "Initialized.");
701
702
703 MsiGetPropertyW (hInstall, L"SERVICENAME", ServiceName, &ServiceNameLen);
704 if(ServiceName[0])
705 {
706 if(ServiceNameLen > 256)
707 {
708 ErrorMsg= L"Invalid service name. The maximum length is 256 characters.";
709 goto LExit;
710 }
711 for(DWORD i=0; i< ServiceNameLen;i++)
712 {
713 if(ServiceName[i] == L'\\' || ServiceName[i] == L'/'
714 || ServiceName[i]=='\'' || ServiceName[i] ==L'"')
715 {
716 ErrorMsg =
717 L"Invalid service name. Forward slash and back slash are forbidden."
718 L"Single and double quotes are also not permitted.";
719 goto LExit;
720 }
721 }
722 if(CheckServiceExists(ServiceName))
723 {
724 ErrorMsg=
725 L"A service with the same name already exists. "
726 L"Please use a different name.";
727 goto LExit;
728 }
729 }
730
731 MsiGetPropertyW (hInstall, L"PASSWORD", Password, &PasswordLen);
732 EscapeCommandLine(Password, EscapedPassword,
733 sizeof(EscapedPassword)/sizeof(EscapedPassword[0]));
734 MsiSetPropertyW(hInstall,L"ESCAPEDPASSWORD",EscapedPassword);
735
736 MsiGetPropertyW(hInstall, L"SKIPNETWORKING", SkipNetworking,
737 &SkipNetworkingLen);
738 MsiGetPropertyW(hInstall, L"PORT", Port, &PortLen);
739
740 if(SkipNetworking[0]==0 && Port[0] != 0)
741 {
742 /* Strip spaces */
743 for(DWORD i=PortLen-1; i > 0; i--)
744 {
745 if(Port[i]== ' ')
746 Port[i] = 0;
747 }
748
749 if(PortLen > 5 || PortLen <= 3)
750 haveInvalidPort = true;
751 else
752 {
753 for (DWORD i=0; i< PortLen && Port[i] != 0;i++)
754 {
755 if(Port[i] < '0' || Port[i] >'9')
756 {
757 haveInvalidPort=true;
758 break;
759 }
760 }
761 }
762 if (haveInvalidPort)
763 {
764 ErrorMsg =
765 L"Invalid port number. Please use a number between 1025 and 65535.";
766 goto LExit;
767 }
768
769 unsigned short port = (unsigned short)_wtoi(Port);
770 if (!IsPortFree(port))
771 {
772 ErrorMsg =
773 L"The TCP Port you selected is already in use. "
774 L"Please choose a different port.";
775 goto LExit;
776 }
777 }
778
779 MsiGetPropertyW (hInstall, L"STDCONFIG", QuickConfig, &QuickConfigLen);
780 if(QuickConfig[0] !=0)
781 {
782 MEMORYSTATUSEX memstatus;
783 memstatus.dwLength =sizeof(memstatus);
784 wchar_t invalidValueMsg[256];
785
786 if (!GlobalMemoryStatusEx(&memstatus))
787 {
788 WcaLog(LOGMSG_STANDARD, "Error %u from GlobalMemoryStatusEx",
789 GetLastError());
790 er= ERROR_INSTALL_FAILURE;
791 goto LExit;
792 }
793 DWORD BufferPoolSizeLen= 16;
794 MsiGetPropertyW(hInstall, L"BUFFERPOOLSIZE", BufferPoolSize, &BufferPoolSizeLen);
795 /* Strip spaces */
796 for(DWORD i=BufferPoolSizeLen-1; i > 0; i--)
797 {
798 if(BufferPoolSize[i]== ' ')
799 BufferPoolSize[i] = 0;
800 }
801 unsigned long long availableMemory=
802 GetMaxBufferSize(memstatus.ullTotalPhys)/ONE_MB;
803 swprintf_s(invalidValueMsg,
804 L"Invalid buffer pool size. Please use a number between %llu and %llu",
805 minBufferpoolMB, availableMemory);
806 if (BufferPoolSizeLen == 0 || BufferPoolSizeLen > 15 || !BufferPoolSize[0])
807 {
808 ErrorMsg= invalidValueMsg;
809 goto LExit;
810 }
811
812 BufferPoolSize[BufferPoolSizeLen]=0;
813 MsiSetPropertyW(hInstall, L"BUFFERPOOLSIZE", BufferPoolSize);
814 wchar_t *end;
815 unsigned long long sz = wcstoull(BufferPoolSize, &end, 10);
816 if (sz > availableMemory || sz < minBufferpoolMB || *end)
817 {
818 if (*end == 0)
819 {
820 if(sz > availableMemory)
821 {
822 swprintf_s(invalidValueMsg,
823 L"Value for buffer pool size is too large."
824 L"Only approximately %llu MB is available for allocation."
825 L"Please use a number between %llu and %llu.",
826 availableMemory, minBufferpoolMB, availableMemory);
827 }
828 else if(sz < minBufferpoolMB)
829 {
830 swprintf_s(invalidValueMsg,
831 L"Value for buffer pool size is too small."
832 L"Please use a number between %llu and %llu.",
833 minBufferpoolMB, availableMemory);
834 }
835 }
836 ErrorMsg= invalidValueMsg;
837 goto LExit;
838 }
839 }
840 LExit:
841 MsiSetPropertyW (hInstall, L"WarningText", ErrorMsg);
842 return WcaFinalize(er);
843 }
844
845 /*
846 Sets Innodb buffer pool size (1/8 of RAM by default), if not already specified
847 via command line.
848 Calculates innodb log file size as min(100, innodb buffer pool size/4)
849 */
850 extern "C" UINT __stdcall PresetDatabaseProperties(MSIHANDLE hInstall)
851 {
852 unsigned long long InnodbBufferPoolSize= 256;
853 unsigned long long InnodbLogFileSize= 100;
854 wchar_t buff[MAX_PATH];
855 UINT er = ERROR_SUCCESS;
856 HRESULT hr= S_OK;
857 MEMORYSTATUSEX memstatus;
858 DWORD BufferPoolsizeParamLen = MAX_PATH;
859 hr = WcaInitialize(hInstall, __FUNCTION__);
860 ExitOnFailure(hr, "Failed to initialize");
861 WcaLog(LOGMSG_STANDARD, "Initialized.");
862
863 /* Check if bufferpoolsize parameter was given on the command line*/
864 MsiGetPropertyW(hInstall, L"BUFFERPOOLSIZE", buff, &BufferPoolsizeParamLen);
865
866 if (BufferPoolsizeParamLen && buff[0])
867 {
868 WcaLog(LOGMSG_STANDARD, "BUFFERPOOLSIZE=%S, len=%u",buff, BufferPoolsizeParamLen);
869 InnodbBufferPoolSize= _wtoi64(buff);
870 }
871 else
872 {
873 memstatus.dwLength = sizeof(memstatus);
874 if (!GlobalMemoryStatusEx(&memstatus))
875 {
876 WcaLog(LOGMSG_STANDARD, "Error %u from GlobalMemoryStatusEx",
877 GetLastError());
878 er= ERROR_INSTALL_FAILURE;
879 goto LExit;
880 }
881 unsigned long long totalPhys= memstatus.ullTotalPhys;
882 /* Give innodb 12.5% of available physical memory. */
883 InnodbBufferPoolSize= totalPhys/ONE_MB/8;
884 #ifdef _M_IX86
885 /*
886 For 32 bit processes, take virtual address space limitation into account.
887 Do not try to use more than 3/4 of virtual address space, even if there
888 is plenty of physical memory.
889 */
890 InnodbBufferPoolSize= min(GetMaxBufferSize(totalPhys)/ONE_MB*3/4,
891 InnodbBufferPoolSize);
892 #endif
893 swprintf_s(buff, L"%llu",InnodbBufferPoolSize);
894 MsiSetPropertyW(hInstall, L"BUFFERPOOLSIZE", buff);
895 }
896 InnodbLogFileSize = min(100, 2 * InnodbBufferPoolSize);
897 swprintf_s(buff, L"%llu",InnodbLogFileSize);
898 MsiSetPropertyW(hInstall, L"LOGFILESIZE", buff);
899
900 LExit:
901 return WcaFinalize(er);
902 }
903
904 static BOOL FindErrorLog(const wchar_t *dir, wchar_t * ErrorLogFile, size_t ErrorLogLen)
905 {
906 WIN32_FIND_DATA FindFileData;
907 HANDLE hFind;
908 wchar_t name[MAX_PATH];
909 wcsncpy_s(name,dir, MAX_PATH);
910 wcsncat_s(name,L"\\*.err", MAX_PATH);
911 hFind = FindFirstFileW(name,&FindFileData);
912 if (hFind != INVALID_HANDLE_VALUE)
913 {
914 _snwprintf(ErrorLogFile, ErrorLogLen,
915 L"%s\\%s",dir, FindFileData.cFileName);
916 FindClose(hFind);
917 return TRUE;
918 }
919 return FALSE;
920 }
921
922 static void DumpErrorLog(const wchar_t *dir)
923 {
924 wchar_t filepath[MAX_PATH];
925 if (!FindErrorLog(dir, filepath, MAX_PATH))
926 return;
927 FILE *f= _wfopen(filepath, L"r");
928 if (!f)
929 return;
930 char buf[2048];
931 WcaLog(LOGMSG_STANDARD,"=== dumping error log %S === ",filepath);
932 while (fgets(buf, sizeof(buf), f))
933 {
934 /* Strip off EOL chars. */
935 size_t len = strlen(buf);
936 if (len > 0 && buf[len-1] == '\n')
937 buf[--len]= 0;
938 if (len > 0 && buf[len-1] == '\r')
939 buf[--len]= 0;
940 WcaLog(LOGMSG_STANDARD,"%s",buf);
941 }
942 fclose(f);
943 WcaLog(LOGMSG_STANDARD,"=== end of error log ===");
944 }
945
946 /* Remove service and data directory created by CreateDatabase operation */
947 extern "C" UINT __stdcall CreateDatabaseRollback(MSIHANDLE hInstall)
948 {
949 HRESULT hr = S_OK;
950 UINT er = ERROR_SUCCESS;
951 wchar_t* service= 0;
952 wchar_t* dir= 0;
953 wchar_t data[2*MAX_PATH];
954 DWORD len= MAX_PATH;
955
956 hr = WcaInitialize(hInstall, __FUNCTION__);
957 ExitOnFailure(hr, "Failed to initialize");
958 WcaLog(LOGMSG_STANDARD, "Initialized.");
959
960 MsiGetPropertyW(hInstall, L"CustomActionData", data, &len);
961
962 /* Property is encoded as [SERVICENAME]\[DBLOCATION] */
963 if(data[0] == L'\\')
964 {
965 dir= data+1;
966 }
967 else
968 {
969 service= data;
970 dir= wcschr(data, '\\');
971 if (dir)
972 {
973 *dir=0;
974 dir++;
975 }
976 }
977
978 if(service)
979 {
980 ExecRemoveService(service);
981 }
982 if(dir)
983 {
984 DumpErrorLog(dir);
985 ExecRemoveDataDirectory(dir);
986 }
987 LExit:
988 return WcaFinalize(er);
989 }
990
991
992 /*
993 Enables/disables optional "Launch upgrade wizard" checkbox at the end of
994 installation
995 */
996 #define MAX_VERSION_PROPERTY_SIZE 64
997
998 extern "C" UINT __stdcall CheckServiceUpgrades(MSIHANDLE hInstall)
999 {
1000 HRESULT hr = S_OK;
1001 UINT er = ERROR_SUCCESS;
1002 wchar_t installerVersion[MAX_VERSION_PROPERTY_SIZE];
1003 char installDir[MAX_PATH];
1004 DWORD size =MAX_VERSION_PROPERTY_SIZE;
1005 int installerMajorVersion, installerMinorVersion, installerPatchVersion;
1006 bool upgradableServiceFound=false;
1007 LPENUM_SERVICE_STATUS_PROCESSW info;
1008 DWORD bufsize;
1009 int index;
1010 BOOL ok;
1011 SC_HANDLE scm = NULL;
1012
1013 hr = WcaInitialize(hInstall, __FUNCTION__);
1014 WcaLog(LOGMSG_STANDARD, "Initialized.");
1015 if (MsiGetPropertyW(hInstall, L"ProductVersion", installerVersion, &size)
1016 != ERROR_SUCCESS)
1017 {
1018 hr = HRESULT_FROM_WIN32(GetLastError());
1019 ExitOnFailure(hr, "MsiGetPropertyW failed");
1020 }
1021 if (swscanf(installerVersion,L"%d.%d.%d",
1022 &installerMajorVersion, &installerMinorVersion, &installerPatchVersion) !=3)
1023 {
1024 assert(FALSE);
1025 }
1026
1027 size= MAX_PATH;
1028 if (MsiGetPropertyA(hInstall,"INSTALLDIR", installDir, &size)
1029 != ERROR_SUCCESS)
1030 {
1031 hr = HRESULT_FROM_WIN32(GetLastError());
1032 ExitOnFailure(hr, "MsiGetPropertyW failed");
1033 }
1034
1035
1036 scm = OpenSCManager(NULL, NULL,
1037 SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_CONNECT);
1038 if (scm == NULL)
1039 {
1040 hr = HRESULT_FROM_WIN32(GetLastError());
1041 ExitOnFailure(hr,"OpenSCManager failed");
1042 }
1043
1044 static BYTE buf[64*1024];
1045 static BYTE config_buffer[8*1024];
1046
1047 bufsize= sizeof(buf);
1048 DWORD bufneed;
1049 DWORD num_services;
1050 ok= EnumServicesStatusExW(scm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32,
1051 SERVICE_STATE_ALL, buf, bufsize, &bufneed, &num_services, NULL, NULL);
1052 if(!ok)
1053 {
1054 hr = HRESULT_FROM_WIN32(GetLastError());
1055 ExitOnFailure(hr,"EnumServicesStatusEx failed");
1056 }
1057 info =
1058 (LPENUM_SERVICE_STATUS_PROCESSW)buf;
1059 index=-1;
1060 for (ULONG i=0; i < num_services; i++)
1061 {
1062 SC_HANDLE service= OpenServiceW(scm, info[i].lpServiceName,
1063 SERVICE_QUERY_CONFIG);
1064 if (!service)
1065 continue;
1066 QUERY_SERVICE_CONFIGW *config=
1067 (QUERY_SERVICE_CONFIGW*)(void *)config_buffer;
1068 DWORD needed;
1069 ok= QueryServiceConfigW(service, config,sizeof(config_buffer),
1070 &needed) && (config->dwStartType != SERVICE_DISABLED);
1071 CloseServiceHandle(service);
1072 if (ok)
1073 {
1074 mysqld_service_properties props;
1075 if (get_mysql_service_properties(config->lpBinaryPathName, &props))
1076 continue;
1077 /*
1078 Only look for services that have mysqld.exe outside of the current
1079 installation directory.
1080 */
1081 if(installDir[0] == 0 || strstr(props.mysqld_exe,installDir) == 0)
1082 {
1083 WcaLog(LOGMSG_STANDARD, "found service %S, major=%d, minor=%d",
1084 info[i].lpServiceName, props.version_major, props.version_minor);
1085 if(props.version_major < installerMajorVersion
1086 || (props.version_major == installerMajorVersion &&
1087 props.version_minor <= installerMinorVersion))
1088 {
1089 upgradableServiceFound= true;
1090 break;
1091 }
1092 }
1093 }
1094 }
1095
1096 if(!upgradableServiceFound)
1097 {
1098 /* Disable optional checkbox at the end of installation */
1099 MsiSetPropertyW(hInstall, L"WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT", L"");
1100 MsiSetPropertyW(hInstall, L"WIXUI_EXITDIALOGOPTIONALCHECKBOX",L"");
1101 }
1102 else
1103 {
1104 MsiSetPropertyW(hInstall, L"UpgradableServiceFound", L"1");
1105 MsiSetPropertyW(hInstall, L"WIXUI_EXITDIALOGOPTIONALCHECKBOX",L"1");
1106 }
1107 LExit:
1108 if(scm)
1109 CloseServiceHandle(scm);
1110 return WcaFinalize(er);
1111 }
1112
1113
1114 /* DllMain - Initialize and cleanup WiX custom action utils */
1115 extern "C" BOOL WINAPI DllMain(
1116 __in HINSTANCE hInst,
1117 __in ULONG ulReason,
1118 __in LPVOID
1119 )
1120 {
1121 switch(ulReason)
1122 {
1123 case DLL_PROCESS_ATTACH:
1124 WcaGlobalInitialize(hInst);
1125 break;
1126
1127 case DLL_PROCESS_DETACH:
1128 WcaGlobalFinalize();
1129 break;
1130 }
1131
1132 return TRUE;
1133 }
1134