]> git.notmuchmail.org Git - notmuch/blob - sha1.c
Generate message ID (using SHA1) when a mail message contains none.
[notmuch] / sha1.c
1 /* sha1.c - Interfaces to SHA-1 hash for the notmuch mail system
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see http://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-private.h"
22
23 #include "libsha1.h"
24
25 /* Just some simple interfaces on top of libsha1 so that we can leave
26  * libsha1 as untouched as possible. */
27
28 char *
29 notmuch_sha1_of_file (const char *filename)
30 {
31     FILE *file;
32 #define BLOCK_SIZE 4096
33     unsigned char block[BLOCK_SIZE];
34     size_t bytes_read;
35     sha1_ctx sha1;
36     unsigned char digest[SHA1_DIGEST_SIZE];
37     char *result, *r;
38     int i;
39
40     file = fopen (filename, "r");
41     if (file == NULL)
42         return NULL;
43
44     sha1_begin (&sha1);
45
46     while (1) {
47         bytes_read = fread (block, 1, 4096, file);
48         if (bytes_read == 0) {
49             if (feof (file)) {
50                 break;
51             } else if (ferror (file)) {
52                 fclose (file);
53                 return NULL;
54             }
55         } else {
56             sha1_hash (block, bytes_read, &sha1);
57         }
58     }
59
60     sha1_end (digest, &sha1);
61
62     result = calloc (SHA1_DIGEST_SIZE * 2 + 1, 1);
63     if (result == NULL)
64         return NULL;
65
66     for (r = result, i = 0;
67          i < SHA1_DIGEST_SIZE;
68          r += 2, i++)
69     {
70         sprintf (r, "%02x", digest[i]);
71     }
72
73     fclose (file);
74
75     return result;
76 }
77