ventoy_http.c 42.5 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
/******************************************************************************
 * ventoy_http.c  ---- ventoy http
 * 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>
longpanda's avatar
longpanda committed
34
#include <linux/limits.h>
35
36
37
38
39
40
41
42
43
#include <dirent.h>
#include <pthread.h>
#include <ventoy_define.h>
#include <ventoy_json.h>
#include <ventoy_util.h>
#include <ventoy_disk.h>
#include <ventoy_http.h>
#include "fat_filelib.h"

44
45
46
static char *g_pub_out_buf = NULL;
static int g_pub_out_max = 0;

47
48
49
static pthread_mutex_t g_api_mutex;
static char g_cur_language[128];
static int  g_cur_part_style = 0;
50
static int  g_cur_show_all = 0;
51
52
53
54
55
56
57
58
59
static char g_cur_server_token[64];
static struct mg_context *g_ventoy_http_ctx = NULL;

static uint32_t g_efi_part_offset = 0;
static uint8_t *g_efi_part_raw_img = NULL;
static uint8_t *g_grub_stg1_raw_img = NULL;

static char g_cur_process_diskname[64];
static char g_cur_process_type[64];
60
61
static volatile int g_cur_process_result = 0;
static volatile PROGRESS_POINT g_current_progress = PT_FINISH;
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

static int ventoy_load_mbr_template(void)
{
    FILE *fp = NULL;

    fp = fopen("boot/boot.img", "rb");
    if (fp == NULL)
    {
        vlog("Failed to open file boot/boot.img\n");
        return 1;
    }

    fread(g_mbr_template, 1, 512, fp);
    fclose(fp);
    
    ventoy_gen_preudo_uuid(g_mbr_template + 0x180);    
    return 0;
}

static int ventoy_disk_xz_flush(void *src, unsigned int size)
{
    memcpy(g_efi_part_raw_img + g_efi_part_offset, src, size);
    g_efi_part_offset += size;

    g_current_progress = PT_LOAD_DISK_IMG + (g_efi_part_offset / SIZE_1MB);
    return (int)size;
}

static int ventoy_unxz_efipart_img(void)
{
    int rc;
    int inlen;
    int xzlen;
    void *xzbuf = NULL;
    uint8_t *buf = NULL;

    rc = ventoy_read_file_to_buf(VENTOY_FILE_DISK_IMG, 0, &xzbuf, &xzlen);
    vdebug("read disk.img.xz rc:%d len:%d\n", rc, xzlen);

    if (g_efi_part_raw_img)
    {
        buf = g_efi_part_raw_img;
    }
    else
    {
        buf = malloc(VTOYEFI_PART_BYTES);
        if (!buf)
        {
            check_free(xzbuf);
            return 1;
        }
    }

    g_efi_part_offset = 0;
    g_efi_part_raw_img = buf;
    
    rc = unxz(xzbuf, xzlen, NULL, ventoy_disk_xz_flush, buf, &inlen, NULL);
    vdebug("ventoy_unxz_efipart_img len:%d rc:%d unxzlen:%u\n", inlen, rc, g_efi_part_offset);

    check_free(xzbuf);
    return 0;
}

static int ventoy_unxz_stg1_img(void)
{
    int rc;
    int inlen;
    int xzlen;
    void *xzbuf = NULL;
    uint8_t *buf = NULL;

    rc = ventoy_read_file_to_buf(VENTOY_FILE_STG1_IMG, 0, &xzbuf, &xzlen);
    vdebug("read core.img.xz rc:%d len:%d\n", rc, xzlen);

    if (g_grub_stg1_raw_img)
    {
        buf = g_grub_stg1_raw_img;
    }
    else
    {
        buf = zalloc(SIZE_1MB);
        if (!buf)
        {
            check_free(xzbuf);
            return 1;
        }
    }
    
    rc = unxz(xzbuf, xzlen, NULL, NULL, buf, &inlen, NULL);
    vdebug("ventoy_unxz_stg1_img len:%d rc:%d\n", inlen, rc);

    g_grub_stg1_raw_img = buf;

    check_free(xzbuf);
    return 0;
}


static int ventoy_http_save_cfg(void)
{
    FILE *fp;

longpanda's avatar
longpanda committed
164
    fp = fopen(g_ini_file, "w");
165
166
    if (!fp)
    {
longpanda's avatar
longpanda committed
167
        vlog("Failed to open %s code:%d\n", g_ini_file, errno);
168
169
170
        return 0;
    }

171
172
    fprintf(fp, "[Ventoy]\nLanguage=%s\nPartStyle=%d\nShowAllDevice=%d\n", 
        g_cur_language, g_cur_part_style, g_cur_show_all);
173
174
175
176
177
178
179
180
181
182
183
184

    fclose(fp);
    return 0;
}

static int ventoy_http_load_cfg(void)
{
    int i;
    int len;
    char line[256];
    FILE *fp;

longpanda's avatar
longpanda committed
185
    fp = fopen(g_ini_file, "r");
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
    if (!fp)
    {
        return 0;
    }

    while (fgets(line, sizeof(line), fp))
    {
        len = (int)strlen(line);
        for (i = len - 1; i >= 0; i--)
        {
            if (line[i] == ' ' || line[i] == '\t' || line[i] == '\r' || line[i] == '\n')
            {
                line[i] = 0;
            }
            else
            {
                break;
            }
        }
    
        len = (int)strlen("Language=");
        if (strncmp(line, "Language=", len) == 0)
        {
            scnprintf(g_cur_language, "%s", line + len);
        }
        else if (strncmp(line, "PartStyle=", strlen("PartStyle=")) == 0)
        {
            g_cur_part_style = (int)strtol(line + strlen("PartStyle="), NULL, 10);
        }
215
216
217
218
        else if (strncmp(line, "ShowAllDevice=", strlen("ShowAllDevice=")) == 0)
        {
            g_cur_show_all = (int)strtol(line + strlen("ShowAllDevice="), NULL, 10);
        }
219
220
221
222
223
224
225
226
227
    }

    fclose(fp);
    return 0;
}


static int ventoy_json_result(struct mg_connection *conn, const char *err)
{
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    if (conn)
    {
        mg_printf(conn, 
                  "HTTP/1.1 200 OK \r\n"
                  "Content-Type: application/json\r\n"
                  "Content-Length: %d\r\n"
                  "\r\n%s",
                  (int)strlen(err), err);
    }
    else
    {
        memcpy(g_pub_out_buf, err, (int)strlen(err) + 1);
    }

242
243
244
245
246
    return 0;
}

static int ventoy_json_buffer(struct mg_connection *conn, const char *json_buf, int json_len)
{
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
    if (conn)
    {
        mg_printf(conn, 
                  "HTTP/1.1 200 OK \r\n"
                  "Content-Type: application/json\r\n"
                  "Content-Length: %d\r\n"
                  "\r\n%s",
                  json_len, json_buf);    
    }
    else
    {
        if (json_len >= g_pub_out_max)
        {
            vlog("json buffer overflow\n");
        }
        else
        {
            memcpy(g_pub_out_buf, json_buf, json_len);
            g_pub_out_buf[json_len] = 0;
        }
    }

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
331
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
380
381
382
383
    return 0;
}

static int ventoy_api_sysinfo(struct mg_connection *conn, VTOY_JSON *json)
{
    int busy = 0;
    int pos = 0;
    int buflen = 0;
    char buf[512];
    
    (void)json;

    busy = (g_current_progress == PT_FINISH) ? 0 : 1;

    buflen = sizeof(buf) - 1;
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_STRN("token", g_cur_server_token);
    VTOY_JSON_FMT_STRN("language", g_cur_language);
    VTOY_JSON_FMT_STRN("ventoy_ver", ventoy_get_local_version());
    VTOY_JSON_FMT_UINT("partstyle", g_cur_part_style);
    VTOY_JSON_FMT_BOOL("busy", busy);
    VTOY_JSON_FMT_STRN("process_disk", g_cur_process_diskname);
    VTOY_JSON_FMT_STRN("process_type", g_cur_process_type);
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);

    ventoy_json_buffer(conn, buf, pos);
    return 0;
}

static int ventoy_api_get_percent(struct mg_connection *conn, VTOY_JSON *json)
{
    int pos = 0;
    int buflen = 0;
    int percent = 0;
    char buf[128];
    
    (void)json;

    percent = g_current_progress * 100 / PT_FINISH;

    buflen = sizeof(buf) - 1;
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_STRN("result", g_cur_process_result ? "failed" : "success");
    VTOY_JSON_FMT_STRN("process_disk", g_cur_process_diskname);
    VTOY_JSON_FMT_STRN("process_type", g_cur_process_type);
    VTOY_JSON_FMT_UINT("percent", percent);
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);

    ventoy_json_buffer(conn, buf, pos);
    return 0;
}

static int ventoy_api_set_language(struct mg_connection *conn, VTOY_JSON *json)
{
    const char *lang = NULL;
    
    lang = vtoy_json_get_string_ex(json, "language");
    if (lang)
    {
        scnprintf(g_cur_language, "%s", lang);
        ventoy_http_save_cfg();
    }

    ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
    return 0;    
}

static int ventoy_api_set_partstyle(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int style = 0;
    
    ret = vtoy_json_get_int(json, "partstyle", &style);
    if (JSON_SUCCESS == ret)
    {
        if ((style == 0) || (style == 1))
        {
            g_cur_part_style = style;
            ventoy_http_save_cfg();            
        }
    }

    ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
    return 0;    
}

static int ventoy_clean_disk(int fd, uint64_t size)
{
    int zerolen;
    ssize_t len;
    off_t offset;
    void *buf = NULL;
    
    vdebug("ventoy_clean_disk fd:%d size:%llu\n", fd, (_ull)size);

    zerolen = 64 * 1024;
    buf = zalloc(zerolen);
    if (!buf)
    {
        vlog("failed to alloc clean buffer\n");
        return 1;
    }

    offset = lseek(fd, 0, SEEK_SET);
    len = write(fd, buf, zerolen);
    vdebug("write disk at off:%llu writelen:%lld datalen:%d\n", (_ull)offset, (_ll)len, zerolen);

    offset = lseek(fd, size - zerolen, SEEK_SET);
    len = write(fd, buf, zerolen);
    vdebug("write disk at off:%llu writelen:%lld datalen:%d\n", (_ull)offset, (_ll)len, zerolen);

longpanda's avatar
longpanda committed
384
385
    fsync(fd);

386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
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
445
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
    free(buf);
    return 0;
}

static int ventoy_write_legacy_grub(int fd, int partstyle)
{
    ssize_t len;
    off_t offset;
    
    if (partstyle)
    {
        vlog("Write GPT stage1 ...\n");

        offset = lseek(fd, 512 * 34, SEEK_SET);

        g_grub_stg1_raw_img[500] = 35;//update blocklist
        len = write(fd, g_grub_stg1_raw_img, SIZE_1MB - 512 * 34);

        vlog("lseek offset:%llu(%u) writelen:%llu(%u)\n", (_ull)offset, 512 * 34, (_ull)len, SIZE_1MB - 512 * 34);
        if (SIZE_1MB - 512 * 34 != len)
        {
            vlog("write length error\n");
            return 1;
        }
    }
    else
    {
        vlog("Write MBR stage1 ...\n");
        offset = lseek(fd, 512, SEEK_SET);
        len = write(fd, g_grub_stg1_raw_img, SIZE_1MB - 512);
        
        vlog("lseek offset:%llu(%u) writelen:%llu(%u)\n", (_ull)offset, 512, (_ull)len, SIZE_1MB - 512);
        if (SIZE_1MB - 512 != len)
        {
            vlog("write length error\n");
            return 1;
        }
    }

    return 0;
}

static int VentoyFatMemRead(uint32 Sector, uint8 *Buffer, uint32 SectorCount)
{
	uint32 i;
	uint32 offset;

	for (i = 0; i < SectorCount; i++)
	{
		offset = (Sector + i) * 512;
        memcpy(Buffer + i * 512, g_efi_part_raw_img + offset, 512);
	}

	return 1;
}

static int VentoyFatMemWrite(uint32 Sector, uint8 *Buffer, uint32 SectorCount)
{
	uint32 i;
	uint32 offset;

	for (i = 0; i < SectorCount; i++)
	{
		offset = (Sector + i) * 512;
        memcpy(g_efi_part_raw_img + offset, Buffer + i * 512, 512);
	}

	return 1;
}

static int VentoyProcSecureBoot(int SecureBoot)
{
	int rc = 0;
	int size;
	char *filebuf = NULL;
	void *file = NULL;

	vlog("VentoyProcSecureBoot %d ...\n", SecureBoot);
	
	if (SecureBoot)
	{
		vlog("Secure boot is enabled ...\n");
		return 0;
	}

	fl_init();

	if (0 == fl_attach_media(VentoyFatMemRead, VentoyFatMemWrite))
	{
		file = fl_fopen("/EFI/BOOT/grubx64_real.efi", "rb");
		vlog("Open ventoy efi file %p \n", file);
		if (file)
		{
			fl_fseek(file, 0, SEEK_END);
			size = (int)fl_ftell(file);
			fl_fseek(file, 0, SEEK_SET);

			vlog("ventoy efi file size %d ...\n", size);

			filebuf = (char *)malloc(size);
			if (filebuf)
			{
				fl_fread(filebuf, 1, size, file);
			}

			fl_fclose(file);

			vlog("Now delete all efi files ...\n");
			fl_remove("/EFI/BOOT/BOOTX64.EFI");
			fl_remove("/EFI/BOOT/grubx64.efi");
			fl_remove("/EFI/BOOT/grubx64_real.efi");
			fl_remove("/EFI/BOOT/MokManager.efi");
498
			fl_remove("/EFI/BOOT/mmx64.efi");
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
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
552
553
554
555
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
            fl_remove("/ENROLL_THIS_KEY_IN_MOKMANAGER.cer");

			file = fl_fopen("/EFI/BOOT/BOOTX64.EFI", "wb");
			vlog("Open bootx64 efi file %p \n", file);
			if (file)
			{
				if (filebuf)
				{
					fl_fwrite(filebuf, 1, size, file);
				}
				
				fl_fflush(file);
				fl_fclose(file);
			}

			if (filebuf)
			{
				free(filebuf);
			}
		}

        file = fl_fopen("/EFI/BOOT/grubia32_real.efi", "rb");
        vlog("Open ventoy efi file %p\n", file);
        if (file)
        {
            fl_fseek(file, 0, SEEK_END);
            size = (int)fl_ftell(file);
            fl_fseek(file, 0, SEEK_SET);

            vlog("ventoy efi file size %d ...\n", size);

            filebuf = (char *)malloc(size);
            if (filebuf)
            {
                fl_fread(filebuf, 1, size, file);
            }

            fl_fclose(file);

            vlog("Now delete all efi files ...\n");
            fl_remove("/EFI/BOOT/BOOTIA32.EFI");
            fl_remove("/EFI/BOOT/grubia32.efi");
            fl_remove("/EFI/BOOT/grubia32_real.efi");
            fl_remove("/EFI/BOOT/mmia32.efi");            

            file = fl_fopen("/EFI/BOOT/BOOTIA32.EFI", "wb");
            vlog("Open bootia32 efi file %p\n", file);
            if (file)
            {
                if (filebuf)
                {
                    fl_fwrite(filebuf, 1, size, file);
                }

                fl_fflush(file);
                fl_fclose(file);
            }

            if (filebuf)
            {
                free(filebuf);
            }
        }

	}
	else
	{
		rc = 1;
	}

	fl_shutdown();

	return rc;
}

static int ventoy_check_efi_part_data(int fd, uint64_t offset)
{
    int i;
    ssize_t len;
    char *buf;

    buf = malloc(SIZE_1MB);
    if (!buf)
    {
        return 0;
    }
    
    lseek(fd, offset, SEEK_SET);
    for (i = 0; i < 32; i++)
    {
        len = read(fd, buf, SIZE_1MB);
        if (len != SIZE_1MB || memcmp(buf, g_efi_part_raw_img + i * SIZE_1MB, SIZE_1MB))
        {
            vlog("part2 data check failed i=%d len:%llu\n", i, (_ull)len);
            return 1;
        }

        g_current_progress = PT_CHECK_PART2 + (i / 4);
    }

    return 0;
}

static int ventoy_write_efipart(int fd, uint64_t offset, uint32_t secureboot)
{
    int i;
    ssize_t len;
    
    vlog("Formatting part2 EFI offset:%llu ...\n", (_ull)offset);
    lseek(fd, offset, SEEK_SET);

    VentoyProcSecureBoot((int)secureboot);

    g_current_progress = PT_WRITE_VENTOY_START;
    for (i = 0; i < 32; i++)
    {
        len = write(fd, g_efi_part_raw_img + i * SIZE_1MB, SIZE_1MB);
        vlog("write disk writelen:%lld datalen:%d [ %s ]\n", 
            (_ll)len, SIZE_1MB, (len == SIZE_1MB) ? "success" : "failed");
        
        if (len != SIZE_1MB)
        {
            vlog("failed to format part2 EFI\n");
            return 1;
        }
    
        g_current_progress = PT_WRITE_VENTOY_START + i / 4;
    }

    return 0;
}

static int VentoyFillBackupGptHead(VTOY_GPT_INFO *pInfo, VTOY_GPT_HDR *pHead)
{
    uint64_t LBA;
    uint64_t BackupLBA;

    memcpy(pHead, &pInfo->Head, sizeof(VTOY_GPT_HDR));

    LBA = pHead->EfiStartLBA;
    BackupLBA = pHead->EfiBackupLBA;
    
    pHead->EfiStartLBA = BackupLBA;
    pHead->EfiBackupLBA = LBA;
    pHead->PartTblStartLBA = BackupLBA + 1 - 33;

    pHead->Crc = 0;
    pHead->Crc = ventoy_crc32(pHead, pHead->Length);

    return 0;
}

static int ventoy_write_gpt_part_table(int fd, uint64_t disksize, VTOY_GPT_INFO *gpt)
{
    ssize_t len;
    off_t offset;
    VTOY_GPT_HDR BackupHead;
    
    VentoyFillBackupGptHead(gpt, &BackupHead);

    offset = lseek(fd, disksize - 512, SEEK_SET);
    len = write(fd, &BackupHead, sizeof(VTOY_GPT_HDR));
    vlog("write backup gpt part table off:%llu len:%llu\n", (_ull)offset, (_ull)len);
    if (offset != disksize - 512 || len != sizeof(VTOY_GPT_HDR))
    {
        return 1;
    }

    offset = lseek(fd, disksize - 512 * 33, SEEK_SET);
    len = write(fd, gpt->PartTbl, sizeof(gpt->PartTbl));
    vlog("write main gpt part table off:%llu len:%llu\n", (_ull)offset, (_ull)len);
    if (offset != disksize - 512 * 33 || len != sizeof(gpt->PartTbl))
    {
        return 1;
    }
    
    offset = lseek(fd, 0, SEEK_SET);
    len = write(fd, gpt, sizeof(VTOY_GPT_INFO));
    vlog("write gpt part head off:%llu len:%llu\n", (_ull)offset, (_ull)len);
    if (offset != 0 || len != sizeof(VTOY_GPT_INFO))
    {
        return 1;
    }
    
    return 0;
}

686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
static int ventoy_mbr_need_update(ventoy_disk *disk, MBR_HEAD *mbr)
{
    int update = 0;
    int partition_style;
    MBR_HEAD LocalMBR;

    partition_style = disk->vtoydata.partition_style;
    memcpy(mbr, &(disk->vtoydata.gptinfo.MBR), 512);
    
    VentoyGetLocalBootImg(&LocalMBR);
    memcpy(LocalMBR.BootCode + 0x180, mbr->BootCode + 0x180, 16);
    if (partition_style)
    {
        LocalMBR.BootCode[92] = 0x22;        
    }

    if (memcmp(LocalMBR.BootCode, mbr->BootCode, 440))
    {
        memcpy(mbr->BootCode, LocalMBR.BootCode, 440);
        vlog("MBR boot code different, must update it.\n");
        update = 1;
    }

    if (partition_style == 0 && mbr->PartTbl[0].Active == 0)
    {
        mbr->PartTbl[0].Active = 0x80;
        mbr->PartTbl[1].Active = 0;
        mbr->PartTbl[2].Active = 0;
        mbr->PartTbl[3].Active = 0;
        vlog("set MBR partition 1 active flag enabled\n");
        update = 1;
    }

    return update;
}

722
723
724
725
726
727
728
729
static void * ventoy_update_thread(void *data)
{
    int fd;
    ssize_t len;
    off_t offset;
    MBR_HEAD MBR;
    ventoy_disk *disk = NULL;
    ventoy_thread_data *thread = (ventoy_thread_data *)data;
730
    VTOY_GPT_INFO *pstGPT = NULL;
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782

    vdebug("ventoy_update_thread run ...\n");

    fd = thread->diskfd;
    disk = thread->disk;

    g_current_progress = PT_PRAPARE_FOR_CLEAN;
    vdebug("check disk %s\n", disk->disk_name);
    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("disk is mounted, now try to unmount it ...\n");
        ventoy_try_umount_disk(disk->disk_path);
    }

    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("%s is mounted and can't umount!\n", disk->disk_path);
        goto err;
    }
    else
    {
        vlog("disk is not mounted now, we can do continue ...\n");
    }

    g_current_progress = PT_LOAD_CORE_IMG;
    ventoy_unxz_stg1_img();
    
    g_current_progress = PT_LOAD_DISK_IMG;
    ventoy_unxz_efipart_img();

    g_current_progress = PT_FORMAT_PART2;

    vlog("Formatting part2 EFI ...\n");
    if (0 != ventoy_write_efipart(fd, disk->vtoydata.part2_start_sector * 512, thread->secure_boot))
    {
        vlog("Failed to format part2 efi ...\n");
        goto err;
    }

    g_current_progress = PT_WRITE_STG1_IMG;

    vlog("Writing legacy grub ...\n");
    if (0 != ventoy_write_legacy_grub(fd, disk->vtoydata.partition_style))
    {
        vlog("ventoy_write_legacy_grub failed ...\n");
        goto err;
    }

    offset = lseek(fd, 512 * 2040, SEEK_SET);
    len = write(fd, disk->vtoydata.rsvdata, sizeof(disk->vtoydata.rsvdata));
    vlog("Writing reserve data offset:%llu len:%llu ...\n", (_ull)offset, (_ull)len);

783
    if (ventoy_mbr_need_update(disk, &MBR))
784
    {
785
786
        offset = lseek(fd, 0, SEEK_SET);
        len = write(fd, &MBR, 512);
787
        vlog("update MBR offset:%llu len:%llu\n", (_ull)offset, (_ull)len);
788
    }
789
790
791
792
793
    else
    {
        vlog("No need to update MBR\n");
    }

794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
    
    if (disk->vtoydata.partition_style)
    {
        pstGPT = (VTOY_GPT_INFO *)malloc(sizeof(VTOY_GPT_INFO));
        memset(pstGPT, 0, sizeof(VTOY_GPT_INFO));
            
        offset = lseek(fd, 0, SEEK_SET);
        len = read(fd, pstGPT, sizeof(VTOY_GPT_INFO));
        vlog("Read GPT table offset:%llu len:%llu ...\n", (_ull)offset, (_ull)len);

        if (pstGPT->PartTbl[1].Attr != 0x8000000000000000ULL)
        {
            vlog("Update EFI part attr from 0x%016llx to 0x%016llx\n", 
                 pstGPT->PartTbl[1].Attr, 0x8000000000000000ULL);

            pstGPT->PartTbl[1].Attr = 0x8000000000000000ULL;
            pstGPT->Head.Crc = 0;
            pstGPT->Head.Crc = ventoy_crc32(&(pstGPT->Head), pstGPT->Head.Length);            
            ventoy_write_gpt_part_table(fd, disk->size_in_byte, pstGPT);
        }
        else
        {
            vlog("No need to update EFI part attr\n");
        }
        free(pstGPT);
    }
    

822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
    g_current_progress = PT_SYNC_DATA1;

    vlog("fsync data1...\n");
    fsync(fd);
    vtoy_safe_close_fd(fd);

    g_current_progress = PT_SYNC_DATA2;

    vlog("====================================\n");
    vlog("====== ventoy update success ======\n");
    vlog("====================================\n");
    goto end;

err:
    g_cur_process_result = 1;
    vtoy_safe_close_fd(fd);        

end:
    g_current_progress = PT_FINISH;

    check_free(thread);
    
    return NULL;
}

static void * ventoy_install_thread(void *data)
{
    int fd;
    ssize_t len;
    off_t offset;
    MBR_HEAD MBR;
    ventoy_disk *disk = NULL;
    VTOY_GPT_INFO *gpt = NULL;
    ventoy_thread_data *thread = (ventoy_thread_data *)data;
    uint64_t Part1StartSector = 0;
    uint64_t Part1SectorCount = 0;
    uint64_t Part2StartSector = 0;

    vdebug("ventoy_install_thread run ...\n");

    fd = thread->diskfd;
    disk = thread->disk;

    g_current_progress = PT_PRAPARE_FOR_CLEAN;
    vdebug("check disk %s\n", disk->disk_name);
    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("disk is mounted, now try to unmount it ...\n");
        ventoy_try_umount_disk(disk->disk_path);
    }

    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("%s is mounted and can't umount!\n", disk->disk_path);
        goto err;
    }
    else
    {
        vlog("disk is not mounted now, we can do continue ...\n");
    }

    g_current_progress = PT_DEL_ALL_PART;
    ventoy_clean_disk(fd, disk->size_in_byte);
    
    g_current_progress = PT_LOAD_CORE_IMG;
    ventoy_unxz_stg1_img();
    
    g_current_progress = PT_LOAD_DISK_IMG;
    ventoy_unxz_efipart_img();

    if (thread->partstyle)
    {
        vdebug("Fill GPT part table\n");
        gpt = zalloc(sizeof(VTOY_GPT_INFO));
        ventoy_fill_gpt(disk->size_in_byte, thread->reserveBytes, thread->align4kb, gpt);
        Part1StartSector = gpt->PartTbl[0].StartLBA;
        Part1SectorCount = gpt->PartTbl[0].LastLBA - Part1StartSector + 1;
        Part2StartSector = gpt->PartTbl[1].StartLBA;
    }
    else
    {
        vdebug("Fill MBR part table\n");
longpanda's avatar
longpanda committed
904
        ventoy_fill_mbr(disk->size_in_byte, thread->reserveBytes, thread->align4kb, &MBR);
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
        Part1StartSector = MBR.PartTbl[0].StartSectorId;
        Part1SectorCount = MBR.PartTbl[0].SectorCount;
        Part2StartSector = MBR.PartTbl[1].StartSectorId;
    }

    vlog("Part1StartSector:%llu Part1SectorCount:%llu Part2StartSector:%llu\n", 
        (_ull)Part1StartSector, (_ull)Part1SectorCount, (_ull)Part2StartSector);

    if (thread->partstyle != disk->partstyle)
    {
        vlog("Wait for format part1 (partstyle changed) ...\n");
        sleep(1);
    }

    g_current_progress = PT_FORMAT_PART1;
    vlog("Formatting part1 exFAT %s ...\n", disk->disk_path);
    if (0 != mkexfat_main(disk->disk_path, fd, Part1SectorCount))
    {
        vlog("Failed to format exfat ...\n");
        goto err;
    }

    g_current_progress = PT_FORMAT_PART2;
    vlog("Formatting part2 EFI ...\n");
    if (0 != ventoy_write_efipart(fd, Part2StartSector * 512, thread->secure_boot))
    {
        vlog("Failed to format part2 efi ...\n");
        goto err;
    }

    g_current_progress = PT_WRITE_STG1_IMG;
    vlog("Writing legacy grub ...\n");
    if (0 != ventoy_write_legacy_grub(fd, thread->partstyle))
    {
        vlog("ventoy_write_legacy_grub failed ...\n");
        goto err;
    }

    g_current_progress = PT_SYNC_DATA1;
    vlog("fsync data1...\n");
    fsync(fd);
    vtoy_safe_close_fd(fd);

    /* reopen for check part2 data */
    vlog("Checking part2 efi data %s ...\n", disk->disk_path);
    g_current_progress = PT_CHECK_PART2;
    fd = open(disk->disk_path, O_RDONLY | O_BINARY);
    if (fd < 0)
    {
        vlog("failed to open %s for check fd:%d err:%d\n", disk->disk_path, fd, errno);
        goto err;
    }

    if (0 == ventoy_check_efi_part_data(fd, Part2StartSector * 512))
    {
        vlog("efi part data check success\n");
    }
    else
    {
        vlog("efi part data check failed\n");
        goto err;
    }

    vtoy_safe_close_fd(fd);
    
    /* reopen for write part table */
    g_current_progress = PT_WRITE_PART_TABLE;
    vlog("Writting Partition Table style:%d...\n", thread->partstyle);

    fd = open(disk->disk_path, O_RDWR | O_BINARY);
    if (fd < 0)
    {
        vlog("failed to open %s for part table fd:%d err:%d\n", disk->disk_path, fd, errno);
        goto err;
    }

    if (thread->partstyle)
    {
        ventoy_write_gpt_part_table(fd, disk->size_in_byte, gpt);
    }
    else
    {
        offset = lseek(fd, 0, SEEK_SET);
        len = write(fd, &MBR, 512);
        vlog("Writting MBR Partition Table %llu %llu\n", (_ull)offset, (_ull)len);
        if (offset != 0 || len != 512)
        {
            goto err;
        }
    }

    g_current_progress = PT_SYNC_DATA2;
    vlog("fsync data2...\n");
    fsync(fd);
    vtoy_safe_close_fd(fd);


    vlog("====================================\n");
    vlog("====== ventoy install success ======\n");
    vlog("====================================\n");
    goto end;

err:
    g_cur_process_result = 1;
    vtoy_safe_close_fd(fd);        

end:
    g_current_progress = PT_FINISH;

    check_free(gpt);
    check_free(thread);
    
    return NULL;
}

static int ventoy_api_clean(struct mg_connection *conn, VTOY_JSON *json)
{
    int i = 0;
    int fd = 0;
    ventoy_disk *disk = NULL;
    const char *diskname = NULL;
    char path[128];
    
    if (g_current_progress != PT_FINISH)
    {
        ventoy_json_result(conn, VTOY_JSON_BUSY_RET);
        return 0;  
    }
    
    diskname = vtoy_json_get_string_ex(json, "disk");
    if (diskname == NULL)
    {
        ventoy_json_result(conn, VTOY_JSON_INVALID_RET);
        return 0;
    }

    for (i = 0; i < g_disk_num; i++)
    {
        if (strcmp(g_disk_list[i].disk_name, diskname) == 0)
        {
            disk = g_disk_list + i;
            break;
        }
    }

    if (disk == NULL)
    {
        vlog("disk %s not found\n", diskname);
        ventoy_json_result(conn, VTOY_JSON_NOTFOUND_RET);
        return 0;
    }

    scnprintf(path, "/sys/block/%s", diskname);
    if (access(path, F_OK) < 0)
    {
        vlog("File %s not exist anymore\n", path);
        ventoy_json_result(conn, VTOY_JSON_NOTFOUND_RET);
        return 0;
    }

    vlog("==================================\n");
    vlog("===== ventoy clean %s =====\n", disk->disk_path);
    vlog("==================================\n");

    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("disk is mounted, now try to unmount it ...\n");
        ventoy_try_umount_disk(disk->disk_path);
    }

    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("%s is mounted and can't umount!\n", disk->disk_path);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    else
    {
        vlog("disk is not mounted now, we can do the clean ...\n");
    }

    fd = open(disk->disk_path, O_RDWR | O_BINARY);
    if (fd < 0)
    {
        vlog("failed to open %s fd:%d err:%d\n", disk->disk_path, fd, errno);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }

    vdebug("start clean %s ...\n", disk->disk_model);
    ventoy_clean_disk(fd, disk->size_in_byte);    

    vtoy_safe_close_fd(fd);
    
    ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
    return 0;    
}

static int ventoy_api_install(struct mg_connection *conn, VTOY_JSON *json)
{
    int i = 0;
    int ret = 0;
    int fd = 0;
    uint32_t align4kb = 0;
    uint32_t style = 0;
    uint32_t secure_boot = 0;
    uint64_t reserveBytes = 0;
    ventoy_disk *disk = NULL;
    const char *diskname = NULL;
    const char *reserve_space = NULL;
    ventoy_thread_data *thread = NULL;
    char path[128];
    
    if (g_current_progress != PT_FINISH)
    {
        ventoy_json_result(conn, VTOY_JSON_BUSY_RET);
        return 0;  
    }
    
    diskname = vtoy_json_get_string_ex(json, "disk");
    reserve_space = vtoy_json_get_string_ex(json, "reserve_space");
    ret += vtoy_json_get_uint(json, "partstyle", &style);
    ret += vtoy_json_get_uint(json, "secure_boot", &secure_boot);
    ret += vtoy_json_get_uint(json, "align_4kb", &align4kb);

    if (diskname == NULL || reserve_space == NULL || ret != JSON_SUCCESS)
    {
        ventoy_json_result(conn, VTOY_JSON_INVALID_RET);
        return 0;
    }

    reserveBytes = (uint64_t)strtoull(reserve_space, NULL, 10);

    for (i = 0; i < g_disk_num; i++)
    {
        if (strcmp(g_disk_list[i].disk_name, diskname) == 0)
        {
            disk = g_disk_list + i;
            break;
        }
    }

    if (disk == NULL)
    {
        vlog("disk %s not found\n", diskname);
        ventoy_json_result(conn, VTOY_JSON_NOTFOUND_RET);
        return 0;
    }

1154
1155
1156
1157
1158
1159
1160
    if (disk->is4kn)
    {
        vlog("disk %s is 4k native, not supported.\n", diskname);
        ventoy_json_result(conn, VTOY_JSON_4KN_RET);
        return 0;
    }

1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
    scnprintf(path, "/sys/block/%s", diskname);
    if (access(path, F_OK) < 0)
    {
        vlog("File %s not exist anymore\n", path);
        ventoy_json_result(conn, VTOY_JSON_NOTFOUND_RET);
        return 0;
    }

    if (disk->size_in_byte > 2199023255552ULL && style == 0)
    {
        vlog("disk %s is more than 2TB and GPT is needed\n", path);
        ventoy_json_result(conn, VTOY_JSON_MBR_2TB_RET);
        return 0;
    }

    if ((reserveBytes + VTOYEFI_PART_BYTES * 2) > disk->size_in_byte)
    {
        vlog("reserve space %llu is too big for disk %s %llu\n", (_ull)reserveBytes, path, (_ull)disk->size_in_byte);
        ventoy_json_result(conn, VTOY_JSON_INVALID_RSV_RET);
        return 0;
    }

    vlog("==================================================================================\n");
    vlog("===== ventoy install %s style:%s secureboot:%u align4K:%u reserve:%llu =========\n",
         disk->disk_path, (style ? "GPT" : "MBR"), secure_boot, align4kb, (_ull)reserveBytes);
    vlog("==================================================================================\n");

    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("disk is mounted, now try to unmount it ...\n");
        ventoy_try_umount_disk(disk->disk_path);
    }

    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("%s is mounted and can't umount!\n", disk->disk_path);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    else
    {
        vlog("disk is not mounted now, we can do the install ...\n");
    }

    fd = open(disk->disk_path, O_RDWR | O_BINARY);
    if (fd < 0)
    {
        vlog("failed to open %s fd:%d err:%d\n", disk->disk_path, fd, errno);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }

    vdebug("start install thread %s ...\n", disk->disk_model);
    thread = zalloc(sizeof(ventoy_thread_data));
    if (!thread)
    {
        vtoy_safe_close_fd(fd);
        vlog("failed to alloc thread data err:%d\n", errno);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    
    g_current_progress = PT_START;
    g_cur_process_result = 0;
    scnprintf(g_cur_process_type, "%s", "install");
    scnprintf(g_cur_process_diskname, "%s", disk->disk_name);

    thread->disk = disk;
    thread->diskfd = fd;
    thread->align4kb = align4kb;
    thread->partstyle = style;
    thread->secure_boot = secure_boot;
    thread->reserveBytes = reserveBytes;
    
    mg_start_thread(ventoy_install_thread, thread);
    
    ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
    return 0;    
}

static int ventoy_api_update(struct mg_connection *conn, VTOY_JSON *json)
{
    int i = 0;
    int ret = 0;
    int fd = 0;
    uint32_t secure_boot = 0;
    ventoy_disk *disk = NULL;
    const char *diskname = NULL;
    ventoy_thread_data *thread = NULL;
    char path[128];
    
    if (g_current_progress != PT_FINISH)
    {
        ventoy_json_result(conn, VTOY_JSON_BUSY_RET);
        return 0;  
    }
    
    diskname = vtoy_json_get_string_ex(json, "disk");
    ret += vtoy_json_get_uint(json, "secure_boot", &secure_boot);
    if (diskname == NULL || ret != JSON_SUCCESS)
    {
        ventoy_json_result(conn, VTOY_JSON_INVALID_RET);
        return 0;
    }

    for (i = 0; i < g_disk_num; i++)
    {
        if (strcmp(g_disk_list[i].disk_name, diskname) == 0)
        {
            disk = g_disk_list + i;
            break;
        }
    }

    if (disk == NULL)
    {
        vlog("disk %s not found\n", diskname);
        ventoy_json_result(conn, VTOY_JSON_NOTFOUND_RET);
        return 0;
    }

    if (disk->vtoydata.ventoy_valid == 0)
    {
        vlog("disk %s is not ventoy disk\n", diskname);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }

    scnprintf(path, "/sys/block/%s", diskname);
    if (access(path, F_OK) < 0)
    {
        vlog("File %s not exist anymore\n", path);
        ventoy_json_result(conn, VTOY_JSON_NOTFOUND_RET);
        return 0;
    }

    vlog("==========================================================\n");
    vlog("===== ventoy update %s new_secureboot:%u =========\n", disk->disk_path, secure_boot);
    vlog("==========================================================\n");

    vlog("%s version:%s partstyle:%u oldsecureboot:%u reserve:%llu\n", 
        disk->disk_path, disk->vtoydata.ventoy_ver, 
        disk->vtoydata.partition_style,
        disk->vtoydata.secure_boot_flag,
        (_ull)(disk->vtoydata.preserved_space)
        );

    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("disk is mounted, now try to unmount it ...\n");
        ventoy_try_umount_disk(disk->disk_path);
    }

    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("%s is mounted and can't umount!\n", disk->disk_path);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    else
    {
        vlog("disk is not mounted now, we can do the update ...\n");
    }

    fd = open(disk->disk_path, O_RDWR | O_BINARY);
    if (fd < 0)
    {
        vlog("failed to open %s fd:%d err:%d\n", disk->disk_path, fd, errno);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }

    vdebug("start update thread %s ...\n", disk->disk_model);
    thread = zalloc(sizeof(ventoy_thread_data));
    if (!thread)
    {
        vtoy_safe_close_fd(fd);
        vlog("failed to alloc thread data err:%d\n", errno);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    
    g_current_progress = PT_START;
    g_cur_process_result = 0;
    scnprintf(g_cur_process_type, "%s", "update");
    scnprintf(g_cur_process_diskname, "%s", disk->disk_name);

    thread->disk = disk;
    thread->diskfd = fd;
    thread->secure_boot = secure_boot;
    
    mg_start_thread(ventoy_update_thread, thread);
    
    ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
    return 0;    
}


static int ventoy_api_refresh_device(struct mg_connection *conn, VTOY_JSON *json)
{
    (void)json;

    if (g_current_progress == PT_FINISH)
    {
        g_disk_num = 0;
        ventoy_disk_enumerate_all();
    }

    ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
    return 0;
}

static int ventoy_api_get_dev_list(struct mg_connection *conn, VTOY_JSON *json)
{
    int i = 0;
    int rc = 0;
    int pos = 0;
    int buflen = 0;
    uint32_t alldev = 0;
    char *buf = NULL;
    ventoy_disk *cur = NULL;
    
    rc = vtoy_json_get_uint(json, "alldev", &alldev);
    if (JSON_SUCCESS != rc)
    {
        alldev = 0;
    }

    buflen = g_disk_num * 1024;
    buf = (char *)malloc(buflen + 1024);
    if (!buf)
    {
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }

    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_KEY("list");
    VTOY_JSON_FMT_ARY_BEGIN();

    for (i = 0; i < g_disk_num; i++)
    {
        cur = g_disk_list + i;

        if (alldev == 0 && cur->type != VTOY_DEVICE_USB)
        {
            continue;
        }
        
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_STRN("name", cur->disk_name);
        VTOY_JSON_FMT_STRN("model", cur->disk_model);
        VTOY_JSON_FMT_STRN("size", cur->human_readable_size);
        VTOY_JSON_FMT_UINT("vtoy_valid", cur->vtoydata.ventoy_valid);
        VTOY_JSON_FMT_STRN("vtoy_ver", cur->vtoydata.ventoy_ver);
        VTOY_JSON_FMT_UINT("vtoy_secure_boot", cur->vtoydata.secure_boot_flag);
        VTOY_JSON_FMT_UINT("vtoy_partstyle", cur->vtoydata.partition_style);
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    
    VTOY_JSON_FMT_ARY_END();
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);

    ventoy_json_buffer(conn, buf, pos);
    return 0;
}

static JSON_CB g_ventoy_json_cb[] = 
{
    { "sysinfo",        ventoy_api_sysinfo        },
    { "sel_language",   ventoy_api_set_language   },
    { "sel_partstyle",  ventoy_api_set_partstyle  },
    { "refresh_device", ventoy_api_refresh_device },
    { "get_dev_list",   ventoy_api_get_dev_list   },
    { "install",        ventoy_api_install        },
    { "update",         ventoy_api_update         },
    { "clean",          ventoy_api_clean          },
    { "get_percent",    ventoy_api_get_percent    },
};

static int ventoy_json_handler(struct mg_connection *conn, VTOY_JSON *json)
{
    int i;
    const char *token = NULL;
    const char *method = NULL;

    method = vtoy_json_get_string_ex(json, "method");
    if (!method)
    {
        ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
        return 0;
    }

    if (strcmp(method, "sysinfo"))
    {
        token = vtoy_json_get_string_ex(json, "token");
        if (token == NULL || strcmp(token, g_cur_server_token))
        {
            ventoy_json_result(conn, VTOY_JSON_TOKEN_ERR_RET);
            return 0;
        }
    }

    for (i = 0; i < (int)(sizeof(g_ventoy_json_cb) / sizeof(g_ventoy_json_cb[0])); i++)
    {
        if (strcmp(method, g_ventoy_json_cb[i].method) == 0)
        {
            g_ventoy_json_cb[i].callback(conn, json);
            break;
        }
    }

    return 0;
}

1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
int ventoy_func_handler(const char *jsonstr, char *jsonbuf, int buflen)
{
    int i;
    const char *method = NULL;
    VTOY_JSON *json = NULL;

    g_pub_out_buf = jsonbuf;
    g_pub_out_max = buflen;

    json = vtoy_json_create();
    if (JSON_SUCCESS == vtoy_json_parse(json, jsonstr))
    {
        pthread_mutex_lock(&g_api_mutex);

        method = vtoy_json_get_string_ex(json->pstChild, "method");
        for (i = 0; i < (int)(sizeof(g_ventoy_json_cb) / sizeof(g_ventoy_json_cb[0])); i++)
        {
            if (method && strcmp(method, g_ventoy_json_cb[i].method) == 0)
            {
                g_ventoy_json_cb[i].callback(NULL, json->pstChild);
                break;
            }
        }

        pthread_mutex_unlock(&g_api_mutex);
    }
    else
    {
        ventoy_json_result(NULL, VTOY_JSON_INVALID_RET);
    }

    vtoy_json_destroy(json);
    return 0;
}

1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
static int ventoy_request_handler(struct mg_connection *conn)
{
    int post_data_len;
    int post_buf_len;
    VTOY_JSON *json = NULL;
    char *post_data_buf = NULL;
    const struct mg_request_info *ri = NULL;
    char stack_buf[512];
    
    ri = mg_get_request_info(conn);    

    if (strcmp(ri->uri, "/vtoy/json") == 0)
    {
        if (ri->content_length > 500)
        {
            post_data_buf = malloc(ri->content_length + 4);
            post_buf_len  = ri->content_length + 1;
        }
        else
        {
            post_data_buf = stack_buf;
            post_buf_len = sizeof(stack_buf);
        }
        
        post_data_len = mg_read(conn, post_data_buf, post_buf_len);
        post_data_buf[post_data_len] = 0;

        json = vtoy_json_create();
        if (JSON_SUCCESS == vtoy_json_parse(json, post_data_buf))
        {
            pthread_mutex_lock(&g_api_mutex);
            ventoy_json_handler(conn, json->pstChild);
            pthread_mutex_unlock(&g_api_mutex);
        }
        else
        {
            ventoy_json_result(conn, VTOY_JSON_INVALID_RET);
        }

        vtoy_json_destroy(json);

        if (post_data_buf != stack_buf)
        {
            free(post_data_buf);
        }
        return 1;
    }
    else
    {
        return 0;
    }
}

int ventoy_http_start(const char *ip, const char *port)
{
    uint8_t uuid[16];
    char addr[128];
    struct mg_callbacks callbacks;
    const char *options[] = 
    {
	    "listening_ports",    "24680",
        "document_root",      "WebUI",
longpanda's avatar
longpanda committed
1575
        "error_log_file",     g_log_file,
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
	    "request_timeout_ms", "10000",
	     NULL
    };

    /* unique token */
    ventoy_gen_preudo_uuid(uuid);
    scnprintf(g_cur_server_token, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
        uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
        uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);

    /* option */
    scnprintf(addr, "%s:%s", ip, port);
    options[1] = addr;

    memset(&callbacks, 0, sizeof(callbacks));
    callbacks.begin_request = ventoy_request_handler;
    g_ventoy_http_ctx = mg_start(&callbacks, NULL, options);

    return g_ventoy_http_ctx ? 0 : 1;
}

int ventoy_http_stop(void)
{
    if (g_ventoy_http_ctx)
    {
        mg_stop(g_ventoy_http_ctx);        
    }
    return 0;
}

int ventoy_http_init(void)
{
    pthread_mutex_init(&g_api_mutex, NULL);

    ventoy_http_load_cfg();

    ventoy_load_mbr_template();
    
    return 0;
}

void ventoy_http_exit(void)
{
    pthread_mutex_destroy(&g_api_mutex);

    check_free(g_efi_part_raw_img);
    g_efi_part_raw_img = NULL;    
}

1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698

const char * ventoy_code_get_cur_language(void)
{
    return g_cur_language;
}

int ventoy_code_get_cur_part_style(void)
{
    return g_cur_part_style;
}

void ventoy_code_set_cur_part_style(int style)
{
    pthread_mutex_lock(&g_api_mutex);
    
    g_cur_part_style = style;
    ventoy_http_save_cfg();

    pthread_mutex_unlock(&g_api_mutex);
}

int ventoy_code_get_cur_show_all(void)
{
    return g_cur_show_all;
}

void ventoy_code_set_cur_show_all(int show_all)
{
    pthread_mutex_lock(&g_api_mutex);
    
    g_cur_show_all = show_all;
    ventoy_http_save_cfg();

    pthread_mutex_unlock(&g_api_mutex);
}

void ventoy_code_set_cur_language(const char *lang)
{
    pthread_mutex_lock(&g_api_mutex);
    
    scnprintf(g_cur_language, "%s", lang);
    ventoy_http_save_cfg();
    
    pthread_mutex_unlock(&g_api_mutex);
}

void ventoy_code_refresh_device(void)
{
    if (g_current_progress == PT_FINISH)
    {
        g_disk_num = 0;
        ventoy_disk_enumerate_all();
    }
}

int ventoy_code_is_busy(void)
{
    return (g_current_progress == PT_FINISH) ? 0 : 1;
}

int ventoy_code_get_percent(void)
{
    return g_current_progress * 100 / PT_FINISH;
}

int ventoy_code_get_result(void)
{
    return g_cur_process_result;
}

void ventoy_code_save_cfg(void)
{
    ventoy_http_save_cfg();
}