ventoy_util.c 13.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/******************************************************************************
 * ventoy_util.c  ---- ventoy util
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <linux/fs.h>
#include <dirent.h>
#include <time.h>
#include <ventoy_define.h>
#include <ventoy_util.h>

uint8_t g_mbr_template[512];

void ventoy_gen_preudo_uuid(void *uuid)
{
    int i;
    int fd;

    fd = open("/dev/urandom", O_RDONLY | O_BINARY);
    if (fd < 0)
    {
        srand(time(NULL));
        for (i = 0; i < 8; i++)
        {
            *((uint16_t *)uuid + i) = (uint16_t)(rand() & 0xFFFF);
        }
    }
    else
    {
        read(fd, uuid, 16);
        close(fd);
    }
}

uint64_t ventoy_get_human_readable_gb(uint64_t SizeBytes)
{
    int i;
    int Pow2 = 1;
    double Delta;
    double GB = SizeBytes * 1.0 / 1000 / 1000 / 1000;

    if ((SizeBytes % SIZE_1GB) == 0)
    {
        return (uint64_t)(SizeBytes / SIZE_1GB);
    }

    for (i = 0; i < 12; i++)
    {
        if (Pow2 > GB)
        {
            Delta = (Pow2 - GB) / Pow2;
        }
        else
        {
            Delta = (GB - Pow2) / Pow2;
        }

        if (Delta < 0.05)
        {
            return Pow2;
        }

        Pow2 <<= 1;
    }

    return (uint64_t)GB;
}


int ventoy_get_sys_file_line(char *buffer, int buflen, const char *fmt, ...)
{
    int len;
    char c;
    char path[256];
    va_list arg;

    va_start(arg, fmt);
    vsnprintf(path, 256, fmt, arg);
    va_end(arg);

    if (access(path, F_OK) >= 0)
    {
        FILE *fp = fopen(path, "r");
        memset(buffer, 0, buflen);
        len = (int)fread(buffer, 1, buflen - 1, fp);
        fclose(fp);

        while (len > 0)
        {
            c = buffer[len - 1];
            if (c == '\r' || c == '\n' || c == ' ' || c == '\t')
            {
                buffer[len - 1] = 0;
                len--;
            }
            else
            {
                break;
            }
        }
        
        return 0;
    }
    else
    {
        vdebug("%s not exist \n", path);
        return 1;
    }
}

int ventoy_is_disk_mounted(const char *devpath)
{
    int len;
    int mount = 0;
    char line[512];
    FILE *fp = NULL;

    fp = fopen("/proc/mounts", "r");
    if (!fp)
    {
        return 0;
    }

    len = (int)strlen(devpath);
    while (fgets(line, sizeof(line), fp))
    {
        if (strncmp(line, devpath, len) == 0)
        {
            mount = 1;
            vdebug("%s mounted <%s>\n", devpath, line);
            goto end;
        }
    }

end:
    fclose(fp);
    return mount;
}

167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
static int ventoy_mount_path_escape(char *src, char *dst, int len)
{
    int i = 0;
    int n = 0;
    
    dst[len - 1] = 0;

    for (i = 0; i < len - 1; i++)
    {
        if (src[i] == '\\' && src[i + 1] == '0' && src[i + 2] == '4' && src[i + 3] == '0')
        {
            dst[n++] = ' ';
            i += 3;
        }
        else
        {
            dst[n++] = src[i];
        }
    
        if (src[i] == 0)
        {
            break;
        }
    }

    return 0;
}

195
196
197
198
int ventoy_try_umount_disk(const char *devpath)
{
    int rc;
    int len;
199
200
    char line[1024];
    char mntpt[1024];
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
    char *pos1 = NULL;
    char *pos2 = NULL;
    FILE *fp = NULL;

    fp = fopen("/proc/mounts", "r");
    if (!fp)
    {
        return 0;
    }

    len = (int)strlen(devpath);
    while (fgets(line, sizeof(line), fp))
    {
        if (strncmp(line, devpath, len) == 0)
        {
            pos1 = strchr(line, ' ');
            if (pos1)
            {
                pos2 = strchr(pos1 + 1, ' ');
                if (pos2)
                {
                    *pos2 = 0;
                }

225
226
                ventoy_mount_path_escape(pos1 + 1, mntpt, sizeof(mntpt));                
                rc = umount(mntpt);
227
228
                if (rc)
                {
229
                    vdebug("umount <%s> <%s> [ failed ] error:%d\n", devpath, mntpt, errno);                                        
230
231
232
                }
                else
                {
233
                    vdebug("umount <%s> <%s> [ success ]\n", devpath, mntpt);
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
                }
            }
        }
    }

    fclose(fp);
    return 0;
}

int ventoy_read_file_to_buf(const char *FileName, int ExtLen, void **Bufer, int *BufLen)
{
    int FileSize;
    FILE *fp = NULL;
    void *Data = NULL;

    fp = fopen(FileName, "rb");
    if (fp == NULL)
    {
        vlog("Failed to open file %s", FileName);
        return 1;
    }

    fseek(fp, 0, SEEK_END);
    FileSize = (int)ftell(fp);

    Data = malloc(FileSize + ExtLen);
    if (!Data)
    {
        fclose(fp);
        return 1;
    }

    fseek(fp, 0, SEEK_SET);
    fread(Data, 1, FileSize, fp);

    fclose(fp);

    *Bufer = Data;
    *BufLen = FileSize;

    return 0;
}

const char * ventoy_get_local_version(void)
{
    int rc;
    int FileSize;
    char *Pos = NULL;
    char *Buf = NULL;
    static char LocalVersion[64] = { 0 };

    if (LocalVersion[0] == 0)
    {
        rc = ventoy_read_file_to_buf("ventoy/version", 1, (void **)&Buf, &FileSize);
        if (rc)
        {
            return "";
        }
        Buf[FileSize] = 0;

        for (Pos = Buf; *Pos; Pos++)
        {
            if (*Pos == '\r' || *Pos == '\n')
            {
                *Pos = 0;
                break;
            }
        }

        scnprintf(LocalVersion, "%s", Buf);
        free(Buf);
    }
    
    return LocalVersion;
}

int VentoyGetLocalBootImg(MBR_HEAD *pMBR)
{
    memcpy(pMBR, g_mbr_template, 512);
    return 0;    
}

static int VentoyFillProtectMBR(uint64_t DiskSizeBytes, MBR_HEAD *pMBR)
{
    ventoy_guid Guid;
    uint32_t DiskSignature;
    uint64_t DiskSectorCount;

    VentoyGetLocalBootImg(pMBR);

    ventoy_gen_preudo_uuid(&Guid);

    memcpy(&DiskSignature, &Guid, sizeof(uint32_t));

    vdebug("Disk signature: 0x%08x\n", DiskSignature);

    memcpy(pMBR->BootCode + 0x1B8, &DiskSignature, 4);
longpanda's avatar
longpanda committed
331
    memcpy(pMBR->BootCode + 0x180, &Guid, 16);
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379

    DiskSectorCount = DiskSizeBytes / 512 - 1;
    if (DiskSectorCount > 0xFFFFFFFF)
    {
        DiskSectorCount = 0xFFFFFFFF;
    }

    memset(pMBR->PartTbl, 0, sizeof(pMBR->PartTbl));

    pMBR->PartTbl[0].Active = 0x00;
    pMBR->PartTbl[0].FsFlag = 0xee; // EE

    pMBR->PartTbl[0].StartHead = 0;
    pMBR->PartTbl[0].StartSector = 1;
    pMBR->PartTbl[0].StartCylinder = 0;
    pMBR->PartTbl[0].EndHead = 254;
    pMBR->PartTbl[0].EndSector = 63;
    pMBR->PartTbl[0].EndCylinder = 1023;

    pMBR->PartTbl[0].StartSectorId = 1;
    pMBR->PartTbl[0].SectorCount = (uint32_t)DiskSectorCount;

    pMBR->Byte55 = 0x55;
    pMBR->ByteAA = 0xAA;

    pMBR->BootCode[92] = 0x22;

    return 0;
}

static int ventoy_fill_gpt_partname(uint16_t Name[36], const char *asciiName)
{
    int i;
    int len;

    memset(Name, 0, 36 * sizeof(uint16_t));
    len = (int)strlen(asciiName);
    for (i = 0; i < 36 && i < len; i++)
    {
        Name[i] = asciiName[i];
    }
    
    return 0;
}

int ventoy_fill_gpt(uint64_t size, uint64_t reserve, int align4k, VTOY_GPT_INFO *gpt)
{
    uint64_t ReservedSector = 33;
longpanda's avatar
longpanda committed
380
    uint64_t ModSectorCount = 0;
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
    uint64_t Part1SectorCount = 0;
    uint64_t DiskSectorCount = size / 512;
    VTOY_GPT_HDR *Head = &gpt->Head;
    VTOY_GPT_PART_TBL *Table = gpt->PartTbl;
    ventoy_guid WindowsDataPartType = { 0xebd0a0a2, 0xb9e5, 0x4433, { 0x87, 0xc0, 0x68, 0xb6, 0xb7, 0x26, 0x99, 0xc7 } };
    //ventoy_guid EspPartType = { 0xc12a7328, 0xf81f, 0x11d2, { 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b } };
	//ventoy_guid BiosGrubPartType = { 0x21686148, 0x6449, 0x6e6f, { 0x74, 0x4e, 0x65, 0x65, 0x64, 0x45, 0x46, 0x49 } };

    VentoyFillProtectMBR(size, &gpt->MBR);

    if (reserve > 0)
    {
        ReservedSector += reserve / 512;
    }

longpanda's avatar
longpanda committed
396
397
398
399
400
401
402
403
    Part1SectorCount = DiskSectorCount - ReservedSector - (VTOYEFI_PART_BYTES / 512) - 2048;

    ModSectorCount = (Part1SectorCount % 8);
    if (ModSectorCount)
    {
        vlog("Part1SectorCount:%llu is not aligned by 4KB (%llu)\n", (_ull)Part1SectorCount, (_ull)ModSectorCount);
    }

404
405
406
    // check aligned with 4KB
    if (align4k)
    {
longpanda's avatar
longpanda committed
407
        if (ModSectorCount)
408
        {
longpanda's avatar
longpanda committed
409
410
411
412
413
414
            vdebug("Disk need to align with 4KB %u\n", (uint32_t)ModSectorCount);
            Part1SectorCount -= ModSectorCount;
        }
        else
        {
            vdebug("no need to align with 4KB\n");
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
        }
    }

    memcpy(Head->Signature, "EFI PART", 8);
    Head->Version[2] = 0x01;
    Head->Length = 92;
    Head->Crc = 0;
    Head->EfiStartLBA = 1;
    Head->EfiBackupLBA = DiskSectorCount - 1;
    Head->PartAreaStartLBA = 34;
    Head->PartAreaEndLBA = DiskSectorCount - 34;
    ventoy_gen_preudo_uuid(&Head->DiskGuid);
    Head->PartTblStartLBA = 2;
    Head->PartTblTotNum = 128;
    Head->PartTblEntryLen = 128;


    memcpy(&(Table[0].PartType), &WindowsDataPartType, sizeof(ventoy_guid));
    ventoy_gen_preudo_uuid(&(Table[0].PartGuid));
    Table[0].StartLBA = 2048;
    Table[0].LastLBA = 2048 + Part1SectorCount - 1;
    Table[0].Attr = 0;
    ventoy_fill_gpt_partname(Table[0].Name, "Ventoy");

    // to fix windows issue
    //memcpy(&(Table[1].PartType), &EspPartType, sizeof(GUID));
    memcpy(&(Table[1].PartType), &WindowsDataPartType, sizeof(ventoy_guid));
    ventoy_gen_preudo_uuid(&(Table[1].PartGuid));
    Table[1].StartLBA = Table[0].LastLBA + 1;
    Table[1].LastLBA = Table[1].StartLBA + VTOYEFI_PART_BYTES / 512 - 1;
445
    Table[1].Attr = 0xC000000000000001ULL;
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
    ventoy_fill_gpt_partname(Table[1].Name, "VTOYEFI");

#if 0
	memcpy(&(Table[2].PartType), &BiosGrubPartType, sizeof(ventoy_guid));
	ventoy_gen_preudo_uuid(&(Table[2].PartGuid));
	Table[2].StartLBA = 34;
	Table[2].LastLBA = 2047;
	Table[2].Attr = 0;
#endif

    //Update CRC
    Head->PartTblCrc = ventoy_crc32(Table, sizeof(gpt->PartTbl));
    Head->Crc = ventoy_crc32(Head, Head->Length);

    return 0;
}

int VentoyFillMBRLocation(uint64_t DiskSizeInBytes, uint32_t StartSectorId, uint32_t SectorCount, PART_TABLE *Table)
{
    uint8_t Head;
    uint8_t Sector;
    uint8_t nSector = 63;
    uint8_t nHead = 8;    
    uint32_t Cylinder;
    uint32_t EndSectorId;

    while (nHead != 0 && (DiskSizeInBytes / 512 / nSector / nHead) > 1024)
    {
        nHead = (uint8_t)nHead * 2;
    }

    if (nHead == 0)
    {
        nHead = 255;
    }

    Cylinder = StartSectorId / nSector / nHead;
    Head = StartSectorId / nSector % nHead;
    Sector = StartSectorId % nSector + 1;

    Table->StartHead = Head;
    Table->StartSector = Sector;
    Table->StartCylinder = Cylinder;

    EndSectorId = StartSectorId + SectorCount - 1;
    Cylinder = EndSectorId / nSector / nHead;
    Head = EndSectorId / nSector % nHead;
    Sector = EndSectorId % nSector + 1;

    Table->EndHead = Head;
    Table->EndSector = Sector;
    Table->EndCylinder = Cylinder;

    Table->StartSectorId = StartSectorId;
    Table->SectorCount = SectorCount;

    return 0;
}

longpanda's avatar
longpanda committed
505
int ventoy_fill_mbr(uint64_t size, uint64_t reserve, int align4k, MBR_HEAD *pMBR)
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
{
    ventoy_guid Guid;
    uint32_t DiskSignature;
    uint32_t DiskSectorCount;
    uint32_t PartSectorCount;
    uint32_t PartStartSector;
	uint32_t ReservedSector;

    VentoyGetLocalBootImg(pMBR);

    ventoy_gen_preudo_uuid(&Guid);

    memcpy(&DiskSignature, &Guid, sizeof(uint32_t));

    vdebug("Disk signature: 0x%08x\n", DiskSignature);

    memcpy(pMBR->BootCode + 0x1B8, &DiskSignature, 4);
longpanda's avatar
longpanda committed
523
    memcpy(pMBR->BootCode + 0x180, &Guid, 16);
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551

    if (size / 512 > 0xFFFFFFFF)
    {
        DiskSectorCount = 0xFFFFFFFF;
    }
    else
    {
        DiskSectorCount = (uint32_t)(size / 512);
    }

	if (reserve <= 0)
	{
		ReservedSector = 0;
	}
	else
	{
		ReservedSector = (uint32_t)(reserve / 512);
	}

    // check aligned with 4KB
    if (align4k)
    {
        uint64_t sectors = size / 512;
        if (sectors % 8)
        {
            vlog("Disk need to align with 4KB %u\n", (uint32_t)(sectors % 8));
            ReservedSector += (uint32_t)(sectors % 8);
        }
longpanda's avatar
longpanda committed
552
553
554
555
        else
        {
            vdebug("no need to align with 4KB\n");
        }
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
    }

	vlog("ReservedSector: %u\n", ReservedSector);

    //Part1
    PartStartSector = VTOYIMG_PART_START_SECTOR;
	PartSectorCount = DiskSectorCount - ReservedSector - VTOYEFI_PART_BYTES / 512 - PartStartSector;
    VentoyFillMBRLocation(size, PartStartSector, PartSectorCount, pMBR->PartTbl);

    pMBR->PartTbl[0].Active = 0x80; // bootable
    pMBR->PartTbl[0].FsFlag = 0x07; // exFAT/NTFS/HPFS

    //Part2
    PartStartSector += PartSectorCount;
    PartSectorCount = VTOYEFI_PART_BYTES / 512;
    VentoyFillMBRLocation(size, PartStartSector, PartSectorCount, pMBR->PartTbl + 1);

    pMBR->PartTbl[1].Active = 0x00; 
    pMBR->PartTbl[1].FsFlag = 0xEF; // EFI System Partition

    pMBR->Byte55 = 0x55;
    pMBR->ByteAA = 0xAA;

    return 0;
}