Replace boost::scoped_ptr with std::unique_ptr.
[cumulus.git] / hash.cc
1 /* Cumulus: Smart Filesystem Backup to Dumb Servers
2  *
3  * Copyright (C) 2012  Michael Vrable <vrable@cs.hmc.edu>
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 2 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 along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19
20 #include <stdio.h>
21 #include <stdint.h>
22 #include <map>
23 #include <string>
24
25 #include "hash.h"
26
27 using std::map;
28 using std::string;
29
30 static string default_algorithm;
31 static map<string, Hash *(*)()> hash_registry;
32
33 void Hash::Register(const std::string& name, Hash *(*constructor)())
34 {
35     hash_registry.insert(make_pair(name, constructor));
36 }
37
38 Hash *Hash::New()
39 {
40     return New(default_algorithm);
41 }
42
43 Hash *Hash::New(const std::string& name)
44 {
45     Hash *(*constructor)() = hash_registry[name];
46     if (!constructor)
47         return NULL;
48     else
49         return constructor();
50 }
51
52 std::string Hash::hash_file(const char *filename)
53 {
54     string result;
55     Hash *hash = Hash::New();
56     if (hash->update_from_file(filename))
57         result = hash->digest_str();
58
59     delete hash;
60     return result;
61 }
62
63 bool Hash::update_from_file(const char *filename)
64 {
65     FILE *f = fopen(filename, "rb");
66     if (f == NULL)
67         return false;
68
69     while (!feof(f)) {
70         char buf[4096];
71         size_t bytes = fread(buf, 1, sizeof(buf), f);
72
73         if (ferror(f)) {
74             fclose(f);
75             return false;
76         }
77
78         update(buf, bytes);
79     }
80
81     fclose(f);
82     return true;
83 }
84
85 const uint8_t *Hash::digest()
86 {
87     if (!digest_bytes) {
88         digest_bytes = finalize();
89     }
90
91     return digest_bytes;
92 }
93
94 string Hash::digest_str()
95 {
96     const uint8_t *raw_digest = digest();
97     size_t len = digest_size();
98     char hexbuf[len*2 + 1];
99
100     hexbuf[0] = '\0';
101     for (size_t i = 0; i < len; i++) {
102         snprintf(&hexbuf[2*i], 3, "%02x", raw_digest[i]);
103     }
104
105     return name() + "=" + hexbuf;
106 }
107
108 void sha1_register();
109 void sha256_register();
110
111 void hash_init()
112 {
113     sha1_register();
114     sha256_register();
115     default_algorithm = "sha224";
116 }