File: autoupdater.c

package info (click to toggle)
openmohaa 0.81.1%2Bdfsg-2
  • links: PTS, VCS
  • area: contrib
  • in suites: trixie
  • size: 29,124 kB
  • sloc: ansic: 270,865; cpp: 250,173; sh: 234; asm: 141; xml: 64; makefile: 7
file content (1046 lines) | stat: -rw-r--r-- 29,011 bytes parent folder | download | duplicates (4)
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
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
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
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
384
385
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
498
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
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
722
723
724
725
726
727
728
729
730
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
783
784
785
786
787
788
789
790
791
792
793
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
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
904
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
/*
The code in this file is in the public domain. The rest of ioquake3
is licensed under the GPLv2. Do not mingle code, please!
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>

#if defined(_MSC_VER) && (_MSC_VER < 1600)
typedef __int64 int64_t;
#else
#include <stdint.h>
#endif

#include <time.h>
#include <unistd.h>
#include <sys/stat.h>

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#include <wininet.h>
#include <tlhelp32.h>
#define PIDFMT "%u"
#define PIDFMTCAST unsigned int
typedef DWORD PID;
#else
#include <signal.h>
#include <curl/curl.h>
typedef pid_t PID;
#define PIDFMT "%llu"
#define PIDFMTCAST unsigned long long
#endif

/* If your build fails here with tomcrypt.h missing, you probably need to
   run the build-libtom script in the rsa_tools subdirectory. */
#define TFM_DESC
#define LTC_NO_ROLC
#include "tomcrypt.h"

#define PUBLICKEY_FNAME "updater-publickey.bin"
#define SALT_LEN 8
static int sha256_hash_index = 0;


#ifndef AUTOUPDATE_USER_AGENT
#define AUTOUPDATE_USER_AGENT "ioq3autoupdater/0.1"
#endif


#ifndef AUTOUPDATE_URL

#ifndef AUTOUPDATE_BASEURL
#define AUTOUPDATE_BASEURL "https://upd.ioquake3.org/updates/v1"
#endif

#ifndef AUTOUPDATE_PACKAGE 
#define AUTOUPDATE_PACKAGE "ioquake3"
#endif

#ifdef __APPLE__
#define AUTOUPDATE_PLATFORM "mac"
#elif defined(__linux__)
#define AUTOUPDATE_PLATFORM "linux"
#elif defined(_WIN32)
#define AUTOUPDATE_PLATFORM "windows"
#else
#error Please define your platform.
#endif

#ifdef __i386__
#define AUTOUPDATE_ARCH "x86"
#elif defined(__x86_64__)
#define AUTOUPDATE_ARCH "x86_64"
#else
#error Please define your platform.
#endif

#define AUTOUPDATE_URL AUTOUPDATE_BASEURL "/" AUTOUPDATE_PACKAGE "/" AUTOUPDATE_PLATFORM "/" AUTOUPDATE_ARCH "/"
#endif

#if defined(__GNUC__) || defined(__clang__)
#define NEVER_RETURNS __attribute__((noreturn))
#define PRINTF_FUNC(fmtargnum, dotargnum) __attribute__ (( format( __printf__, fmtargnum, dotargnum )))
#else
#define NEVER_RETURNS
#define PRINTF_FUNC(fmtargnum, dotargnum)
#endif


typedef struct
{
    pid_t waitforprocess;
    const char *updateself;
} Options;

static Options options;


typedef struct ManifestItem
{
    char *fname;
    unsigned char sha256[32];
    int64_t len;
    int update;
    int rollback;
    struct ManifestItem *next;
} ManifestItem;

static ManifestItem *manifest = NULL;

static void freeManifest(void)
{
    ManifestItem *item = manifest;
    manifest = NULL;

    while (item != NULL) {
        ManifestItem *next = item->next;
        free(item->fname);
        free(item);
        item = next;
    }
    manifest = NULL;
}

static const char *timestamp(void)
{
    time_t t = time(NULL);
    char *retval = asctime(localtime(&t));
    if (retval) {
        char *ptr;
        for (ptr = retval; *ptr; ptr++) {
            if ((*ptr == '\r') || (*ptr == '\n')) {
                *ptr = '\0';
                break;
            }
        }
    }
    return retval ? retval : "[date unknown]";
}


static FILE *logfile = NULL;

static void info(const char *str)
{
    fputs(str, logfile);
    fputs("\n", logfile);
    fflush(logfile);
}

static void infof(const char *fmt, ...) PRINTF_FUNC(1, 2);
static void infof(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vfprintf(logfile, fmt, ap);
    va_end(ap);
    fputs("\n", logfile);
    fflush(logfile);
}

static void restoreRollbacks(void)
{
    /* you can't call die() in this function! If this fails, you're doomed. */
    ManifestItem *item;
    for (item = manifest; item != NULL; item = item->next) {
        if (item->rollback) {
            char rollbackPath[64];
            snprintf(rollbackPath, sizeof (rollbackPath), "updates/rollbacks/%d", item->rollback);
            infof("restore rollback: '%s' -> '%s'", rollbackPath, item->fname);
            remove(item->fname);
            rename(rollbackPath, item->fname);
        }
    }
}

static void die(const char *why) NEVER_RETURNS;



#ifdef _WIN32

#define chmod(a,b) do {} while (0)
#define makeDir(path) mkdir(path)

static void windowsWaitForProcessToDie(const DWORD pid)
{
    HANDLE h;
    infof("Waiting on process ID #%u", (unsigned int) pid);
    h = OpenProcess(SYNCHRONIZE, FALSE, pid);
    if (!h) {
        const DWORD err = GetLastError();
        if (err == ERROR_INVALID_PARAMETER) {
            info("No such process; probably already dead. Carry on.");
            return;  /* process is (probably) already gone. */
        }
        infof("OpenProcess failed. err=%d", (unsigned int) err);
        die("OpenProcess failed");
    }
    if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
        die("WaitForSingleObject failed");
    }
    CloseHandle(h);
}

static void launchProcess(const char *exe, ...)
{
     PROCESS_INFORMATION procinfo;
     STARTUPINFO startinfo;
     va_list ap;
     char cmdline[1024];
     char *ptr = cmdline;
     size_t totallen = 0;
     const char *arg = NULL;

     #define APPENDCMDLINE(str) { \
        const size_t len = strlen(str); \
        totallen += len; \
        if ((totallen + 1) < sizeof (cmdline)) { \
            strcpy(ptr, str); \
            ptr += len; \
        } \
     }

     va_start(ap, exe);
     APPENDCMDLINE(exe);
     while ((arg = va_arg(ap, const char *)) != NULL) {
         APPENDCMDLINE(arg);
     }
     va_end(ap);

     if (totallen >= sizeof (cmdline)) {
        die("command line too long to launch.");
     }

     cmdline[totallen] = 0;

     infof("launching process '%s' with cmdline '%s'", exe, cmdline);

     memset(&procinfo, '\0', sizeof (procinfo));
     memset(&startinfo, '\0', sizeof (startinfo));
     startinfo.cb = sizeof (startinfo);
     if (CreateProcessA(exe, cmdline, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &startinfo, &procinfo))
     {
         CloseHandle(procinfo.hProcess);
         CloseHandle(procinfo.hThread);
         exit(0);  /* we're done, it's launched. */
     }

     infof("CreateProcess failed: err=%d", (int) GetLastError());
}

static HINTERNET hInternet;
static void prepHttpLib(void)
{
    hInternet = InternetOpenA(AUTOUPDATE_USER_AGENT,
                              INTERNET_OPEN_TYPE_PRECONFIG,
                              NULL, NULL, 0);
    if (!hInternet) {
        die("InternetOpen failed");
    }
}

static void shutdownHttpLib(void)
{
    if (hInternet) {
        InternetCloseHandle(hInternet);
        hInternet = NULL;
    }
}

static int runHttpDownload(const char *from, FILE *to)
{
    /* !!! FIXME: some of this could benefit from GetLastError+FormatMessage. */
    int retval = 0;
    DWORD httpcode = 0;
    DWORD dwordlen = sizeof (DWORD);
    DWORD zero = 0;
    HINTERNET hUrl = InternetOpenUrlA(hInternet, from, NULL, 0,
                                INTERNET_FLAG_HYPERLINK |
                                INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
                                INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
                                INTERNET_FLAG_NO_CACHE_WRITE |
                                INTERNET_FLAG_NO_COOKIES |
                                INTERNET_FLAG_NO_UI |
                                INTERNET_FLAG_RESYNCHRONIZE |
                                INTERNET_FLAG_RELOAD |
                                INTERNET_FLAG_SECURE, 0);

    if (!hUrl) {
        infof("InternetOpenUrl failed. err=%d", (int) GetLastError());
    } else if (!HttpQueryInfo(hUrl, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &httpcode, &dwordlen, &zero)) {
        infof("HttpQueryInfo failed. err=%d", (int) GetLastError());
    } else if (httpcode != 200) {
        infof("HTTP request failed with response code %d", (int) httpcode);
    } else {
        while (1) {
            DWORD br = 0;
            BYTE buf[1024 * 64];
            if (!InternetReadFile(hUrl, buf, sizeof (buf), &br)) {
                infof("InternetReadFile failed. err=%d", (int) GetLastError());
                break;
            } else if (br == 0) {
                retval = 1;
                break;  /* done! */
            } else {
                if (fwrite(buf, br, 1, to) != 1) {
                    info("fwrite failed");
                    break;
                }
            }
        }
    }

    InternetCloseHandle(hUrl);
    return retval;
}

#else  /* Everything that isn't Windows. */

#define launchProcess execl
#define makeDir(path) mkdir(path, 0777)

/* hooray for Unix linker hostility! */
#undef curl_easy_setopt
#include <dlfcn.h>
typedef void (*CURLFN_curl_easy_cleanup)(CURL *curl);
typedef CURL *(*CURLFN_curl_easy_init)(void);
typedef CURLcode (*CURLFN_curl_easy_setopt)(CURL *curl, CURLoption option, ...);
typedef CURLcode (*CURLFN_curl_easy_perform)(CURL *curl);
typedef CURLcode (*CURLFN_curl_global_init)(long flags);
typedef void (*CURLFN_curl_global_cleanup)(void);

static CURLFN_curl_easy_cleanup CURL_curl_easy_cleanup;
static CURLFN_curl_easy_init CURL_curl_easy_init;
static CURLFN_curl_easy_setopt CURL_curl_easy_setopt;
static CURLFN_curl_easy_perform CURL_curl_easy_perform;
static CURLFN_curl_global_init CURL_curl_global_init;
static CURLFN_curl_global_cleanup CURL_curl_global_cleanup;

static void prepHttpLib(void)
{
    #ifdef __APPLE__
    const char *libname = "libcurl.4.dylib";
    #else
    const char *libname = "libcurl.so.4";
    #endif

    void *handle = dlopen(libname, RTLD_NOW | RTLD_GLOBAL);
    if (!handle) {
        infof("dlopen(\"%s\") failed: %s", libname, dlerror());
        die("Failed to load libcurl library");
    }
    #define LOADCURLSYM(fn) \
        if ((CURL_##fn = (CURLFN_##fn) dlsym(handle, #fn)) == NULL) { \
            die("Failed to load libcurl symbol '" #fn "'"); \
        }

    LOADCURLSYM(curl_easy_cleanup);
    LOADCURLSYM(curl_easy_init);
    LOADCURLSYM(curl_easy_setopt);
    LOADCURLSYM(curl_easy_perform);
    LOADCURLSYM(curl_global_init);
    LOADCURLSYM(curl_global_cleanup);

    #define curl_easy_cleanup CURL_curl_easy_cleanup
    #define curl_easy_init CURL_curl_easy_init
    #define curl_easy_setopt CURL_curl_easy_setopt
    #define curl_easy_perform CURL_curl_easy_perform
    #define curl_global_init CURL_curl_global_init
    #define curl_global_cleanup CURL_curl_global_cleanup

    if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) {
        die("curl_global_init() failed!");
    }
}

static void shutdownHttpLib(void)
{
    if (curl_global_cleanup) {
        curl_global_cleanup();
    }
}

static int runHttpDownload(const char *from, FILE *to)
{
    int retval;
    CURL *curl = curl_easy_init();
    if (!curl) {
        info("curl_easy_init() failed");
        return 0;
    }

    #if 0
    /* !!! FIXME: enable compression? */
    curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "");  /* enable compression */

    /* !!! FIXME; hook up proxy support to libcurl */
    curl_easy_setopt(curl, CURLOPT_PROXY, proxyURL);
    #endif

    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
    curl_easy_setopt(curl, CURLOPT_STDERR, logfile);

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, to);

    curl_easy_setopt(curl, CURLOPT_URL, from);

    curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);  /* allow redirects. */
    curl_easy_setopt(curl, CURLOPT_USERAGENT, AUTOUPDATE_USER_AGENT);

    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);  /* require valid SSL cert. */
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);  /* require SSL cert with same hostname as we connected to. */

    retval = (curl_easy_perform(curl) == CURLE_OK);
    curl_easy_cleanup(curl);
    return retval;
}
#endif


static void die(const char *why)
{
    infof("FAILURE: %s", why);
    restoreRollbacks();
    freeManifest();
    infof("Updater ending (in failure), %s", timestamp());
    exit(1);
}

static void outOfMemory(void) NEVER_RETURNS;
static void outOfMemory(void)
{
    die("Out of memory");
}

static void buildParentDirs(const char *_path)
{
    char *ptr;
    char *path = (char *) alloca(strlen(_path) + 1);
    if (!path) {
        outOfMemory();
    }
    strcpy(path, _path);

    for (ptr = path; *ptr; ptr++) {
        if (*ptr == '/') {
            *ptr = '\0';
            makeDir(path);
            *ptr = '/';
        }
    }
}

static int64_t fileLength(const char *fname)
{
    struct stat statbuf;
    if (stat(fname, &statbuf) == -1) {
        return -1;
    }
    return (int64_t) statbuf.st_size;
}

static void parseArgv(int argc, char **argv)
{
    int i;

    infof("command line (argc=%d)...", argc);
    for (i = 0; i < argc; i++) {
        infof("  argv[%d]: %s",i, argv[i]);
    }

    for (i = 1; i < argc; i += 2) {
        if (strcmp(argv[i], "--waitpid") == 0) {
            options.waitforprocess = atoll(argv[i + 1]);
            infof("We will wait for process " PIDFMT " if necessary", (PIDFMTCAST) options.waitforprocess);
        } else if (strcmp(argv[i], "--updateself") == 0) {
            options.updateself = argv[i + 1];
            infof("We are updating ourself ('%s')", options.updateself);
        }
    }
}

static void downloadURL(const char *from, const char *to)
{
    FILE *io = NULL;
    const size_t len = strlen(AUTOUPDATE_URL) + strlen(from) + 1;
    char *fullurl = (char *) alloca(len);
    if (!fullurl) {
        outOfMemory();
    }
    snprintf(fullurl, len, "%s%s", AUTOUPDATE_URL, from);

    infof("Downloading from '%s' to '%s'", fullurl, to);

    buildParentDirs(to);
    io = fopen(to, "wb");
    if (!io) {
        die("Failed to open output file");
    }

    if (!runHttpDownload(fullurl, io)) {
        fclose(io);
        remove(to);
        die("Download failed");
    }

    if (fclose(io) == EOF) {
        die("Can't flush file on close. i/o error? Disk full?");
    }

    chmod(to, 0777);  /* !!! FIXME */
}

static int hexcvt(const int ch)
{
    if ((ch >= 'a') && (ch <= 'f')) {
        return (ch - 'a') + 10;
    } else if ((ch >= 'A') && (ch <= 'F')) {
        return (ch - 'A') + 10;
    } else if ((ch >= '0') && (ch <= '9')) {
        return ch - '0';
    } else {
        die("Invalid hex character");
    }
    return 0;
}

static void convertSha256(char *str, unsigned char *sha256)
{
    int i;
    for (i = 0; i < 32; i++) {
        const int a = hexcvt(*(str++));
        const int b = hexcvt(*(str++));
        *sha256 = (a << 4) | b;
        sha256++;
    }
}

static void parseManifest(const char *fname)
{
    ManifestItem *item = NULL;
    FILE *io = fopen(fname, "r");
    char buf[512];
    if (!io) {
        die("Failed to open manifest for reading");
    }

    /* !!! FIXME: this code sucks. */
    while (fgets(buf, sizeof (buf), io)) {
        char *ptr = (buf + strlen(buf)) - 1;
        while (ptr >= buf) {
            if ((*ptr != '\n') && (*ptr != '\r')) {
                break;
            }
            *ptr = '\0';
            ptr--;
        }

        if (!item && !buf[0]) {
            continue;  /* blank line between items or blank at EOF */
        }

        if (!item) {
            infof("Next manifest item: %s", buf);

            item = (ManifestItem *) calloc(1, sizeof (ManifestItem));
            if (!item) {
                outOfMemory();
            }
            item->fname = strdup(buf);
            if (!item->fname) {
                outOfMemory();
            }
            item->len = -1;
            item->next = NULL;
        } else if (item->len == -1) {
            infof("Item size: %s", buf);
            item->len = atoll(buf);
        } else {
            infof("Item sha256: %s", buf);
            convertSha256(buf, item->sha256);
            item->next = manifest;
            manifest = item;
            item = NULL;
        }
    }

    if (ferror(io)) {
        die("Error reading manifest");
    } else if (item) {
        die("Incomplete manifest");
    }

    fclose(io);
}

static void read_file(const char *fname, void *buf, unsigned long *len)
{
    ssize_t br;
    FILE *io = fopen(fname, "rb");
    if (!io) {
        infof("Can't open '%s' for reading: %s", fname, strerror(errno));
        die("Failed to read file");
    }

    br = fread(buf, 1, *len, io);
    if (ferror(io)) {
        infof("Couldn't read '%s': %s", fname, strerror(errno));
        die("Failed to read file");
    } else if (!feof(io)) {
        infof("Buffer too small to read '%s'", fname);
        die("Failed to read file");
    }
    fclose(io);

    *len = (unsigned long) br;
}

static void read_rsakey(rsa_key *key, const char *fname)
{
    unsigned char buf[4096];
    unsigned long len = sizeof (buf);
    int rc;

    read_file(fname, buf, &len);

    if ((rc = rsa_import(buf, len, key)) != CRYPT_OK) {
        infof("rsa_import for '%s' failed: %s", fname, error_to_string(rc));
        die("Couldn't import public key");
    }
}

static void verifySignature(const char *fname, const char *sigfname, const char *keyfname)
{
    rsa_key key;
    unsigned char hash[256];
    unsigned long hashlen = sizeof (hash);
    unsigned char sig[1024];
    unsigned long siglen = sizeof (sig);
    int status = 0;
    int rc = 0;

    read_rsakey(&key, keyfname);
    read_file(sigfname, sig, &siglen);

    if ((rc = hash_file(sha256_hash_index, fname, hash, &hashlen)) != CRYPT_OK) {
        infof("hash_file for '%s' failed: %s", fname, error_to_string(rc));
        die("Couldn't verify manifest signature");
    }

    if ((rc = rsa_verify_hash(sig, siglen, hash, hashlen, sha256_hash_index, SALT_LEN, &status, &key)) != CRYPT_OK) {
        infof("rsa_verify_hash for '%s' failed: %s", fname, error_to_string(rc));
        die("Couldn't verify manifest signature");
    }

    if (!status) {
        infof("Invalid signature for '%s'! Don't trust this file!", fname);
        die("Manifest is incomplete, corrupt, or compromised");
    }

    info("Manifest signature appears to be valid");
    rsa_free(&key);
}

static void downloadManifest(void)
{
    const char *manifestfname = "updates/manifest.txt";
    const char *manifestsigfname = "updates/manifest.txt.sig";
    downloadURL("manifest.txt", manifestfname);
    downloadURL("manifest.txt.sig", manifestsigfname);
    verifySignature(manifestfname, manifestsigfname, PUBLICKEY_FNAME);
    parseManifest(manifestfname);
}

static void upgradeSelfAndRestart(const char *argv0) NEVER_RETURNS;
static void upgradeSelfAndRestart(const char *argv0)
{
    const char *tempfname = "origUpdater";
    const char *why = NULL;
    FILE *in = NULL;
    FILE *out = NULL;

    /* unix replaces the process with execl(), but Windows needs to wait for the parent to terminate. */
    #ifdef _WIN32
    DWORD ppid = 0;
    HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (h) {
        const DWORD myPid = GetCurrentProcessId();
        PROCESSENTRY32 pe;
        memset(&pe, '\0', sizeof (pe));
        pe.dwSize = sizeof(PROCESSENTRY32);

        if (Process32First(h, &pe)) {
            do {
                if (pe.th32ProcessID == myPid) {
                    ppid = pe.th32ParentProcessID;
                    break;
                }
            } while (Process32Next(h, &pe));
        }
        CloseHandle(h);
    }
    if (!ppid) {
        die("Can't determine parent process id");
    }
    windowsWaitForProcessToDie(ppid);
    #endif

    in = fopen(argv0, "rb");
    if (!in) {
        die("Can't open self for input while upgrading updater");
    }

    remove(tempfname);
    if (rename(options.updateself, tempfname) == -1) {
        die("Can't rename original while upgrading updater");
    }

    out = fopen(options.updateself, "wb");
    if (!out) {
        die("Can't open file for output while upgrading updater");
    }

    while (!feof(in) && !why) {
        char buf[512];
        const size_t br = fread(buf, 1, sizeof (buf), in);
        if (br > 0) {
            if (fwrite(buf, br, 1, out) != 1) {
                why = "write failure while upgrading updater";
            }
        } else if (ferror(in)) {
            why = "read failure while upgrading updater";
        }
    }

    fclose(in);

    if ((fclose(out) == EOF) && (!why)) {
        why = "close failure while upgrading updater";
    }

    if (why) {
        remove(options.updateself);
        rename(tempfname, options.updateself);
        die(why);
    }

    remove(tempfname);

    chmod(options.updateself, 0777);

    if (options.waitforprocess) {
        char pidstr[64];
        snprintf(pidstr, sizeof (pidstr), PIDFMT, (PIDFMTCAST) options.waitforprocess);
        launchProcess(options.updateself, options.updateself, "--waitpid", pidstr, NULL);
    } else {
        launchProcess(options.updateself, options.updateself, NULL);
    }
    die("Failed to relaunch upgraded updater");
}

static const char *justFilename(const char *path)
{
    const char *fname = strrchr(path, '/');
    return fname ? fname + 1 : path;
}

static void hashFile(const char *fname, unsigned char *sha256)
{
    int rc = 0;
    unsigned long hashlen = 32;
    if ((rc = hash_file(sha256_hash_index, fname, sha256, &hashlen)) != CRYPT_OK) {
        infof("hash_file failed for '%s': %s", fname, error_to_string(rc));
        die("Can't hash file");
    }
}

static int fileHashMatches(const char *fname, const unsigned char *wanted)
{
    unsigned char sha256[32];
    hashFile(fname, sha256);
    return (memcmp(sha256, wanted, 32) == 0);
}

static int fileNeedsUpdate(const ManifestItem *item)
{
    if (item->len != fileLength(item->fname)) {
        infof("Update '%s', file size is different", item->fname);
        return 1;  /* obviously different. */
    } else if (!fileHashMatches(item->fname, item->sha256)) {
        infof("Update '%s', file sha256 is different", item->fname);
        return 1;
    }

    infof("Don't update '%s', the file is already up to date", item->fname);
    return 0;
}

static void downloadFile(const ManifestItem *item)
{
    const char *outpath = "updates/downloads/";
    const size_t len = strlen(outpath) + strlen(item->fname) + 1;
    char *to = (char *) alloca(len);
    if (!to) {
        outOfMemory();
    }

    snprintf(to, len, "%s%s", outpath, item->fname);

    if ((item->len == fileLength(to)) && fileHashMatches(to, item->sha256)) {
        infof("Already downloaded '%s', not getting again", item->fname);
    } else {
        downloadURL(item->fname, to);
        if ((item->len != fileLength(to)) || !fileHashMatches(to, item->sha256)) {
            die("Download is incorrect or corrupted");
        }
    }
}

static int downloadUpdates(void)
{
    int updatesAvailable = 0;
    ManifestItem *item;
    for (item = manifest; item != NULL; item = item->next) {
        item->update = fileNeedsUpdate(item);
        if (item->update) {
            updatesAvailable = 1;
            downloadFile(item);
        }
    }
    return updatesAvailable;
}

static void maybeUpdateSelf(const char *argv0)
{
    ManifestItem *item;

    /* !!! FIXME: this needs to be a different string on macOS. */
    const char *fname = justFilename(argv0);

    for (item = manifest; item != NULL; item = item->next) {
        if (strcasecmp(item->fname, fname) == 0) {
            if (fileNeedsUpdate(item)) {
                const char *outpath = "updates/downloads/";
                const size_t len = strlen(outpath) + strlen(item->fname) + 1;
                char *to = (char *) alloca(len);
                if (!to) {
                    outOfMemory();
                }
                snprintf(to, len, "%s%s", outpath, item->fname);
                info("Have to upgrade the updater");
                downloadFile(item);
                chmod(to, 0777);

                if (options.waitforprocess) {
                    char pidstr[64];
                    snprintf(pidstr, sizeof (pidstr), PIDFMT, (PIDFMTCAST) options.waitforprocess);
                    launchProcess(to, to, "--updateself", argv0, "--waitpid", pidstr, NULL);
                } else {
                    launchProcess(to, to, "--updateself", argv0, NULL);
                }
                die("Failed to initially launch upgraded updater");
            }
            break;  /* done in any case. */
        }
    }
}

static void installUpdatedFile(const ManifestItem *item)
{
    const char *basepath = "updates/downloads/";
    const size_t len = strlen(basepath) + strlen(item->fname) + 1;
    char *downloadPath = (char *) alloca(len);
    if (!downloadPath) {
        outOfMemory();
    }

    snprintf(downloadPath, len, "%s%s", basepath, item->fname);

    infof("Moving file for update: '%s' -> '%s'", downloadPath, item->fname);
    buildParentDirs(item->fname);
    if (rename(downloadPath, item->fname) == -1) {
        die("Failed to move updated file to final position");
    }
}

static void applyUpdates(void)
{
    FILE *io;
    ManifestItem *item;
    for (item = manifest; item != NULL; item = item->next) {
        if (!item->update) {
            continue;
        }

        io = fopen(item->fname, "rb");
        if (io != NULL) {
            static int rollbackIndex = 0;
            char rollbackPath[64];
            fclose(io);
            item->rollback = ++rollbackIndex;
            snprintf(rollbackPath, sizeof (rollbackPath), "updates/rollbacks/%d", rollbackIndex);
            infof("Moving file for rollback: '%s' -> '%s'", item->fname, rollbackPath);
            remove(rollbackPath);
            if (rename(item->fname, rollbackPath) == -1) {
                die("failed to move to rollback dir");
            }
        }

        installUpdatedFile(item);
    }
}


static void waitToApplyUpdates(void)
{
    if (options.waitforprocess) {
        infof("Waiting for pid " PIDFMT " to die...", (PIDFMTCAST) options.waitforprocess);
        {
            #ifdef _WIN32
            windowsWaitForProcessToDie(options.waitforprocess);
            #else
            /* The parent opens a pipe on fd 3, and then forgets about it. We block
               on a read to that pipe here. When the game process quits (and the
               OS forcibly closes the pipe), we will unblock. Then we can loop on
               kill() until the process is truly gone. */
            int x = 0;
            struct timespec req;
            req.tv_sec = 0;
            req.tv_nsec = 100000000;
            read(3, &x, sizeof (x));
            info("Pipe has closed, waiting for process to fully go away now.");
            while (kill(options.waitforprocess, 0) == 0) {
                nanosleep(&req, NULL);
            }
            #endif
        }
        info("pid is gone, continuing");
    }
}

static void deleteRollbacks(void)
{
    ManifestItem *item;
    for (item = manifest; item != NULL; item = item->next) {
        if (item->rollback) {
            char rollbackPath[64];
            snprintf(rollbackPath, sizeof (rollbackPath), "updates/rollbacks/%d", item->rollback);
            infof("delete rollback: %s", rollbackPath);
            remove(rollbackPath);
        }
    }
}

static void chdirToBasePath(const char *argv0)
{
    const char *fname = justFilename(argv0);
    size_t len;
    char *buf;

    if (fname == argv0) { /* no path? Assume we're already there. */
        return;
    }

    len = ((size_t) (fname - argv0)) - 1;
    buf = (char *) alloca(len);
    if (!buf) {
        outOfMemory();
    }

    memcpy(buf, argv0, len);
    buf[len] = '\0';
    if (chdir(buf) == -1) {
        infof("base path is '%s'", buf);
        die("chdir to base path failed");
    }
}

int main(int argc, char **argv)
{
    #ifndef _WIN32
    signal(SIGPIPE, SIG_IGN);  /* don't trigger signal when fd3 closes */
    #endif

    logfile = stdout;
    chdirToBasePath(argv[0]);

    makeDir("updates");
    makeDir("updates/downloads");
    makeDir("updates/rollbacks");

    logfile = fopen("updates/updater-log.txt", "a");
    if (!logfile) {
        logfile = stdout;
    }

    infof("Updater starting, %s", timestamp());

    parseArgv(argc, argv);

    /* set up crypto */
    ltc_mp = tfm_desc;
    sha256_hash_index = register_hash(&sha256_desc);
    if (sha256_hash_index == -1) {
        die("Failed to register sha256 hasher");
    }

    /* if we have downloaded a new updater and restarted with that binary,
       replace the original updater and restart again in the right place. */
    if (options.updateself) {
        upgradeSelfAndRestart(argv[0]);
    }

    prepHttpLib();

    downloadManifest();  /* see if we need an update at all. */

    maybeUpdateSelf(argv[0]);  /* might relaunch if there's an updater upgrade. */

    if (!downloadUpdates()) {
        info("Nothing needs updating, so we're done here!");
    } else {
        waitToApplyUpdates();
        applyUpdates();
        deleteRollbacks();
        info("You are now up to date!");
    }

    freeManifest();
    shutdownHttpLib();

    unregister_hash(&sha256_desc);

    infof("Updater ending, %s", timestamp());

    return 0;
}