Merge branch 'master' into zaoqi-patch-1
[appimagekit.git] / src / digest_md5.c
blob5285f20b540e23761f65bd23feb7f8bfe381c79e
1 #include <glib.h>
2 #include <stdio.h>
3 #include <stdlib.h>
5 #include "appimage/appimage_shared.h"
6 #include "getsection.h"
9 bool compare_byte_buffers(const char* buf1, const char* buf2, size_t num_bytes) {
10 for (size_t i = 0; i < num_bytes; i++) {
11 if (buf1[i] != buf2[i]) {
12 return false;
16 return true;
20 int main(int argc, char* argv[]) {
21 if (argc != 2) {
22 printf("Usage: %s <my.AppImage>\n", argv[0]);
23 printf("\n");
24 printf("Calculate AppImage MD5 digest, and compare it to embedded value (if available)\n");
27 const char* fname = argv[1];
28 if (!g_file_test(fname, G_FILE_TEST_IS_REGULAR)) {
29 fprintf(stderr, "No such file or directory: %s\n", fname);
30 return 1;
33 static const int digest_size = 16;
35 // first, calculate MD5 digest using algorithm in libappimage
36 char expected_digest[digest_size];
38 if (!appimage_type2_digest_md5(fname, expected_digest)) {
39 fprintf(stderr, "Could not calculate MD5 digest\n");
40 return 1;
43 // print hex encoded digest
44 char* hexlified_expected_digest = appimage_hexlify(expected_digest, digest_size);
45 printf("calculated: %s\n", hexlified_expected_digest);
46 free(hexlified_expected_digest);
48 unsigned long offset = 0, length = 0;
50 static const char section_name[] = ".digest_md5";
52 if (!appimage_get_elf_section_offset_and_length(fname, section_name, &offset, &length) || offset == 0 || length == 0) {
53 fprintf(stderr, "Could not find %s section in file\n", section_name);
54 return 1;
57 if (length < digest_size) {
58 fprintf(stderr,
59 "Invalid section length for section %s: expected %d bytes, found %lu bytes\n",
60 section_name, digest_size, length
62 return 1;
65 char embedded_digest[digest_size];
66 FILE* fp = fopen(fname, "r");
68 if (fp == NULL) {
69 fprintf(stderr, "Failed to open AppImage for writing");
70 return 1;
73 if (fseek(fp, offset, SEEK_SET) != 0) {
74 fprintf(stderr, "Failed to read embedded digest: failed to seek to offset\n");
75 fclose(fp);
76 return 1;
79 if (fread(embedded_digest, sizeof(char), digest_size, fp) != digest_size) {
80 fprintf(stderr, "Failed to read embedded digest: read invalid amount of bytes from file\n");
81 fclose(fp);
82 return 1;
85 fclose(fp);
87 char* hexlified_embedded_digest = appimage_hexlify(embedded_digest, digest_size);
88 printf(" embedded: %s\n", hexlified_embedded_digest);
89 free(hexlified_embedded_digest);
91 if (compare_byte_buffers(expected_digest, embedded_digest, digest_size)) {
92 printf("Digests match\n");
93 return 0;
94 } else {
95 printf("Digests don't match!");
96 return 1;