]> glassweightruler.freedombox.rocks Git - Ventoy.git/blob - vtoyjump/vtoyjump/vtoyjump.c
9f6443ec4c1c3c1b89324aa78f4058a7b2d827e2
[Ventoy.git] / vtoyjump / vtoyjump / vtoyjump.c
1 /******************************************************************************
2 * vtoyjump.c
3 *
4 * Copyright (c) 2020, longpanda <admin@ventoy.net>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation; either version 3 of the
9 * License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
18 *
19 */
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <Windows.h>
25 #include <virtdisk.h>
26 #include <winioctl.h>
27 #include <VersionHelpers.h>
28 #include "vtoyjump.h"
29 #include "fat_filelib.h"
30
31 static ventoy_os_param g_os_param;
32 static ventoy_windows_data g_windows_data;
33 static UINT8 g_os_param_reserved[32];
34 static BOOL g_64bit_system = FALSE;
35 static ventoy_guid g_ventoy_guid = VENTOY_GUID;
36 static HANDLE g_vtoylog_mutex = NULL;
37 static HANDLE g_vtoyins_mutex = NULL;
38
39 //Unicode "CmdLine"
40 static BOOL g_PecmdHasCmdLine = FALSE;
41 static UCHAR g_aucCmdLineHex[] =
42 {
43 0x43, 0x00, 0x6D, 0x00, 0x64, 0x00, 0x4C, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x65, 0x00
44 };
45
46 #define VTOY_PID_FILE "X:\\Windows\\System32\\pidventoy"
47 #define MUTEX_LOCK(hmutex) if (hmutex != NULL) LockStatus = WaitForSingleObject(hmutex, INFINITE)
48 #define MUTEX_UNLOCK(hmutex) if (hmutex != NULL && WAIT_OBJECT_0 == LockStatus) ReleaseMutex(hmutex)
49
50 void Log(const char *Fmt, ...)
51 {
52 va_list Arg;
53 int Len = 0;
54 FILE *File = NULL;
55 SYSTEMTIME Sys;
56 char szBuf[1024];
57 DWORD LockStatus = 0;
58 DWORD PID = GetCurrentProcessId();
59
60 GetLocalTime(&Sys);
61 Len += sprintf_s(szBuf, sizeof(szBuf),
62 "[%4d/%02d/%02d %02d:%02d:%02d.%03d] [%u] ",
63 Sys.wYear, Sys.wMonth, Sys.wDay,
64 Sys.wHour, Sys.wMinute, Sys.wSecond,
65 Sys.wMilliseconds, PID);
66
67 va_start(Arg, Fmt);
68 Len += vsnprintf_s(szBuf + Len, sizeof(szBuf)-Len, sizeof(szBuf)-Len, Fmt, Arg);
69 va_end(Arg);
70
71 MUTEX_LOCK(g_vtoylog_mutex);
72
73 fopen_s(&File, "ventoy.log", "a+");
74 if (File)
75 {
76 fwrite(szBuf, 1, Len, File);
77 fwrite("\n", 1, 1, File);
78 fclose(File);
79 }
80
81 MUTEX_UNLOCK(g_vtoylog_mutex);
82 }
83
84
85 static int LoadNtDriver(const char *DrvBinPath)
86 {
87 int i;
88 int rc = 0;
89 BOOL Ret;
90 DWORD Status;
91 SC_HANDLE hServiceMgr;
92 SC_HANDLE hService;
93 char name[256] = { 0 };
94
95 for (i = (int)strlen(DrvBinPath) - 1; i >= 0; i--)
96 {
97 if (DrvBinPath[i] == '\\' || DrvBinPath[i] == '/')
98 {
99 sprintf_s(name, sizeof(name), "%s", DrvBinPath + i + 1);
100 break;
101 }
102 }
103
104 Log("Load NT driver: %s %s", DrvBinPath, name);
105
106 hServiceMgr = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS);
107 if (hServiceMgr == NULL)
108 {
109 Log("OpenSCManager failed Error:%u", GetLastError());
110 return 1;
111 }
112
113 Log("OpenSCManager OK");
114
115 hService = CreateServiceA(hServiceMgr,
116 name,
117 name,
118 SERVICE_ALL_ACCESS,
119 SERVICE_KERNEL_DRIVER,
120 SERVICE_DEMAND_START,
121 SERVICE_ERROR_NORMAL,
122 DrvBinPath,
123 NULL, NULL, NULL, NULL, NULL);
124 if (hService == NULL)
125 {
126 Status = GetLastError();
127 if (Status != ERROR_IO_PENDING && Status != ERROR_SERVICE_EXISTS)
128 {
129 Log("CreateService failed v %u", Status);
130 CloseServiceHandle(hServiceMgr);
131 return 1;
132 }
133
134 hService = OpenServiceA(hServiceMgr, name, SERVICE_ALL_ACCESS);
135 if (hService == NULL)
136 {
137 Log("OpenService failed %u", Status);
138 CloseServiceHandle(hServiceMgr);
139 return 1;
140 }
141 }
142
143 Log("CreateService imdisk OK");
144
145 Ret = StartServiceA(hService, 0, NULL);
146 if (Ret)
147 {
148 Log("StartService OK");
149 }
150 else
151 {
152 Status = GetLastError();
153 if (Status == ERROR_SERVICE_ALREADY_RUNNING)
154 {
155 rc = 0;
156 }
157 else
158 {
159 Log("StartService error %u", Status);
160 rc = 1;
161 }
162 }
163
164 CloseServiceHandle(hService);
165 CloseServiceHandle(hServiceMgr);
166
167 Log("Load NT driver %s", rc ? "failed" : "success");
168
169 return rc;
170 }
171
172 static int ReadWholeFile2Buf(const char *Fullpath, void **Data, DWORD *Size)
173 {
174 int rc = 1;
175 DWORD FileSize;
176 DWORD dwSize;
177 HANDLE Handle;
178 BYTE *Buffer = NULL;
179
180 Log("ReadWholeFile2Buf <%s>", Fullpath);
181
182 Handle = CreateFileA(Fullpath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
183 if (Handle == INVALID_HANDLE_VALUE)
184 {
185 Log("Could not open the file<%s>, error:%u", Fullpath, GetLastError());
186 goto End;
187 }
188
189 FileSize = SetFilePointer(Handle, 0, NULL, FILE_END);
190
191 Buffer = malloc(FileSize);
192 if (!Buffer)
193 {
194 Log("Failed to alloc memory size:%u", FileSize);
195 goto End;
196 }
197
198 SetFilePointer(Handle, 0, NULL, FILE_BEGIN);
199 if (!ReadFile(Handle, Buffer, FileSize, &dwSize, NULL))
200 {
201 Log("ReadFile failed, dwSize:%u error:%u", dwSize, GetLastError());
202 goto End;
203 }
204
205 *Data = Buffer;
206 *Size = FileSize;
207
208 Log("Success read file size:%u", FileSize);
209
210 rc = 0;
211
212 End:
213 SAFE_CLOSE_HANDLE(Handle);
214
215 return rc;
216 }
217
218 static BOOL CheckPeHead(BYTE *Head)
219 {
220 UINT32 PeOffset;
221
222 if (Head[0] != 'M' || Head[1] != 'Z')
223 {
224 return FALSE;
225 }
226
227 PeOffset = *(UINT32 *)(Head + 60);
228 if (*(UINT32 *)(Head + PeOffset) != 0x00004550)
229 {
230 return FALSE;
231 }
232
233 return TRUE;
234 }
235
236 static BOOL IsPe64(BYTE *buffer)
237 {
238 DWORD pe_off;
239
240 if (!CheckPeHead(buffer))
241 {
242 return FALSE;
243 }
244
245 pe_off = *(UINT32 *)(buffer + 60);
246 if (*(UINT16 *)(buffer + pe_off + 24) == 0x020b)
247 {
248 return TRUE;
249 }
250
251 return FALSE;
252 }
253
254
255 static BOOL CheckOsParam(ventoy_os_param *param)
256 {
257 UINT32 i;
258 BYTE Sum = 0;
259
260 if (memcmp(&param->guid, &g_ventoy_guid, sizeof(ventoy_guid)))
261 {
262 return FALSE;
263 }
264
265 for (i = 0; i < sizeof(ventoy_os_param); i++)
266 {
267 Sum += *((BYTE *)param + i);
268 }
269
270 if (Sum)
271 {
272 return FALSE;
273 }
274
275 if (param->vtoy_img_location_addr % 4096)
276 {
277 return FALSE;
278 }
279
280 return TRUE;
281 }
282
283 static int SaveBuffer2File(const char *Fullpath, void *Buffer, DWORD Length)
284 {
285 int rc = 1;
286 DWORD dwSize;
287 HANDLE Handle;
288
289 Log("SaveBuffer2File <%s> len:%u", Fullpath, Length);
290
291 Handle = CreateFileA(Fullpath, GENERIC_READ | GENERIC_WRITE,
292 FILE_SHARE_READ | FILE_SHARE_WRITE, 0, CREATE_NEW, 0, 0);
293 if (Handle == INVALID_HANDLE_VALUE)
294 {
295 Log("Could not create new file, error:%u", GetLastError());
296 goto End;
297 }
298
299 WriteFile(Handle, Buffer, Length, &dwSize, NULL);
300
301 rc = 0;
302
303 End:
304 SAFE_CLOSE_HANDLE(Handle);
305
306 return rc;
307 }
308
309 static int IsUTF8Encode(const char *src)
310 {
311 int i;
312 const UCHAR *Byte = (const UCHAR *)src;
313
314 for (i = 0; i < MAX_PATH && Byte[i]; i++)
315 {
316 if (Byte[i] > 127)
317 {
318 return 1;
319 }
320 }
321
322 return 0;
323 }
324
325 static int Utf8ToUtf16(const char* src, WCHAR * dst)
326 {
327 int size = MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, 0);
328 return MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, size + 1);
329 }
330
331 static BOOL IsDirExist(const char *Fmt, ...)
332 {
333 va_list Arg;
334 DWORD Attr;
335 int UTF8 = 0;
336 CHAR FilePathA[MAX_PATH];
337 WCHAR FilePathW[MAX_PATH];
338
339 va_start(Arg, Fmt);
340 vsnprintf_s(FilePathA, sizeof(FilePathA), sizeof(FilePathA), Fmt, Arg);
341 va_end(Arg);
342
343 UTF8 = IsUTF8Encode(FilePathA);
344
345 if (UTF8)
346 {
347 Utf8ToUtf16(FilePathA, FilePathW);
348 Attr = GetFileAttributesW(FilePathW);
349 }
350 else
351 {
352 Attr = GetFileAttributesA(FilePathA);
353 }
354
355 if (Attr != INVALID_FILE_ATTRIBUTES && (Attr & FILE_ATTRIBUTE_DIRECTORY))
356 {
357 return TRUE;
358 }
359
360 return FALSE;
361 }
362
363 static BOOL IsFileExist(const char *Fmt, ...)
364 {
365 va_list Arg;
366 HANDLE hFile;
367 DWORD Attr;
368 BOOL bRet = FALSE;
369 int UTF8 = 0;
370 CHAR FilePathA[MAX_PATH];
371 WCHAR FilePathW[MAX_PATH];
372
373 va_start(Arg, Fmt);
374 vsnprintf_s(FilePathA, sizeof(FilePathA), sizeof(FilePathA), Fmt, Arg);
375 va_end(Arg);
376
377 UTF8 = IsUTF8Encode(FilePathA);
378
379 if (UTF8)
380 {
381 Utf8ToUtf16(FilePathA, FilePathW);
382 hFile = CreateFileW(FilePathW, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
383 }
384 else
385 {
386 hFile = CreateFileA(FilePathA, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
387 }
388 if (INVALID_HANDLE_VALUE == hFile)
389 {
390 goto out;
391 }
392
393 CloseHandle(hFile);
394
395 if (UTF8)
396 {
397 Attr = GetFileAttributesW(FilePathW);
398 }
399 else
400 {
401 Attr = GetFileAttributesA(FilePathA);
402 }
403
404 if (Attr & FILE_ATTRIBUTE_DIRECTORY)
405 {
406 goto out;
407 }
408
409 bRet = TRUE;
410
411 out:
412 Log("File <%s> %s", FilePathA, (bRet ? "exist" : "NOT exist"));
413 return bRet;
414 }
415
416 static int GetPhyDiskUUID(const char LogicalDrive, UINT8 *UUID, DISK_EXTENT *DiskExtent)
417 {
418 BOOL Ret;
419 DWORD dwSize;
420 HANDLE Handle;
421 VOLUME_DISK_EXTENTS DiskExtents;
422 CHAR PhyPath[128];
423 UINT8 SectorBuf[512];
424
425 Log("GetPhyDiskUUID %C", LogicalDrive);
426
427 sprintf_s(PhyPath, sizeof(PhyPath), "\\\\.\\%C:", LogicalDrive);
428 Handle = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
429 if (Handle == INVALID_HANDLE_VALUE)
430 {
431 Log("Could not open the disk<%s>, error:%u", PhyPath, GetLastError());
432 return 1;
433 }
434
435 Ret = DeviceIoControl(Handle,
436 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
437 NULL,
438 0,
439 &DiskExtents,
440 (DWORD)(sizeof(DiskExtents)),
441 (LPDWORD)&dwSize,
442 NULL);
443 if (!Ret || DiskExtents.NumberOfDiskExtents == 0)
444 {
445 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed, error:%u", GetLastError());
446 CloseHandle(Handle);
447 return 1;
448 }
449 CloseHandle(Handle);
450
451 memcpy(DiskExtent, DiskExtents.Extents, sizeof(DiskExtent));
452 Log("%C: is in PhysicalDrive%d ", LogicalDrive, DiskExtents.Extents[0].DiskNumber);
453
454 sprintf_s(PhyPath, sizeof(PhyPath), "\\\\.\\PhysicalDrive%d", DiskExtents.Extents[0].DiskNumber);
455 Handle = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
456 if (Handle == INVALID_HANDLE_VALUE)
457 {
458 Log("Could not open the disk<%s>, error:%u", PhyPath, GetLastError());
459 return 1;
460 }
461
462 if (!ReadFile(Handle, SectorBuf, sizeof(SectorBuf), &dwSize, NULL))
463 {
464 Log("ReadFile failed, dwSize:%u error:%u", dwSize, GetLastError());
465 CloseHandle(Handle);
466 return 1;
467 }
468
469 memcpy(UUID, SectorBuf + 0x180, 16);
470 CloseHandle(Handle);
471 return 0;
472 }
473
474 static int VentoyMountAnywhere(HANDLE Handle)
475 {
476 DWORD Status;
477 ATTACH_VIRTUAL_DISK_PARAMETERS AttachParameters;
478
479 Log("VentoyMountAnywhere");
480
481 memset(&AttachParameters, 0, sizeof(AttachParameters));
482 AttachParameters.Version = ATTACH_VIRTUAL_DISK_VERSION_1;
483
484 Status = AttachVirtualDisk(Handle, NULL, ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY | ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME, 0, &AttachParameters, NULL);
485 if (Status != ERROR_SUCCESS)
486 {
487 Log("Failed to attach virtual disk ErrorCode:%u", Status);
488 return 1;
489 }
490
491 return 0;
492 }
493
494 int VentoyMountY(HANDLE Handle)
495 {
496 int i;
497 BOOL bRet = FALSE;
498 DWORD Status;
499 DWORD physicalDriveNameSize;
500 CHAR *Pos = NULL;
501 WCHAR physicalDriveName[MAX_PATH];
502 CHAR physicalDriveNameA[MAX_PATH];
503 CHAR cdromDriveName[MAX_PATH];
504 ATTACH_VIRTUAL_DISK_PARAMETERS AttachParameters;
505
506 Log("VentoyMountY");
507
508 memset(&AttachParameters, 0, sizeof(AttachParameters));
509 AttachParameters.Version = ATTACH_VIRTUAL_DISK_VERSION_1;
510
511 Status = AttachVirtualDisk(Handle, NULL, ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY | ATTACH_VIRTUAL_DISK_FLAG_NO_DRIVE_LETTER | ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME, 0, &AttachParameters, NULL);
512 if (Status != ERROR_SUCCESS)
513 {
514 Log("Failed to attach virtual disk ErrorCode:%u", Status);
515 return 1;
516 }
517
518 memset(physicalDriveName, 0, sizeof(physicalDriveName));
519 memset(physicalDriveNameA, 0, sizeof(physicalDriveNameA));
520
521 physicalDriveNameSize = MAX_PATH;
522 Status = GetVirtualDiskPhysicalPath(Handle, &physicalDriveNameSize, physicalDriveName);
523 if (Status != ERROR_SUCCESS)
524 {
525 Log("Failed GetVirtualDiskPhysicalPath ErrorCode:%u", Status);
526 return 1;
527 }
528
529 for (i = 0; physicalDriveName[i]; i++)
530 {
531 physicalDriveNameA[i] = toupper((CHAR)(physicalDriveName[i]));
532 }
533
534 Log("physicalDriveNameA=<%s>", physicalDriveNameA);
535
536 Pos = strstr(physicalDriveNameA, "CDROM");
537 if (!Pos)
538 {
539 Log("Not cdrom phy drive");
540 return 1;
541 }
542
543 sprintf_s(cdromDriveName, sizeof(cdromDriveName), "\\Device\\%s", Pos);
544 Log("cdromDriveName=<%s>", cdromDriveName);
545
546 for (i = 0; i < 3 && (bRet == FALSE); i++)
547 {
548 Sleep(1000);
549 bRet = DefineDosDeviceA(DDD_RAW_TARGET_PATH, "Y:", cdromDriveName);
550 Log("DefineDosDeviceA %s", bRet ? "success" : "failed");
551 }
552
553 return bRet ? 0 : 1;
554 }
555
556 static BOOL VentoyNeedMountY(const char *IsoPath)
557 {
558 /* TBD */
559 return FALSE;
560 }
561
562 static int VentoyAttachVirtualDisk(HANDLE Handle, const char *IsoPath)
563 {
564 int DriveYFree;
565 DWORD Drives;
566
567 Drives = GetLogicalDrives();
568 if ((1 << 24) & Drives)
569 {
570 Log("Y: is occupied");
571 DriveYFree = 0;
572 }
573 else
574 {
575 Log("Y: is free now");
576 DriveYFree = 1;
577 }
578
579 if (DriveYFree && VentoyNeedMountY(IsoPath))
580 {
581 return VentoyMountY(Handle);
582 }
583 else
584 {
585 return VentoyMountAnywhere(Handle);
586 }
587 }
588
589 int VentoyMountISOByAPI(const char *IsoPath)
590 {
591 HANDLE Handle;
592 DWORD Status;
593 WCHAR wFilePath[512] = { 0 };
594 VIRTUAL_STORAGE_TYPE StorageType;
595 OPEN_VIRTUAL_DISK_PARAMETERS OpenParameters;
596
597 Log("VentoyMountISOByAPI <%s>", IsoPath);
598
599 if (IsUTF8Encode(IsoPath))
600 {
601 MultiByteToWideChar(CP_UTF8, 0, IsoPath, (int)strlen(IsoPath), wFilePath, (int)(sizeof(wFilePath) / sizeof(WCHAR)));
602 }
603 else
604 {
605 MultiByteToWideChar(CP_ACP, 0, IsoPath, (int)strlen(IsoPath), wFilePath, (int)(sizeof(wFilePath) / sizeof(WCHAR)));
606 }
607
608 memset(&StorageType, 0, sizeof(StorageType));
609 memset(&OpenParameters, 0, sizeof(OpenParameters));
610
611 OpenParameters.Version = OPEN_VIRTUAL_DISK_VERSION_1;
612
613 Status = OpenVirtualDisk(&StorageType, wFilePath, VIRTUAL_DISK_ACCESS_READ, 0, &OpenParameters, &Handle);
614 if (Status != ERROR_SUCCESS)
615 {
616 if (ERROR_VIRTDISK_PROVIDER_NOT_FOUND == Status)
617 {
618 Log("VirtualDisk for ISO file is not supported in current system");
619 }
620 else
621 {
622 Log("Failed to open virtual disk ErrorCode:%u", Status);
623 }
624 return 1;
625 }
626
627 Log("OpenVirtualDisk success");
628
629 Status = VentoyAttachVirtualDisk(Handle, IsoPath);
630 if (Status != ERROR_SUCCESS)
631 {
632 Log("Failed to attach virtual disk ErrorCode:%u", Status);
633 CloseHandle(Handle);
634 return 1;
635 }
636
637 Log("VentoyAttachVirtualDisk success");
638
639 CloseHandle(Handle);
640 return 0;
641 }
642
643
644 static HANDLE g_FatPhyDrive;
645 static UINT64 g_Part2StartSec;
646
647 static int CopyFileFromFatDisk(const CHAR* SrcFile, const CHAR *DstFile)
648 {
649 int rc = 1;
650 int size = 0;
651 char *buf = NULL;
652 void *flfile = NULL;
653
654 Log("CopyFileFromFatDisk (%s)==>(%s)", SrcFile, DstFile);
655
656 flfile = fl_fopen(SrcFile, "rb");
657 if (flfile)
658 {
659 fl_fseek(flfile, 0, SEEK_END);
660 size = (int)fl_ftell(flfile);
661 fl_fseek(flfile, 0, SEEK_SET);
662
663 buf = (char *)malloc(size);
664 if (buf)
665 {
666 fl_fread(buf, 1, size, flfile);
667
668 rc = 0;
669 SaveBuffer2File(DstFile, buf, size);
670 free(buf);
671 }
672
673 fl_fclose(flfile);
674 }
675
676 return rc;
677 }
678
679 static int VentoyFatDiskRead(uint32 Sector, uint8 *Buffer, uint32 SectorCount)
680 {
681 DWORD dwSize;
682 BOOL bRet;
683 DWORD ReadSize;
684 LARGE_INTEGER liCurrentPosition;
685
686 liCurrentPosition.QuadPart = Sector + g_Part2StartSec;
687 liCurrentPosition.QuadPart *= 512;
688 SetFilePointerEx(g_FatPhyDrive, liCurrentPosition, &liCurrentPosition, FILE_BEGIN);
689
690 ReadSize = (DWORD)(SectorCount * 512);
691
692 bRet = ReadFile(g_FatPhyDrive, Buffer, ReadSize, &dwSize, NULL);
693 if (bRet == FALSE || dwSize != ReadSize)
694 {
695 Log("ReadFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u\n", bRet, ReadSize, dwSize, GetLastError());
696 }
697
698 return 1;
699 }
700
701 static BOOL Is2K10PE(void)
702 {
703 BOOL bRet = FALSE;
704 FILE *fp = NULL;
705 CHAR szLine[1024];
706
707 fopen_s(&fp, "X:\\Windows\\System32\\PECMD.INI", "r");
708 if (!fp)
709 {
710 return FALSE;
711 }
712
713 memset(szLine, 0, sizeof(szLine));
714 while (fgets(szLine, sizeof(szLine) - 1, fp))
715 {
716 if (strstr(szLine, "\\2k10\\"))
717 {
718 bRet = TRUE;
719 break;
720 }
721 }
722
723 fclose(fp);
724 return bRet;
725 }
726
727 static CHAR GetMountLogicalDrive(void)
728 {
729 CHAR Letter = 'Y';
730 DWORD Drives;
731 DWORD Mask = 0x1000000;
732
733 // fixed use M as mountpoint for 2K10 PE
734 if (Is2K10PE())
735 {
736 Log("Use M: for 2K10 PE");
737 return 'M';
738 }
739
740 Drives = GetLogicalDrives();
741 Log("Drives=0x%x", Drives);
742
743 while (Mask)
744 {
745 if ((Drives & Mask) == 0)
746 {
747 break;
748 }
749
750 Letter--;
751 Mask >>= 1;
752 }
753
754 return Letter;
755 }
756
757 UINT64 GetVentoyEfiPartStartSector(HANDLE hDrive)
758 {
759 BOOL bRet;
760 DWORD dwSize;
761 MBR_HEAD MBR;
762 VTOY_GPT_INFO *pGpt = NULL;
763 UINT64 StartSector = 0;
764
765 SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
766
767 bRet = ReadFile(hDrive, &MBR, sizeof(MBR), &dwSize, NULL);
768 Log("Read MBR Ret:%u Size:%u code:%u", bRet, dwSize, LASTERR);
769
770 if ((!bRet) || (dwSize != sizeof(MBR)))
771 {
772 0;
773 }
774
775 if (MBR.PartTbl[0].FsFlag == 0xEE)
776 {
777 Log("GPT partition style");
778
779 pGpt = malloc(sizeof(VTOY_GPT_INFO));
780 if (!pGpt)
781 {
782 return 0;
783 }
784
785 SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
786 bRet = ReadFile(hDrive, pGpt, sizeof(VTOY_GPT_INFO), &dwSize, NULL);
787 if ((!bRet) || (dwSize != sizeof(VTOY_GPT_INFO)))
788 {
789 Log("Failed to read gpt info %d %u %d", bRet, dwSize, LASTERR);
790 return 0;
791 }
792
793 StartSector = pGpt->PartTbl[1].StartLBA;
794 free(pGpt);
795 }
796 else
797 {
798 Log("MBR partition style");
799 StartSector = MBR.PartTbl[1].StartSectorId;
800 }
801
802 Log("GetVentoyEfiPart StartSector: %llu", StartSector);
803 return StartSector;
804 }
805
806 static int VentoyRunImdisk(const char *IsoPath, const char *imdiskexe)
807 {
808 CHAR Letter;
809 CHAR Cmdline[512];
810 WCHAR CmdlineW[512];
811 PROCESS_INFORMATION Pi;
812
813 Log("VentoyRunImdisk <%s> <%s>", IsoPath, imdiskexe);
814
815 Letter = GetMountLogicalDrive();
816 sprintf_s(Cmdline, sizeof(Cmdline), "%s -a -o ro -f \"%s\" -m %C:", imdiskexe, IsoPath, Letter);
817 Log("mount iso to %C: use imdisk cmd <%s>", Letter, Cmdline);
818
819 if (IsUTF8Encode(IsoPath))
820 {
821 STARTUPINFOW Si;
822 GetStartupInfoW(&Si);
823 Si.dwFlags |= STARTF_USESHOWWINDOW;
824 Si.wShowWindow = SW_HIDE;
825
826 Utf8ToUtf16(Cmdline, CmdlineW);
827 CreateProcessW(NULL, CmdlineW, NULL, NULL, FALSE, 0, NULL, NULL, &Si, &Pi);
828
829 Log("This is UTF8 encoding");
830 }
831 else
832 {
833 STARTUPINFOA Si;
834 GetStartupInfoA(&Si);
835 Si.dwFlags |= STARTF_USESHOWWINDOW;
836 Si.wShowWindow = SW_HIDE;
837
838 CreateProcessA(NULL, Cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &Si, &Pi);
839
840 Log("This is ANSI encoding");
841 }
842
843 Log("Wait for imdisk process ...");
844 WaitForSingleObject(Pi.hProcess, INFINITE);
845 Log("imdisk process finished");
846
847 return 0;
848 }
849
850 int VentoyMountISOByImdisk(const char *IsoPath, DWORD PhyDrive)
851 {
852 int rc = 1;
853 BOOL bRet;
854 DWORD dwBytes;
855 HANDLE hDrive;
856 CHAR PhyPath[MAX_PATH];
857 GET_LENGTH_INFORMATION LengthInfo;
858
859 Log("VentoyMountISOByImdisk %s", IsoPath);
860
861 if (IsFileExist("X:\\Windows\\System32\\imdisk.exe"))
862 {
863 Log("imdisk.exe exist, use it directly...");
864 VentoyRunImdisk(IsoPath, "imdisk.exe");
865 return 0;
866 }
867
868 sprintf_s(PhyPath, sizeof(PhyPath), "\\\\.\\PhysicalDrive%d", PhyDrive);
869 hDrive = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
870 if (hDrive == INVALID_HANDLE_VALUE)
871 {
872 Log("Could not open the disk<%s>, error:%u", PhyPath, GetLastError());
873 goto End;
874 }
875
876 bRet = DeviceIoControl(hDrive, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &LengthInfo, sizeof(LengthInfo), &dwBytes, NULL);
877 if (!bRet)
878 {
879 Log("Could not get phy disk %s size, error:%u", PhyPath, GetLastError());
880 goto End;
881 }
882
883 g_FatPhyDrive = hDrive;
884 g_Part2StartSec = GetVentoyEfiPartStartSector(hDrive);
885
886 Log("Parse FAT fs...");
887
888 fl_init();
889
890 if (0 == fl_attach_media(VentoyFatDiskRead, NULL))
891 {
892 if (g_64bit_system)
893 {
894 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.sys", "ventoy\\imdisk.sys");
895 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.exe", "ventoy\\imdisk.exe");
896 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.cpl", "ventoy\\imdisk.cpl");
897 }
898 else
899 {
900 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.sys", "ventoy\\imdisk.sys");
901 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.exe", "ventoy\\imdisk.exe");
902 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.cpl", "ventoy\\imdisk.cpl");
903 }
904
905 GetCurrentDirectoryA(sizeof(PhyPath), PhyPath);
906 strcat_s(PhyPath, sizeof(PhyPath), "\\ventoy\\imdisk.sys");
907
908 if (LoadNtDriver(PhyPath) == 0)
909 {
910 VentoyRunImdisk(IsoPath, "ventoy\\imdisk.exe");
911 rc = 0;
912 }
913 }
914 fl_shutdown();
915
916 End:
917
918 SAFE_CLOSE_HANDLE(hDrive);
919
920 return rc;
921 }
922
923 static int MountIsoFile(CONST CHAR *IsoPath, DWORD PhyDrive)
924 {
925 if (IsWindows8OrGreater())
926 {
927 Log("This is Windows 8 or latter...");
928 if (VentoyMountISOByAPI(IsoPath) == 0)
929 {
930 Log("Mount iso by API success");
931 return 0;
932 }
933 else
934 {
935 Log("Mount iso by API failed, maybe not supported, try imdisk");
936 return VentoyMountISOByImdisk(IsoPath, PhyDrive);
937 }
938 }
939 else
940 {
941 Log("This is before Windows 8 ...");
942 if (VentoyMountISOByImdisk(IsoPath, PhyDrive) == 0)
943 {
944 Log("Mount iso by imdisk success");
945 return 0;
946 }
947 else
948 {
949 return VentoyMountISOByAPI(IsoPath);
950 }
951 }
952 }
953
954 static int GetPhyDriveByLogicalDrive(int DriveLetter)
955 {
956 BOOL Ret;
957 DWORD dwSize;
958 HANDLE Handle;
959 VOLUME_DISK_EXTENTS DiskExtents;
960 CHAR PhyPath[128];
961
962 sprintf_s(PhyPath, sizeof(PhyPath), "\\\\.\\%C:", (CHAR)DriveLetter);
963
964 Handle = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
965 if (Handle == INVALID_HANDLE_VALUE)
966 {
967 Log("Could not open the disk<%s>, error:%u", PhyPath, GetLastError());
968 return -1;
969 }
970
971 Ret = DeviceIoControl(Handle,
972 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
973 NULL,
974 0,
975 &DiskExtents,
976 (DWORD)(sizeof(DiskExtents)),
977 (LPDWORD)&dwSize,
978 NULL);
979
980 if (!Ret || DiskExtents.NumberOfDiskExtents == 0)
981 {
982 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed %s, error:%u", PhyPath, GetLastError());
983 SAFE_CLOSE_HANDLE(Handle);
984 return -1;
985 }
986 SAFE_CLOSE_HANDLE(Handle);
987
988 Log("LogicalDrive:%s PhyDrive:%d Offset:%llu ExtentLength:%llu",
989 PhyPath,
990 DiskExtents.Extents[0].DiskNumber,
991 DiskExtents.Extents[0].StartingOffset.QuadPart,
992 DiskExtents.Extents[0].ExtentLength.QuadPart
993 );
994
995 return (int)DiskExtents.Extents[0].DiskNumber;
996 }
997
998
999 static int DeleteVentoyPart2MountPoint(DWORD PhyDrive)
1000 {
1001 CHAR Letter = 'A';
1002 DWORD Drives;
1003 DWORD PhyDisk;
1004 CHAR DriveName[] = "?:\\";
1005
1006 Log("DeleteVentoyPart2MountPoint Phy%u ...", PhyDrive);
1007
1008 Drives = GetLogicalDrives();
1009 while (Drives)
1010 {
1011 if ((Drives & 0x01) && IsFileExist("%C:\\ventoy\\ventoy.cpio", Letter))
1012 {
1013 Log("File %C:\\ventoy\\ventoy.cpio exist", Letter);
1014
1015 PhyDisk = GetPhyDriveByLogicalDrive(Letter);
1016 Log("PhyDisk=%u for %C", PhyDisk, Letter);
1017
1018 if (PhyDisk == PhyDrive)
1019 {
1020 DriveName[0] = Letter;
1021 DeleteVolumeMountPointA(DriveName);
1022 return 0;
1023 }
1024 }
1025
1026 Letter++;
1027 Drives >>= 1;
1028 }
1029
1030 return 1;
1031 }
1032
1033 static BOOL check_tar_archive(const char *archive, CHAR *tarName)
1034 {
1035 int len;
1036 int nameLen;
1037 const char *pos = archive;
1038 const char *slash = archive;
1039
1040 while (*pos)
1041 {
1042 if (*pos == '\\' || *pos == '/')
1043 {
1044 slash = pos;
1045 }
1046 pos++;
1047 }
1048
1049 len = (int)strlen(slash);
1050
1051 if (len > 7 && (strncmp(slash + len - 7, ".tar.gz", 7) == 0 || strncmp(slash + len - 7, ".tar.xz", 7) == 0))
1052 {
1053 nameLen = (int)sprintf_s(tarName, MAX_PATH, "X:%s", slash);
1054 tarName[nameLen - 3] = 0;
1055 return TRUE;
1056 }
1057 else if (len > 8 && strncmp(slash + len - 8, ".tar.bz2", 8) == 0)
1058 {
1059 nameLen = (int)sprintf_s(tarName, MAX_PATH, "X:%s", slash);
1060 tarName[nameLen - 4] = 0;
1061 return TRUE;
1062 }
1063 else if (len > 9 && strncmp(slash + len - 9, ".tar.lzma", 9) == 0)
1064 {
1065 nameLen = (int)sprintf_s(tarName, MAX_PATH, "X:%s", slash);
1066 tarName[nameLen - 5] = 0;
1067 return TRUE;
1068 }
1069
1070 return FALSE;
1071 }
1072
1073 static int DecompressInjectionArchive(const char *archive, DWORD PhyDrive)
1074 {
1075 int rc = 1;
1076 BOOL bRet;
1077 DWORD dwBytes;
1078 HANDLE hDrive;
1079 HANDLE hOut;
1080 DWORD flags = CREATE_NO_WINDOW;
1081 CHAR StrBuf[MAX_PATH];
1082 CHAR tarName[MAX_PATH];
1083 STARTUPINFOA Si;
1084 PROCESS_INFORMATION Pi;
1085 PROCESS_INFORMATION NewPi;
1086 GET_LENGTH_INFORMATION LengthInfo;
1087 SECURITY_ATTRIBUTES Sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
1088
1089 Log("DecompressInjectionArchive %s", archive);
1090
1091 sprintf_s(StrBuf, sizeof(StrBuf), "\\\\.\\PhysicalDrive%d", PhyDrive);
1092 hDrive = CreateFileA(StrBuf, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
1093 if (hDrive == INVALID_HANDLE_VALUE)
1094 {
1095 Log("Could not open the disk<%s>, error:%u", StrBuf, GetLastError());
1096 goto End;
1097 }
1098
1099 bRet = DeviceIoControl(hDrive, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &LengthInfo, sizeof(LengthInfo), &dwBytes, NULL);
1100 if (!bRet)
1101 {
1102 Log("Could not get phy disk %s size, error:%u", StrBuf, GetLastError());
1103 goto End;
1104 }
1105
1106 g_FatPhyDrive = hDrive;
1107 g_Part2StartSec = GetVentoyEfiPartStartSector(hDrive);
1108
1109 Log("Parse FAT fs...");
1110
1111 fl_init();
1112
1113 if (0 == fl_attach_media(VentoyFatDiskRead, NULL))
1114 {
1115 if (g_64bit_system)
1116 {
1117 CopyFileFromFatDisk("/ventoy/7z/64/7za.exe", "ventoy\\7za.exe");
1118 }
1119 else
1120 {
1121 CopyFileFromFatDisk("/ventoy/7z/32/7za.exe", "ventoy\\7za.exe");
1122 }
1123
1124 sprintf_s(StrBuf, sizeof(StrBuf), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", archive);
1125
1126 Log("extract inject to X:");
1127 Log("cmdline:<%s>", StrBuf);
1128
1129 GetStartupInfoA(&Si);
1130
1131 hOut = CreateFileA("ventoy\\7z.log",
1132 FILE_APPEND_DATA,
1133 FILE_SHARE_WRITE | FILE_SHARE_READ,
1134 &Sa,
1135 OPEN_ALWAYS,
1136 FILE_ATTRIBUTE_NORMAL,
1137 NULL);
1138
1139 Si.dwFlags |= STARTF_USESTDHANDLES;
1140
1141 if (hOut != INVALID_HANDLE_VALUE)
1142 {
1143 Si.hStdError = hOut;
1144 Si.hStdOutput = hOut;
1145 }
1146
1147 CreateProcessA(NULL, StrBuf, NULL, NULL, TRUE, flags, NULL, NULL, &Si, &Pi);
1148 WaitForSingleObject(Pi.hProcess, INFINITE);
1149
1150 //
1151 // decompress tar archive, for tar.gz/tar.xz/tar.bz2
1152 //
1153 if (check_tar_archive(archive, tarName))
1154 {
1155 Log("Decompress tar archive...<%s>", tarName);
1156
1157 sprintf_s(StrBuf, sizeof(StrBuf), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", tarName);
1158
1159 CreateProcessA(NULL, StrBuf, NULL, NULL, TRUE, flags, NULL, NULL, &Si, &NewPi);
1160 WaitForSingleObject(NewPi.hProcess, INFINITE);
1161
1162 Log("Now delete %s", tarName);
1163 DeleteFileA(tarName);
1164 }
1165
1166 SAFE_CLOSE_HANDLE(hOut);
1167 }
1168 fl_shutdown();
1169
1170 End:
1171
1172 SAFE_CLOSE_HANDLE(hDrive);
1173
1174 return rc;
1175 }
1176
1177 static int ProcessUnattendedInstallation(const char *script)
1178 {
1179 DWORD dw;
1180 HKEY hKey;
1181 LSTATUS Ret;
1182 CHAR Letter;
1183 CHAR CurDir[MAX_PATH];
1184
1185 Log("Copy unattended XML ...");
1186
1187 GetCurrentDirectory(sizeof(CurDir), CurDir);
1188 Letter = CurDir[0];
1189 if ((Letter >= 'A' && Letter <= 'Z') || (Letter >= 'a' && Letter <= 'z'))
1190 {
1191 Log("Current Drive Letter: %C", Letter);
1192 }
1193 else
1194 {
1195 Letter = 'X';
1196 }
1197
1198 sprintf_s(CurDir, sizeof(CurDir), "%C:\\Autounattend.xml", Letter);
1199 Log("Copy file <%s> --> <%s>", script, CurDir);
1200 CopyFile(script, CurDir, FALSE);
1201
1202 Ret = RegCreateKeyEx(HKEY_LOCAL_MACHINE, "System\\Setup", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dw);
1203 if (ERROR_SUCCESS == Ret)
1204 {
1205 Ret = RegSetValueEx(hKey, "UnattendFile", 0, REG_SZ, CurDir, (DWORD)(strlen(CurDir) + 1));
1206 }
1207
1208 return 0;
1209 }
1210
1211 static int VentoyHook(ventoy_os_param *param)
1212 {
1213 int rc;
1214 CHAR Letter = 'A';
1215 DISK_EXTENT DiskExtent;
1216 DWORD Drives = GetLogicalDrives();
1217 UINT8 UUID[16];
1218 CHAR IsoPath[MAX_PATH];
1219
1220 Log("Logical Drives=0x%x Path:<%s>", Drives, param->vtoy_img_path);
1221
1222 if (IsUTF8Encode(param->vtoy_img_path))
1223 {
1224 Log("This file is UTF8 encoding\n");
1225 }
1226
1227 while (Drives)
1228 {
1229 if (Drives & 0x01)
1230 {
1231 sprintf_s(IsoPath, sizeof(IsoPath), "%C:\\%s", Letter, param->vtoy_img_path);
1232 if (IsFileExist("%s", IsoPath))
1233 {
1234 Log("File exist under %C:", Letter);
1235 if (GetPhyDiskUUID(Letter, UUID, &DiskExtent) == 0)
1236 {
1237 if (memcmp(UUID, param->vtoy_disk_guid, 16) == 0)
1238 {
1239 Log("Disk UUID match");
1240 break;
1241 }
1242 }
1243 }
1244 else
1245 {
1246 Log("File NOT exist under %C:", Letter);
1247 }
1248 }
1249
1250 Drives >>= 1;
1251 Letter++;
1252 }
1253
1254 if (Drives == 0)
1255 {
1256 Log("Failed to find ISO file");
1257 return 1;
1258 }
1259
1260 Log("Find ISO file <%s>", IsoPath);
1261
1262 rc = MountIsoFile(IsoPath, DiskExtent.DiskNumber);
1263 Log("Mount ISO FILE: %s", rc == 0 ? "SUCCESS" : "FAILED");
1264
1265 // for protect
1266 rc = DeleteVentoyPart2MountPoint(DiskExtent.DiskNumber);
1267 Log("Delete ventoy mountpoint: %s", rc == 0 ? "SUCCESS" : "NO NEED");
1268
1269 if (g_windows_data.auto_install_script[0])
1270 {
1271 sprintf_s(IsoPath, sizeof(IsoPath), "%C:%s", Letter, g_windows_data.auto_install_script);
1272 if (IsFileExist("%s", IsoPath))
1273 {
1274 Log("use auto install script %s...", IsoPath);
1275 ProcessUnattendedInstallation(IsoPath);
1276 }
1277 else
1278 {
1279 Log("auto install script %s not exist", IsoPath);
1280 }
1281 }
1282 else
1283 {
1284 Log("auto install no need");
1285 }
1286
1287 if (g_windows_data.injection_archive[0])
1288 {
1289 sprintf_s(IsoPath, sizeof(IsoPath), "%C:%s", Letter, g_windows_data.injection_archive);
1290 if (IsFileExist("%s", IsoPath))
1291 {
1292 Log("decompress injection archive %s...", IsoPath);
1293 DecompressInjectionArchive(IsoPath, DiskExtent.DiskNumber);
1294 }
1295 else
1296 {
1297 Log("injection archive %s not exist", IsoPath);
1298 }
1299 }
1300 else
1301 {
1302 Log("no injection archive found");
1303 }
1304
1305 return 0;
1306 }
1307
1308 const char * GetFileNameInPath(const char *fullpath)
1309 {
1310 int i;
1311 const char *pos = NULL;
1312
1313 if (strstr(fullpath, ":"))
1314 {
1315 for (i = (int)strlen(fullpath); i > 0; i--)
1316 {
1317 if (fullpath[i - 1] == '/' || fullpath[i - 1] == '\\')
1318 {
1319 return fullpath + i;
1320 }
1321 }
1322 }
1323
1324 return fullpath;
1325 }
1326
1327 int VentoyJumpWimboot(INT argc, CHAR **argv, CHAR *LunchFile)
1328 {
1329 int rc = 1;
1330 char *buf = NULL;
1331 DWORD size = 0;
1332 DWORD Pos;
1333
1334 #ifdef VTOY_32
1335 g_64bit_system = FALSE;
1336 #else
1337 g_64bit_system = TRUE;
1338 #endif
1339
1340 Log("VentoyJumpWimboot %dbit", g_64bit_system ? 64 : 32);
1341
1342 sprintf_s(LunchFile, MAX_PATH, "X:\\setup.exe");
1343
1344 ReadWholeFile2Buf("wimboot.data", &buf, &size);
1345 Log("wimboot.data size:%d", size);
1346
1347 memcpy(&g_os_param, buf, sizeof(ventoy_os_param));
1348 memcpy(&g_windows_data, buf + sizeof(ventoy_os_param), sizeof(ventoy_windows_data));
1349 memcpy(g_os_param_reserved, g_os_param.vtoy_reserved, sizeof(g_os_param_reserved));
1350
1351 if (g_os_param_reserved[0] == 1)
1352 {
1353 Log("break here for debug .....");
1354 goto End;
1355 }
1356
1357 // convert / to \\
1358 for (Pos = 0; Pos < sizeof(g_os_param.vtoy_img_path) && g_os_param.vtoy_img_path[Pos]; Pos++)
1359 {
1360 if (g_os_param.vtoy_img_path[Pos] == '/')
1361 {
1362 g_os_param.vtoy_img_path[Pos] = '\\';
1363 }
1364 }
1365
1366 if (g_os_param_reserved[0] == 2)
1367 {
1368 Log("skip hook for debug .....");
1369 rc = 0;
1370 goto End;
1371 }
1372
1373 rc = VentoyHook(&g_os_param);
1374
1375 End:
1376
1377 if (buf)
1378 {
1379 free(buf);
1380 }
1381
1382 return rc;
1383 }
1384
1385 static int ventoy_check_create_directory(void)
1386 {
1387 if (IsDirExist("ventoy"))
1388 {
1389 Log("ventoy directory already exist");
1390 }
1391 else
1392 {
1393 Log("ventoy directory not exist, now create it.");
1394 if (!CreateDirectoryA("ventoy", NULL))
1395 {
1396 Log("Failed to create ventoy directory err:%u", GetLastError());
1397 return 1;
1398 }
1399 }
1400
1401 return 0;
1402 }
1403
1404 static BOOL VentoyFindCmdLineStr(BYTE *buf, DWORD size)
1405 {
1406 DWORD i = 0;
1407 UINT32 uiDataChk;
1408 UINT32 uiDataHex = *(UINT32 *)(g_aucCmdLineHex);
1409
1410 for (i = 0; i < size - sizeof(g_aucCmdLineHex); i += 16)
1411 {
1412 uiDataChk = *(UINT32 *)(buf + i);
1413 if (uiDataChk == uiDataHex && memcmp(buf + i, g_aucCmdLineHex, sizeof(g_aucCmdLineHex)) == 0)
1414 {
1415 return TRUE;
1416 }
1417 }
1418
1419 return FALSE;
1420 }
1421
1422 int VentoyJump(INT argc, CHAR **argv, CHAR *LunchFile)
1423 {
1424 int rc = 1;
1425 int stat = 0;
1426 DWORD Pos;
1427 DWORD PeStart;
1428 DWORD FileSize;
1429 DWORD LockStatus = 0;
1430 BYTE *Buffer = NULL;
1431 CHAR ExeFileName[MAX_PATH];
1432
1433 sprintf_s(ExeFileName, sizeof(ExeFileName), "%s", argv[0]);
1434 if (!IsFileExist("%s", ExeFileName))
1435 {
1436 Log("File %s NOT exist, now try %s.exe", ExeFileName, ExeFileName);
1437 sprintf_s(ExeFileName, sizeof(ExeFileName), "%s.exe", argv[0]);
1438
1439 Log("File %s exist ? %s", ExeFileName, IsFileExist("%s", ExeFileName) ? "YES" : "NO");
1440 }
1441
1442 if (ReadWholeFile2Buf(ExeFileName, (void **)&Buffer, &FileSize))
1443 {
1444 goto End;
1445 }
1446
1447 g_64bit_system = IsPe64(Buffer);
1448 Log("VentoyJump %dbit", g_64bit_system ? 64 : 32);
1449
1450 MUTEX_LOCK(g_vtoyins_mutex);
1451 stat = ventoy_check_create_directory();
1452 MUTEX_UNLOCK(g_vtoyins_mutex);
1453
1454 if (stat != 0)
1455 {
1456 goto End;
1457 }
1458
1459 for (PeStart = 0; PeStart < FileSize; PeStart += 16)
1460 {
1461 if (CheckOsParam((ventoy_os_param *)(Buffer + PeStart)) &&
1462 CheckPeHead(Buffer + PeStart + sizeof(ventoy_os_param) + sizeof(ventoy_windows_data)))
1463 {
1464 Log("Find os pararm at %u", PeStart);
1465
1466 memcpy(&g_os_param, Buffer + PeStart, sizeof(ventoy_os_param));
1467 memcpy(&g_windows_data, Buffer + PeStart + sizeof(ventoy_os_param), sizeof(ventoy_windows_data));
1468 memcpy(g_os_param_reserved, g_os_param.vtoy_reserved, sizeof(g_os_param_reserved));
1469
1470 if (g_os_param_reserved[0] == 1)
1471 {
1472 Log("break here for debug .....");
1473 goto End;
1474 }
1475
1476 // convert / to \\
1477 for (Pos = 0; Pos < sizeof(g_os_param.vtoy_img_path) && g_os_param.vtoy_img_path[Pos]; Pos++)
1478 {
1479 if (g_os_param.vtoy_img_path[Pos] == '/')
1480 {
1481 g_os_param.vtoy_img_path[Pos] = '\\';
1482 }
1483 }
1484
1485 PeStart += sizeof(ventoy_os_param) + sizeof(ventoy_windows_data);
1486 sprintf_s(LunchFile, MAX_PATH, "ventoy\\%s", GetFileNameInPath(ExeFileName));
1487
1488 MUTEX_LOCK(g_vtoyins_mutex);
1489 if (IsFileExist("%s", LunchFile))
1490 {
1491 Log("vtoyjump multiple call ...");
1492 rc = 0;
1493 MUTEX_UNLOCK(g_vtoyins_mutex);
1494 goto End;
1495 }
1496
1497 SaveBuffer2File(LunchFile, Buffer + PeStart, FileSize - PeStart);
1498 MUTEX_UNLOCK(g_vtoyins_mutex);
1499
1500 #ifdef VTOY_REJUMP_SUPPORTED
1501 if (_stricmp(LunchFile, "ventoy\\PECMD.EXE") == 0)
1502 {
1503 g_PecmdHasCmdLine = VentoyFindCmdLineStr(Buffer + PeStart, FileSize - PeStart);
1504 }
1505 #endif
1506
1507 break;
1508 }
1509 }
1510
1511 if (PeStart >= FileSize)
1512 {
1513 Log("OS param not found");
1514 goto End;
1515 }
1516
1517 if (g_os_param_reserved[0] == 2)
1518 {
1519 Log("skip hook for debug .....");
1520 rc = 0;
1521 goto End;
1522 }
1523
1524 rc = VentoyHook(&g_os_param);
1525
1526 End:
1527
1528 if (Buffer)
1529 {
1530 free(Buffer);
1531 }
1532
1533 return rc;
1534 }
1535
1536
1537
1538 static int ventoy_append_process_id(const char *pidfile)
1539 {
1540 DWORD PID = 0;
1541 FILE *fp = NULL;
1542
1543 PID = GetCurrentProcessId();
1544
1545 fopen_s(&fp, pidfile, "a+");
1546 if (!fp)
1547 {
1548 return 1;
1549 }
1550
1551 fprintf_s(fp, "%u\n", PID);
1552
1553 fclose(fp);
1554 return 0;
1555 }
1556
1557 static int ventoy_get_instance_id(const char *pidfile)
1558 {
1559 int instance = 0;
1560 FILE *fp = NULL;
1561 char line[256];
1562
1563 fopen_s(&fp, pidfile, "r");
1564 if (!fp)
1565 {
1566 return 1;
1567 }
1568
1569 while (fgets(line, sizeof(line), fp))
1570 {
1571 instance++;
1572 }
1573
1574 fclose(fp);
1575 return instance + 1;
1576 }
1577
1578 int main(int argc, char **argv)
1579 {
1580 int i = 0;
1581 int rc = 0;
1582 int id = 0;
1583 BOOL ReJump = FALSE;
1584 CHAR *Pos = NULL;
1585 CHAR CurDir[MAX_PATH];
1586 CHAR LunchFile[MAX_PATH];
1587 CHAR CallParam[1024] = { 0 };
1588 DWORD LockStatus = 0;
1589 STARTUPINFOA Si;
1590 PROCESS_INFORMATION Pi;
1591
1592 #ifdef VTOY_REJUMP_SUPPORTED
1593 if (argv[0] && strcmp(argv[0], "ventoy\\WinLogon.exe") == 0)
1594 {
1595 GetStartupInfoA(&Si);
1596 Si.dwFlags |= STARTF_USESHOWWINDOW;
1597 Si.wShowWindow = SW_HIDE;
1598
1599 sprintf_s(LunchFile, sizeof(LunchFile), "PECMD.EXE");
1600 for (i = 1; i < argc; i++)
1601 {
1602 strcat_s(LunchFile, sizeof(LunchFile), " ");
1603 strcat_s(LunchFile, sizeof(LunchFile), argv[i]);
1604 }
1605
1606 CreateProcessA(NULL, LunchFile, NULL, NULL, FALSE, 0, NULL, NULL, &Si, &Pi);
1607 WaitForSingleObject(Pi.hProcess, INFINITE);
1608 return 0;
1609 }
1610 #endif
1611
1612 g_PecmdHasCmdLine = 0;
1613 g_vtoylog_mutex = CreateMutexA(NULL, FALSE, "VTOYLOG_LOCK");
1614 g_vtoyins_mutex = CreateMutexA(NULL, FALSE, "VTOYINS_LOCK");
1615
1616 MUTEX_LOCK(g_vtoyins_mutex);
1617 if (IsFileExist(VTOY_PID_FILE))
1618 {
1619 id = ventoy_get_instance_id(VTOY_PID_FILE);
1620 }
1621 else
1622 {
1623 id = 1;
1624 }
1625 ventoy_append_process_id(VTOY_PID_FILE);
1626 MUTEX_UNLOCK(g_vtoyins_mutex);
1627
1628 if (argv[0] && argv[0][0] && argv[0][1] == ':')
1629 {
1630 GetCurrentDirectoryA(sizeof(CurDir), CurDir);
1631
1632 strcpy_s(LunchFile, sizeof(LunchFile), argv[0]);
1633 Pos = (char *)GetFileNameInPath(LunchFile);
1634
1635 strcat_s(CurDir, sizeof(CurDir), "\\");
1636 strcat_s(CurDir, sizeof(CurDir), Pos);
1637
1638 if (_stricmp(argv[0], CurDir) != 0)
1639 {
1640 *Pos = 0;
1641 SetCurrentDirectoryA(LunchFile);
1642 }
1643 }
1644
1645 #ifdef VTOY_32
1646 Log("######## VentoyJump 32bit [%d] ##########", id);
1647 #else
1648 Log("######## VentoyJump 64bit [%d] ##########", id);
1649 #endif
1650
1651 Log("argc = %d", argc);
1652 for (i = 0; i < argc; i++)
1653 {
1654 Log("argv[%d]=<%s>", i, argv[i]);
1655 if (i > 0)
1656 {
1657 strcat_s(CallParam, sizeof(CallParam), " ");
1658 strcat_s(CallParam, sizeof(CallParam), argv[i]);
1659 }
1660 }
1661
1662 if (Pos && *Pos == 0)
1663 {
1664 Log("Old current directory = <%s>", CurDir);
1665 Log("New current directory = <%s>", LunchFile);
1666 }
1667 else
1668 {
1669 GetCurrentDirectoryA(sizeof(CurDir), CurDir);
1670 Log("Current directory = <%s>", CurDir);
1671 }
1672
1673 GetStartupInfoA(&Si);
1674
1675 memset(LunchFile, 0, sizeof(LunchFile));
1676
1677 if (strstr(argv[0], "vtoyjump.exe"))
1678 {
1679 rc = VentoyJumpWimboot(argc, argv, LunchFile);
1680 }
1681 else
1682 {
1683 rc = VentoyJump(argc, argv, LunchFile);
1684 }
1685
1686 Log("id=%d LunchFile=<%s> CallParam=<%s>", id, LunchFile, CallParam);
1687
1688 if (id == 1 && _stricmp(argv[0], "PECMD.EXE") == 0 && _stricmp(LunchFile, "ventoy\\PECMD.EXE") == 0)
1689 {
1690 MUTEX_LOCK(g_vtoyins_mutex);
1691 id = ventoy_get_instance_id(VTOY_PID_FILE);
1692 MUTEX_UNLOCK(g_vtoyins_mutex);
1693
1694 Log("Current instance id is: %d", id);
1695
1696 if (id == 2)
1697 {
1698 #ifdef VTOY_REJUMP_SUPPORTED
1699 if (g_PecmdHasCmdLine)
1700 {
1701 ReJump = TRUE;
1702 CopyFileA("PECMD.EXE", "ventoy\\WinLogon.exe", TRUE);
1703 }
1704 #endif
1705
1706 MoveFileA("PECMD.EXE", "PECMD_BACK.EXE");
1707 CopyFileA("ventoy\\PECMD.EXE", "PECMD.EXE", TRUE);
1708 sprintf_s(LunchFile, sizeof(LunchFile), "%s", "PECMD.EXE");
1709 Log("Move original PECMD.EXE <%s>", LunchFile);
1710 }
1711 else
1712 {
1713 Log("%d instance started, don't move PECMD.EXE", id);
1714 }
1715 }
1716
1717 if (g_os_param_reserved[0] == 3)
1718 {
1719 Log("Open log for debug ...");
1720 sprintf_s(LunchFile, sizeof(LunchFile), "%s", "notepad.exe ventoy.log");
1721 }
1722 else
1723 {
1724 if (CallParam[0])
1725 {
1726 strcat_s(LunchFile, sizeof(LunchFile), CallParam);
1727 }
1728 else if (NULL == strstr(LunchFile, "setup.exe"))
1729 {
1730 Log("Not setup.exe, hide windows.");
1731 Si.dwFlags |= STARTF_USESHOWWINDOW;
1732 Si.wShowWindow = SW_HIDE;
1733 }
1734
1735 Log("Ventoy jump %s ...", rc == 0 ? "success" : "failed");
1736 }
1737
1738 Log("Now launch <%s> ...", LunchFile);
1739
1740 if (g_os_param_reserved[0] == 4)
1741 {
1742 Log("Open cmd for debug ...");
1743 sprintf_s(LunchFile, sizeof(LunchFile), "%s", "cmd.exe");
1744 }
1745
1746 #ifdef VTOY_REJUMP_SUPPORTED
1747 if (ReJump)
1748 {
1749 sprintf_s(CallParam, sizeof(CallParam), "ventoy\\WinLogon.exe%s", LunchFile + strlen("PECMD.EXE"));
1750 Log("Now rejump to pecmd.exe <%s> ...", CallParam);
1751
1752 CreateProcessA(NULL, CallParam, NULL, NULL, FALSE, 0, NULL, NULL, &Si, &Pi);
1753
1754 Log("Wait rejump process...");
1755 WaitForSingleObject(Pi.hProcess, INFINITE);
1756 Log("rejump finished");
1757 return 0;
1758 }
1759 #else
1760 (void)ReJump;
1761 #endif
1762
1763 CreateProcessA(NULL, LunchFile, NULL, NULL, FALSE, 0, NULL, NULL, &Si, &Pi);
1764
1765 for (i = 0; rc && i < 1800; i++)
1766 {
1767 Log("Ventoy hook failed, now wait and retry ...");
1768 Sleep(1000);
1769 rc = VentoyHook(&g_os_param);
1770 }
1771
1772 Log("Wait process...");
1773 WaitForSingleObject(Pi.hProcess, INFINITE);
1774
1775 Log("vtoyjump finished");
1776 return 0;
1777 }