aboutsummaryrefslogtreecommitdiff
blob: 1f4cb9b5a1fa5e462351def4e20a1b0cf14be7f7 (plain)
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
#include "conf-update.h"

bool user_modified(char *file) {
	FILE *indexpipe, *filepipe;
	char *line = NULL;
	char *filedump = NULL;
	size_t len = 0, len2 = 0;
	char *md5sum;
	unsigned char filemd5[MD5_DIGEST_LENGTH];
	char hexdigest[32];
	bool user_mod = TRUE;
	if (access(MD5SUM_INDEX, R_OK) != 0) {
		return TRUE;
	} else {
		indexpipe = fopen(MD5SUM_INDEX, "r");
		exit_error(indexpipe, MD5SUM_INDEX);
		while (getline(&line, &len, indexpipe) != -1) {
			if (!strncmp(line, file, strlen(file)) && *(line + strlen(file)) == ' ') {
				md5sum = strrchr(line, ' ') + 1;
				filepipe = fopen(file, "r");
				exit_error(filepipe, file);
				if (getdelim(&filedump, &len2, EOF, filepipe) != -1) {
					MD5((unsigned char *)filedump, strlen(filedump), filemd5);
					md52hex(filemd5, hexdigest);
					if (!strncmp(md5sum, hexdigest, 32)) {
						user_mod = FALSE;
					}
				}
				fclose(filepipe);
				free(filedump);
			}
		}
		fclose(indexpipe);
		free(line);
		return user_mod;
	}
}

void md52hex(unsigned char *md5sum, char *hexdigest) {
	// this one is stolen from python's md5module.c
	char c;
	int i, j = 0;
	
	for(i=0; i<16; i++) {
		c = (md5sum[i] >> 4) & 0xf;
   		hexdigest[j] = (c>9) ? c+'a'-10 : c + '0';
   		j++;
		c = (md5sum[i] & 0xf);
		hexdigest[j] = (c>9) ? c+'a'-10 : c + '0';
		j++;
    } 
}

void calc_md5(char *file, char* hexdigest) {
	FILE *fp;
	char *dump = NULL;
	size_t len = 0;
	
	unsigned char md5sum[MD5_DIGEST_LENGTH];
	
	fp = fopen(file, "r");
	if (getdelim(&dump, &len, EOF, fp) != -1) {
		MD5((unsigned char *)dump, strlen(dump), md5sum);
		md52hex(md5sum, hexdigest);
		free(dump);
	}
	fclose(fp);
}

void md5sum_update(char *file, char *hexdigest) {
	FILE *oldpipe;
	char *dump = NULL;
	size_t len = 0;
	char *entry;

	oldpipe = fopen(MD5SUM_INDEX, "r");
	exit_error(oldpipe, MD5SUM_INDEX);
	
	if ((getdelim(&dump, &len, EOF, oldpipe) != -1) && (entry = strstr(dump, file))) {
		entry = strchr(entry, '\n') - 32;
		strncpy(entry, hexdigest, 32);
		exit_error(freopen(MD5SUM_INDEX, "w", oldpipe), MD5SUM_INDEX);
		exit_error(fwrite(dump, strlen(dump), sizeof(char), oldpipe), MD5SUM_INDEX);
	} else {
		// there's no entry at all yet
		exit_error(freopen(MD5SUM_INDEX, "a", oldpipe), MD5SUM_INDEX);
		exit_error(fwrite(file, strlen(file), sizeof(char), oldpipe), MD5SUM_INDEX);
		exit_error(fwrite(" ", strlen(" "), sizeof(char), oldpipe), MD5SUM_INDEX);
		exit_error(fwrite(hexdigest, 32, sizeof(char), oldpipe), MD5SUM_INDEX);
		exit_error(fwrite("\n", strlen("\n"), sizeof(char), oldpipe), MD5SUM_INDEX);
	}
	free(dump);
	fclose(oldpipe);
}