-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathruntime.c
1853 lines (1575 loc) · 61.8 KB
/
runtime.c
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
/**************************************************************************
*
* PLEASE NOTE:
* This version of the AppImage runtime is meant to be as self-contained
* as possible (one .c file) and use as few external dependencies
* as possible
*
* Copyright (c) 2004-24 Simon Peter
* Portions Copyright (c) 2007 Alexander Larsson
* Portions from WjCryptLib_Md5 originally written by Alexander Peslyak,
modified by WaterJuice retaining Public Domain license
*
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#ident "AppImage by Simon Peter, https://appimage.org/"
#define _GNU_SOURCE
#include <stddef.h>
#include <squashfuse/ll.h>
#include <squashfuse/fuseprivate.h>
extern dev_t sqfs_makedev(int maj, int min);
extern int sqfs_opt_proc(void* data, const char* arg, int key, struct fuse_args* outargs);
#include <limits.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ftw.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <sys/wait.h>
#include <fnmatch.h>
#include <sys/mman.h>
#include <stdint.h>
#include <libgen.h>
#include <dirent.h>
#include <ctype.h>
const char* fusermountPath = NULL;
typedef struct {
uint32_t lo;
uint32_t hi;
uint32_t a;
uint32_t b;
uint32_t c;
uint32_t d;
uint8_t buffer[64];
uint32_t block[16];
} Md5Context;
#define MD5_HASH_SIZE (128 / 8)
typedef struct {
uint8_t bytes[MD5_HASH_SIZE];
} MD5_HASH;
typedef uint16_t Elf32_Half;
typedef uint16_t Elf64_Half;
typedef uint32_t Elf32_Word;
typedef uint32_t Elf64_Word;
typedef uint64_t Elf64_Xword;
typedef uint32_t Elf32_Addr;
typedef uint64_t Elf64_Addr;
typedef uint32_t Elf32_Off;
typedef uint64_t Elf64_Off;
#define EI_NIDENT 16
typedef struct elf32_hdr {
unsigned char e_ident[EI_NIDENT];
Elf32_Half e_type;
Elf32_Half e_machine;
Elf32_Word e_version;
Elf32_Addr e_entry; /* Entry point */
Elf32_Off e_phoff;
Elf32_Off e_shoff;
Elf32_Word e_flags;
Elf32_Half e_ehsize;
Elf32_Half e_phentsize;
Elf32_Half e_phnum;
Elf32_Half e_shentsize;
Elf32_Half e_shnum;
Elf32_Half e_shstrndx;
} Elf32_Ehdr;
typedef struct elf64_hdr {
unsigned char e_ident[EI_NIDENT]; /* ELF "magic number" */
Elf64_Half e_type;
Elf64_Half e_machine;
Elf64_Word e_version;
Elf64_Addr e_entry; /* Entry point virtual address */
Elf64_Off e_phoff; /* Program header table file offset */
Elf64_Off e_shoff; /* Section header table file offset */
Elf64_Word e_flags;
Elf64_Half e_ehsize;
Elf64_Half e_phentsize;
Elf64_Half e_phnum;
Elf64_Half e_shentsize;
Elf64_Half e_shnum;
Elf64_Half e_shstrndx;
} Elf64_Ehdr;
typedef struct elf32_shdr {
Elf32_Word sh_name;
Elf32_Word sh_type;
Elf32_Word sh_flags;
Elf32_Addr sh_addr;
Elf32_Off sh_offset;
Elf32_Word sh_size;
Elf32_Word sh_link;
Elf32_Word sh_info;
Elf32_Word sh_addralign;
Elf32_Word sh_entsize;
} Elf32_Shdr;
typedef struct elf64_shdr {
Elf64_Word sh_name; /* Section name, index in string tbl */
Elf64_Word sh_type; /* Type of section */
Elf64_Xword sh_flags; /* Miscellaneous section attributes */
Elf64_Addr sh_addr; /* Section virtual addr at execution */
Elf64_Off sh_offset; /* Section file offset */
Elf64_Xword sh_size; /* Size of section in bytes */
Elf64_Word sh_link; /* Index of another section */
Elf64_Word sh_info; /* Additional section information */
Elf64_Xword sh_addralign; /* Section alignment */
Elf64_Xword sh_entsize; /* Entry size if section holds table */
} Elf64_Shdr;
/* Note header in a PT_NOTE section */
typedef struct elf32_note {
Elf32_Word n_namesz; /* Name size */
Elf32_Word n_descsz; /* Content size */
Elf32_Word n_type; /* Content type */
} Elf32_Nhdr;
#define ELFCLASS32 1
#define ELFDATA2LSB 1
#define ELFDATA2MSB 2
#define ELFCLASS64 2
#define EI_CLASS 4
#define EI_DATA 5
#define bswap_16(value) \
((((value) & 0xff) << 8) | ((value) >> 8))
#define bswap_32(value) \
(((uint32_t)bswap_16((uint16_t)((value) & 0xffff)) << 16) | \
(uint32_t)bswap_16((uint16_t)((value) >> 16)))
#define bswap_64(value) \
(((uint64_t)bswap_32((uint32_t)((value) & 0xffffffff)) \
<< 32) | \
(uint64_t)bswap_32((uint32_t)((value) >> 32)))
typedef Elf32_Nhdr Elf_Nhdr;
static Elf64_Ehdr ehdr;
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define ELFDATANATIVE ELFDATA2LSB
#elif __BYTE_ORDER == __BIG_ENDIAN
#define ELFDATANATIVE ELFDATA2MSB
#else
#error "Unknown machine endian"
#endif
static uint16_t file16_to_cpu(uint16_t val) {
if (ehdr.e_ident[EI_DATA] != ELFDATANATIVE)
val = bswap_16(val);
return val;
}
static uint32_t file32_to_cpu(uint32_t val) {
if (ehdr.e_ident[EI_DATA] != ELFDATANATIVE)
val = bswap_32(val);
return val;
}
static uint64_t file64_to_cpu(uint64_t val) {
if (ehdr.e_ident[EI_DATA] != ELFDATANATIVE)
val = bswap_64(val);
return val;
}
static off_t read_elf32(FILE* fd) {
Elf32_Ehdr ehdr32;
Elf32_Shdr shdr32;
off_t last_shdr_offset;
ssize_t ret;
off_t sht_end, last_section_end;
fseeko(fd, 0, SEEK_SET);
ret = fread(&ehdr32, 1, sizeof(ehdr32), fd);
if (ret < 0 || (size_t) ret != sizeof(ehdr32)) {
fprintf(stderr, "Read of ELF header failed: %s\n", strerror(errno));
return -1;
}
ehdr.e_shoff = file32_to_cpu(ehdr32.e_shoff);
ehdr.e_shentsize = file16_to_cpu(ehdr32.e_shentsize);
ehdr.e_shnum = file16_to_cpu(ehdr32.e_shnum);
last_shdr_offset = ehdr.e_shoff + (ehdr.e_shentsize * (ehdr.e_shnum - 1));
fseeko(fd, last_shdr_offset, SEEK_SET);
ret = fread(&shdr32, 1, sizeof(shdr32), fd);
if (ret < 0 || (size_t) ret != sizeof(shdr32)) {
fprintf(stderr, "Read of ELF section header failed: %s\n", strerror(errno));
return -1;
}
/* ELF ends either with the table of section headers (SHT) or with a section. */
sht_end = ehdr.e_shoff + (ehdr.e_shentsize * ehdr.e_shnum);
last_section_end = file64_to_cpu(shdr32.sh_offset) + file64_to_cpu(shdr32.sh_size);
return sht_end > last_section_end ? sht_end : last_section_end;
}
static off_t read_elf64(FILE* fd) {
Elf64_Ehdr ehdr64;
Elf64_Shdr shdr64;
off_t last_shdr_offset;
off_t ret;
off_t sht_end, last_section_end;
fseeko(fd, 0, SEEK_SET);
ret = fread(&ehdr64, 1, sizeof(ehdr64), fd);
if (ret < 0 || (size_t) ret != sizeof(ehdr64)) {
fprintf(stderr, "Read of ELF header failed: %s\n", strerror(errno));
return -1;
}
ehdr.e_shoff = file64_to_cpu(ehdr64.e_shoff);
ehdr.e_shentsize = file16_to_cpu(ehdr64.e_shentsize);
ehdr.e_shnum = file16_to_cpu(ehdr64.e_shnum);
last_shdr_offset = ehdr.e_shoff + (ehdr.e_shentsize * (ehdr.e_shnum - 1));
fseeko(fd, last_shdr_offset, SEEK_SET);
ret = fread(&shdr64, 1, sizeof(shdr64), fd);
if (ret < 0 || ret != sizeof(shdr64)) {
fprintf(stderr, "Read of ELF section header failed: %s\n", strerror(errno));
return -1;
}
/* ELF ends either with the table of section headers (SHT) or with a section. */
sht_end = ehdr.e_shoff + (ehdr.e_shentsize * ehdr.e_shnum);
last_section_end = file64_to_cpu(shdr64.sh_offset) + file64_to_cpu(shdr64.sh_size);
return sht_end > last_section_end ? sht_end : last_section_end;
}
ssize_t appimage_get_elf_size(const char* fname) {
off_t ret;
FILE* fd = NULL;
off_t size = -1;
fd = fopen(fname, "rb");
if (fd == NULL) {
fprintf(stderr, "Cannot open %s: %s\n",
fname, strerror(errno));
return -1;
}
ret = fread(ehdr.e_ident, 1, EI_NIDENT, fd);
if (ret != EI_NIDENT) {
fprintf(stderr, "Read of e_ident from %s failed: %s\n", fname, strerror(errno));
return -1;
}
if ((ehdr.e_ident[EI_DATA] != ELFDATA2LSB) &&
(ehdr.e_ident[EI_DATA] != ELFDATA2MSB)) {
fprintf(stderr, "Unknown ELF data order %u\n",
ehdr.e_ident[EI_DATA]);
return -1;
}
if (ehdr.e_ident[EI_CLASS] == ELFCLASS32) {
size = read_elf32(fd);
} else if (ehdr.e_ident[EI_CLASS] == ELFCLASS64) {
size = read_elf64(fd);
} else {
fprintf(stderr, "Unknown ELF class %u\n", ehdr.e_ident[EI_CLASS]);
return -1;
}
fclose(fd);
return size;
}
/* Return the offset, and the length of an ELF section with a given name in a given ELF file */
bool appimage_get_elf_section_offset_and_length(const char* fname, const char* section_name, unsigned long* offset, unsigned long* length) {
uint8_t* data;
int i;
int fd = open(fname, O_RDONLY);
size_t map_size = (size_t) lseek(fd, 0, SEEK_END);
data = mmap(NULL, map_size, PROT_READ, MAP_SHARED, fd, 0);
close(fd);
// this trick works as both 32 and 64 bit ELF files start with the e_ident[EI_NINDENT] section
unsigned char class = data[EI_CLASS];
if (class == ELFCLASS32) {
Elf32_Ehdr* elf;
Elf32_Shdr* shdr;
elf = (Elf32_Ehdr*) data;
shdr = (Elf32_Shdr*) (data + ((Elf32_Ehdr*) elf)->e_shoff);
char* strTab = (char*) (data + shdr[elf->e_shstrndx].sh_offset);
for (i = 0; i < elf->e_shnum; i++) {
if (strcmp(&strTab[shdr[i].sh_name], section_name) == 0) {
*offset = shdr[i].sh_offset;
*length = shdr[i].sh_size;
}
}
} else if (class == ELFCLASS64) {
Elf64_Ehdr* elf;
Elf64_Shdr* shdr;
elf = (Elf64_Ehdr*) data;
shdr = (Elf64_Shdr*) (data + elf->e_shoff);
char* strTab = (char*) (data + shdr[elf->e_shstrndx].sh_offset);
for (i = 0; i < elf->e_shnum; i++) {
if (strcmp(&strTab[shdr[i].sh_name], section_name) == 0) {
*offset = shdr[i].sh_offset;
*length = shdr[i].sh_size;
}
}
} else {
fprintf(stderr, "Platforms other than 32-bit/64-bit are currently not supported!");
munmap(data, map_size);
return false;
}
munmap(data, map_size);
return true;
}
/* Return the offset, and the length of an ELF section with a given name in a given ELF file */
char* read_file_offset_length(const char* fname, unsigned long offset, unsigned long length) {
FILE* f;
if ((f = fopen(fname, "r")) == NULL) {
return NULL;
}
fseek(f, offset, SEEK_SET);
char* buffer = calloc(length + 1, sizeof(char));
fread(buffer, length, sizeof(char), f);
fclose(f);
return buffer;
}
int appimage_print_hex(char* fname, unsigned long offset, unsigned long length) {
char* data;
if ((data = read_file_offset_length(fname, offset, length)) == NULL) {
return 1;
}
for (long long k = 0; k < length && data[k] != '\0'; k++) {
printf("%x", data[k]);
}
free(data);
printf("\n");
return 0;
}
int appimage_print_binary(char* fname, unsigned long offset, unsigned long length) {
char* data;
if ((data = read_file_offset_length(fname, offset, length)) == NULL) {
return 1;
}
printf("%s\n", data);
free(data);
return 0;
}
char* find_fusermount(bool verbose) {
char* fusermount_base = "fusermount";
char* fusermount_path = getenv("PATH");
if (fusermount_path == NULL) {
return NULL;
}
char* path_copy = strdup(fusermount_path);
char* dir = strtok(path_copy, ":");
while (dir != NULL) {
DIR* dir_ptr = opendir(dir);
if (dir_ptr == NULL) {
dir = strtok(NULL, ":");
continue;
}
struct dirent* entry;
while ((entry = readdir(dir_ptr)) != NULL) {
// Check if the entry starts with "fusermount"
if (strncmp(entry->d_name, fusermount_base, 10) == 0) {
// Check if the rest of the entry is a digit
char* suffix = entry->d_name + 10;
int j = 0;
while (suffix[j] != '\0' && isdigit(suffix[j])) {
j++;
}
if (suffix[j] == '\0') {
// Construct the full path of the entry
char* fusermount_full_path = malloc(strlen(dir) + strlen(entry->d_name) + 2);
sprintf(fusermount_full_path, "%s/%s", dir, entry->d_name);
// Check if the binary is setuid root
struct stat sb;
if (stat(fusermount_full_path, &sb) == -1) {
perror("stat");
free(fusermount_full_path);
continue;
}
if (sb.st_uid != 0 || (sb.st_mode & S_ISUID) == 0) {
if (verbose) {
printf("Not setuid root, skipping...\n");
}
free(fusermount_full_path);
continue;
}
if (verbose) {
printf("Found setuid root executable: %s\n", fusermount_full_path);
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
free(fusermount_full_path);
continue;
}
if (pid == 0) {
// Child process
// close stdout and stderr if not in verbose mode
if (!verbose) {
close(1);
close(2);
}
char* args[] = {fusermount_full_path, "--version", NULL};
execvp(fusermount_full_path, args);
// If execvp returns, it means the executable was not found
exit(1);
} else {
// Parent process
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
// The executable was found and executed successfully
closedir(dir_ptr);
free(path_copy);
return fusermount_full_path;
}
free(fusermount_full_path);
}
}
}
}
closedir(dir_ptr);
dir = strtok(NULL, ":");
}
free(path_copy);
return NULL;
}
/* Exit status to use when launching an AppImage fails.
* For applications that assign meanings to exit status codes (e.g. rsync),
* we avoid "cluttering" pre-defined exit status codes by using 127 which
* is known to alias an application exit status and also known as launcher
* error, see SYSTEM(3POSIX).
*/
#define EXIT_EXECERROR 127 /* Execution error exit status. */
struct stat st;
static ssize_t fs_offset; // The offset at which a filesystem image is expected = end of this ELF
static void die(const char* msg) {
fprintf(stderr, "%s\n", msg);
exit(EXIT_EXECERROR);
}
/* Check whether directory is writable */
bool is_writable_directory(char* str) {
if (access(str, W_OK) == 0) {
return true;
} else {
return false;
}
}
bool startsWith(const char* pre, const char* str) {
size_t lenpre = strlen(pre),
lenstr = strlen(str);
return lenstr < lenpre ? false : strncmp(pre, str, lenpre) == 0;
}
/* Fill in a stat structure. Does not set st_ino */
sqfs_err private_sqfs_stat(sqfs* fs, sqfs_inode* inode, struct stat* st) {
sqfs_err err = SQFS_OK;
uid_t id;
memset(st, 0, sizeof(*st));
st->st_mode = inode->base.mode;
st->st_nlink = inode->nlink;
st->st_mtime = st->st_ctime = st->st_atime = inode->base.mtime;
if (S_ISREG(st->st_mode)) {
/* FIXME: do symlinks, dirs, etc have a size? */
st->st_size = inode->xtra.reg.file_size;
st->st_blocks = st->st_size / 512;
} else if (S_ISBLK(st->st_mode) || S_ISCHR(st->st_mode)) {
st->st_rdev = sqfs_makedev(inode->xtra.dev.major,
inode->xtra.dev.minor);
} else if (S_ISLNK(st->st_mode)) {
st->st_size = inode->xtra.symlink_size;
}
st->st_blksize = fs->sb.block_size; /* seriously? */
err = sqfs_id_get(fs, inode->base.uid, &id);
if (err)
return err;
st->st_uid = id;
err = sqfs_id_get(fs, inode->base.guid, &id);
st->st_gid = id;
if (err)
return err;
return SQFS_OK;
}
/* ================= End ELF parsing */
extern int fusefs_main(int argc, char* argv[], void (* mounted)(void));
// extern void ext2_quit(void);
static pid_t fuse_pid;
static int keepalive_pipe[2];
static void*
write_pipe_thread(void* arg) {
char c[32];
int res;
// sprintf(stderr, "Called write_pipe_thread");
memset(c, 'x', sizeof(c));
while (1) {
/* Write until we block, on broken pipe, exit */
res = write(keepalive_pipe[1], c, sizeof(c));
if (res == -1) {
kill(fuse_pid, SIGTERM);
break;
}
}
return NULL;
}
void
fuse_mounted(void) {
pthread_t thread;
fuse_pid = getpid();
pthread_create(&thread, NULL, write_pipe_thread, keepalive_pipe);
}
char* getArg(int argc, char* argv[], char chr) {
int i;
for (i = 1; i < argc; ++i)
if ((argv[i][0] == '-') && (argv[i][1] == chr))
return &(argv[i][2]);
return NULL;
}
/* mkdir -p implemented in C, needed for https://github.com/AppImage/AppImageKit/issues/333
* https://gist.github.com/JonathonReinhart/8c0d90191c38af2dcadb102c4e202950 */
int
mkdir_p(const char* const path) {
/* Adapted from http://stackoverflow.com/a/2336245/119527 */
const size_t len = strlen(path);
char _path[PATH_MAX];
char* p;
errno = 0;
/* Copy string so its mutable */
if (len > sizeof(_path) - 1) {
errno = ENAMETOOLONG;
return -1;
}
strcpy(_path, path);
/* Iterate the string */
for (p = _path + 1; *p; p++) {
if (*p == '/') {
/* Temporarily truncate */
*p = '\0';
if (mkdir(_path, 0755) != 0) {
if (errno != EEXIST)
return -1;
}
*p = '/';
}
}
if (mkdir(_path, 0755) != 0) {
if (errno != EEXIST)
return -1;
}
return 0;
}
void print_help(const char* appimage_path) {
// TODO: "--appimage-list List content from embedded filesystem image\n"
fprintf(stderr,
"AppImage options:\n\n"
" --appimage-extract [<pattern>] Extract content from embedded filesystem image\n"
" If pattern is passed, only extract matching\n"
" files\n"
" --appimage-extract-and-run Temporarily extract content from embedded\n"
" filesystem image, run contained application,\n"
" then delete temporarily extracted content\n"
" --appimage-help Print this help\n"
" --appimage-mount Mount embedded filesystem image and print\n"
" mount point and wait for kill with Ctrl-C\n"
" --appimage-offset Print byte offset to start of embedded\n"
" filesystem image\n"
" --appimage-portable-home Create a portable home folder to use as $HOME\n"
" --appimage-portable-config Create a portable config folder to use as\n"
" $XDG_CONFIG_HOME\n"
" --appimage-signature Print digital signature embedded in AppImage\n"
" --appimage-updateinfo[rmation] Print update info embedded in AppImage\n"
" --appimage-version Print version of AppImage runtime\n"
"\n"
"Portable home:\n"
"\n"
" If you would like the application contained inside this AppImage to store its\n"
" data alongside this AppImage rather than in your home directory, then you can\n"
" place a directory named\n"
"\n"
" %s.home\n"
"\n"
" Or you can invoke this AppImage with the --appimage-portable-home option,\n"
" which will create this directory for you. As long as the directory exists\n"
" and is neither moved nor renamed, the application contained inside this\n"
" AppImage to store its data in this directory rather than in your home\n"
" directory\n"
"\n"
"License:\n"
" This executable contains code from\n"
" * runtime, licensed under the terms of\n"
" https://github.com/probonopd/static-tools/blob/master/LICENSE\n"
" * musl libc, licensed under the terms of\n"
" https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT\n"
" * libfuse, licensed under the terms of\n"
" https://github.com/libfuse/libfuse/blob/master/LGPL2.txt\n"
" * squashfuse, licensed under the terms of\n"
" https://github.com/vasi/squashfuse/blob/master/LICENSE\n"
" * libzstd, licensed under the terms of\n"
" https://github.com/facebook/zstd/blob/dev/LICENSE\n"
" * zlib, licensed under the terms of\n"
" https://zlib.net/zlib_license.html\n"
"Please see https://github.com/probonopd/static-tools/\n"
"for information on how to obtain and build the source code\n", appimage_path);
}
void portable_option(const char* arg, const char* appimage_path, const char* name) {
char option[32];
sprintf(option, "appimage-portable-%s", name);
if (arg && strcmp(arg, option) == 0) {
char portable_dir[PATH_MAX];
char fullpath[PATH_MAX];
ssize_t length = readlink(appimage_path, fullpath, sizeof(fullpath));
if (length < 0) {
fprintf(stderr, "Error getting realpath for %s\n", appimage_path);
exit(EXIT_FAILURE);
}
fullpath[length] = '\0';
sprintf(portable_dir, "%s.%s", fullpath, name);
if (!mkdir(portable_dir, S_IRWXU))
fprintf(stderr, "Portable %s directory created at %s\n", name, portable_dir);
else
fprintf(stderr, "Error creating portable %s directory at %s: %s\n", name, portable_dir, strerror(errno));
exit(0);
}
}
bool extract_appimage(const char* const appimage_path, const char* const _prefix, const char* const _pattern,
const bool overwrite, const bool verbose) {
sqfs_err err = SQFS_OK;
sqfs_traverse trv;
sqfs fs;
char prefixed_path_to_extract[1024];
// local copy we can modify safely
// allocate 1 more byte than we would need so we can add a trailing slash if there is none yet
char* prefix = malloc(strlen(_prefix) + 2);
strcpy(prefix, _prefix);
// sanitize prefix
if (prefix[strlen(prefix) - 1] != '/')
strcat(prefix, "/");
if (access(prefix, F_OK) == -1) {
if (mkdir_p(prefix) == -1) {
perror("mkdir_p error");
return false;
}
}
if ((err = sqfs_open_image(&fs, appimage_path, (size_t) fs_offset))) {
fprintf(stderr, "Failed to open squashfs image\n");
return false;
};
// track duplicate inodes for hardlinks
char** created_inode = calloc(fs.sb.inodes, sizeof(char*));
if (created_inode == NULL) {
fprintf(stderr, "Failed allocating memory to track hardlinks\n");
return false;
}
if ((err = sqfs_traverse_open(&trv, &fs, sqfs_inode_root(&fs)))) {
fprintf(stderr, "sqfs_traverse_open error\n");
free(created_inode);
return false;
}
bool rv = true;
while (sqfs_traverse_next(&trv, &err)) {
if (!trv.dir_end) {
if (_pattern == NULL || fnmatch(_pattern, trv.path, FNM_FILE_NAME | FNM_LEADING_DIR) == 0) {
// fprintf(stderr, "trv.path: %s\n", trv.path);
// fprintf(stderr, "sqfs_inode_id: %lu\n", trv.entry.inode);
sqfs_inode inode;
if (sqfs_inode_get(&fs, &inode, trv.entry.inode)) {
fprintf(stderr, "sqfs_inode_get error\n");
rv = false;
break;
}
// fprintf(stderr, "inode.base.inode_type: %i\n", inode.base.inode_type);
// fprintf(stderr, "inode.xtra.reg.file_size: %lu\n", inode.xtra.reg.file_size);
strcpy(prefixed_path_to_extract, "");
strcat(strcat(prefixed_path_to_extract, prefix), trv.path);
if (verbose)
fprintf(stdout, "%s\n", prefixed_path_to_extract);
if (inode.base.inode_type == SQUASHFS_DIR_TYPE || inode.base.inode_type == SQUASHFS_LDIR_TYPE) {
// fprintf(stderr, "inode.xtra.dir.parent_inode: %ui\n", inode.xtra.dir.parent_inode);
// fprintf(stderr, "mkdir_p: %s/\n", prefixed_path_to_extract);
if (access(prefixed_path_to_extract, F_OK) == -1) {
if (mkdir_p(prefixed_path_to_extract) == -1) {
perror("mkdir_p error");
rv = false;
break;
}
}
} else if (inode.base.inode_type == SQUASHFS_REG_TYPE || inode.base.inode_type == SQUASHFS_LREG_TYPE) {
// if we've already created this inode, then this is a hardlink
char* existing_path_for_inode = created_inode[inode.base.inode_number - 1];
if (existing_path_for_inode != NULL) {
unlink(prefixed_path_to_extract);
if (link(existing_path_for_inode, prefixed_path_to_extract) == -1) {
fprintf(stderr, "Couldn't create hardlink from \"%s\" to \"%s\": %s\n",
prefixed_path_to_extract, existing_path_for_inode, strerror(errno));
rv = false;
break;
} else {
continue;
}
} else {
struct stat st;
if (!overwrite && stat(prefixed_path_to_extract, &st) == 0 &&
st.st_size == inode.xtra.reg.file_size) {
if (verbose) {
fprintf(stderr, "File exists and file size matches, skipping\n");
}
continue;
}
// track the path we extract to for this inode, so that we can `link` if this inode is found again
created_inode[inode.base.inode_number - 1] = strdup(prefixed_path_to_extract);
// fprintf(stderr, "Extract to: %s\n", prefixed_path_to_extract);
if (private_sqfs_stat(&fs, &inode, &st) != 0)
die("private_sqfs_stat error");
// create parent dir
char* p = strrchr(prefixed_path_to_extract, '/');
if (p) {
// set an \0 to end the split the string
*p = '\0';
mkdir_p(prefixed_path_to_extract);
// restore dir seprator
*p = '/';
}
// Read the file in chunks
off_t bytes_already_read = 0;
sqfs_off_t bytes_at_a_time = 64 * 1024;
FILE* f;
f = fopen(prefixed_path_to_extract, "w+");
if (f == NULL) {
perror("fopen error");
rv = false;
break;
}
while (bytes_already_read < inode.xtra.reg.file_size) {
char buf[bytes_at_a_time];
if (sqfs_read_range(&fs, &inode, (sqfs_off_t) bytes_already_read, &bytes_at_a_time, buf)) {
perror("sqfs_read_range error");
rv = false;
break;
}
// fwrite(buf, 1, bytes_at_a_time, stdout);
fwrite(buf, 1, bytes_at_a_time, f);
bytes_already_read = bytes_already_read + bytes_at_a_time;
}
fflush(f);
int fd = fileno(f);
struct timespec times[] = { st.st_atim, st.st_mtim };
if (futimens(fd, times) != 0)
fprintf(stderr, "futimens: %s\n", strerror(errno));
fclose(f);
chmod(prefixed_path_to_extract, st.st_mode);
if (!rv)
break;
}
} else if (inode.base.inode_type == SQUASHFS_SYMLINK_TYPE ||
inode.base.inode_type == SQUASHFS_LSYMLINK_TYPE) {
size_t size;
sqfs_readlink(&fs, &inode, NULL, &size);
char buf[size];
int ret = sqfs_readlink(&fs, &inode, buf, &size);
if (ret != 0) {
perror("symlink error");
rv = false;
break;
}
// fprintf(stderr, "Symlink: %s to %s \n", prefixed_path_to_extract, buf);
unlink(prefixed_path_to_extract);
ret = symlink(buf, prefixed_path_to_extract);
if (ret != 0)
fprintf(stderr, "WARNING: could not create symlink\n");
} else {
fprintf(stderr, "TODO: Implement inode.base.inode_type %i\n", inode.base.inode_type);
}
// fprintf(stderr, "\n");
if (!rv)
break;
}
}
}
for (int i = 0; i < fs.sb.inodes; i++) {
free(created_inode[i]);
}
free(created_inode);
if (err != SQFS_OK) {
fprintf(stderr, "sqfs_traverse_next error\n");
rv = false;
}
sqfs_traverse_close(&trv);
sqfs_fd_close(fs.fd);
return rv;
}
int rm_recursive_callback(const char* path, const struct stat* stat, const int type, struct FTW* ftw) {
(void) stat;
(void) ftw;
switch (type) {
case FTW_NS:
case FTW_DNR:
fprintf(stderr, "%s: ftw error: %s\n",
path, strerror(errno));
return 1;
case FTW_D:
// ignore directories at first, will be handled by FTW_DP
break;
case FTW_F:
case FTW_SL:
case FTW_SLN:
if (remove(path) != 0) {
fprintf(stderr, "Failed to remove %s: %s\n", path, strerror(errno));
return false;
}
break;
case FTW_DP:
if (rmdir(path) != 0) {
fprintf(stderr, "Failed to remove directory %s: %s\n", path, strerror(errno));
return false;
}
break;
default:
fprintf(stderr, "Unexpected fts_info\n");
return 1;
}
return 0;
};
bool rm_recursive(const char* const path) {
// FTW_DEPTH: perform depth-first search to make sure files are deleted before the containing directories
// FTW_MOUNT: prevent deletion of files on other mounted filesystems
// FTW_PHYS: do not follow symlinks, but report symlinks as such; this way, the symlink targets, which might point
// to locations outside path will not be deleted accidentally (attackers might abuse this)
int rv = nftw(path, &rm_recursive_callback, 0, FTW_DEPTH | FTW_MOUNT | FTW_PHYS);
return rv == 0;
}
void build_mount_point(char* mount_dir, const char* const argv0, const char* const temp_base, const size_t templen) {
const size_t maxnamelen = 6;
const size_t prefix_len = 8; // Length of "/.mount_"
const size_t suffix_len = 6; // Length of "XXXXXX"
// Create a modifiable copy of argv0
char argv0_copy[PATH_MAX]; // Ensure this is large enough for your use case
strncpy(argv0_copy, argv0, sizeof(argv0_copy) - 1);
argv0_copy[sizeof(argv0_copy) - 1] = '\0'; // Ensure null termination
char* path_basename = basename(argv0_copy);
size_t namelen = strlen(path_basename);
// Limit length of tempdir name
if (namelen > maxnamelen) {
namelen = maxnamelen;
}
// Ensure mount_dir is large enough before copying
snprintf(mount_dir, templen + prefix_len + namelen + suffix_len + 1, "%s/.mount_%.*sXXXXXX", temp_base, (int)namelen, path_basename);
}
int fusefs_main(int argc, char* argv[], void (* mounted)(void)) {
struct fuse_args args;
sqfs_opts opts;
#if FUSE_USE_VERSION >= 30
struct fuse_cmdline_opts fuse_cmdline_opts;