Deploy the new <ctype.h> and `foocmp' macros from mLib.
[catacomb] / progs / cc-hash.c
CommitLineData
18b3351a
MW
1/* -*-c-*-
2 *
3 * Common functions for hashing utilities
4 *
5 * (c) 2011 Straylight/Edgeware
6 */
7
8/*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of Catacomb.
11 *
12 * Catacomb is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Library General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
16 *
17 * Catacomb is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Library General Public License for more details.
21 *
22 * You should have received a copy of the GNU Library General Public
23 * License along with Catacomb; if not, write to the Free
24 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25 * MA 02111-1307, USA.
26 */
27
28/*----- Header files ------------------------------------------------------*/
29
30#define _FILE_OFFSET_BITS 64
31
32#include "config.h"
33
34#include <ctype.h>
f5e91c02 35#include <errno.h>
18b3351a
MW
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39
f5e91c02
MW
40#include <sys/types.h>
41#include <dirent.h>
42
43#include <mLib/alloc.h>
18b3351a 44#include <mLib/dstr.h>
141c1284 45#include <mLib/macros.h>
f5e91c02 46#include <mLib/report.h>
f377eee1 47#include <mLib/str.h>
18b3351a
MW
48
49#include <mLib/hex.h>
50#include <mLib/base32.h>
51#include <mLib/base64.h>
52
53#include "ghash.h"
54#include "cc.h"
55
56/*----- Encoding and decoding ---------------------------------------------*/
57
58/* --- Hex encoding --- */
59
60static void puthex(const octet *buf, size_t sz, FILE *fp)
61{
62 while (sz) {
63 fprintf(fp, "%02x", *buf++);
64 sz--;
65 }
66}
67
68static size_t gethex(const char *p, octet *q, size_t sz, char **pp)
69{
70 size_t i = 0;
141c1284 71 while (sz > 0 && ISXDIGIT(p[0]) && ISXDIGIT(p[1])) {
18b3351a
MW
72 char buf[3];
73 buf[0] = p[0];
74 buf[1] = p[1];
75 buf[2] = 0;
76 *q++ = strtoul(buf, 0, 16);
77 sz--;
78 p += 2;
79 i++;
80 }
81 if (pp)
82 *pp = (char *)p;
83 return (i);
84}
85
86/* --- Base64 encoding --- */
87
88static void putbase64(const octet *buf, size_t sz, FILE *fp)
89{
90 base64_ctx b;
91 dstr d = DSTR_INIT;
92
93 base64_init(&b);
94 b.indent = "";
95 b.maxline = 0;
96 base64_encode(&b, buf, sz, &d);
97 base64_encode(&b, 0, 0, &d);
98 dstr_write(&d, fp);
99 dstr_destroy(&d);
100}
101
102static size_t getbase64(const char *p, octet *q, size_t sz, char **pp)
103{
104 base64_ctx b;
105 dstr d = DSTR_INIT;
106 size_t n = strlen(p);
107
108 base64_init(&b);
109 base64_decode(&b, p, n, &d);
110 if (pp) *pp = (/*unconst*/ char *)p + n;
111 base64_decode(&b, 0, 0, &d);
112 assert(d.len <= sz);
113 memcpy(q, d.buf, sz);
114 n = d.len;
115 dstr_destroy(&d);
116 return (n);
117}
118
119/* --- Base32 encoding --- */
120
121static void putbase32(const octet *buf, size_t sz, FILE *fp)
122{
123 base32_ctx b;
124 dstr d = DSTR_INIT;
125
126 base32_init(&b);
127 b.indent = "";
128 b.maxline = 0;
129 base32_encode(&b, buf, sz, &d);
130 base32_encode(&b, 0, 0, &d);
131 dstr_write(&d, fp);
132 dstr_destroy(&d);
133}
134
135static size_t getbase32(const char *p, octet *q, size_t sz, char **pp)
136{
137 base32_ctx b;
138 dstr d = DSTR_INIT;
139 size_t n = strlen(p);
140
141 base32_init(&b);
142 base32_decode(&b, p, n, &d);
143 if (pp) *pp = (/*unconst*/ char *)p + n;
144 base32_decode(&b, 0, 0, &d);
145 assert(d.len <= sz);
146 memcpy(q, d.buf, sz);
147 n = d.len;
148 dstr_destroy(&d);
149 return (n);
150}
151
152/* --- Table --- */
153
154const encodeops encodingtab[] = {
155#define TAB(tag, name) { #name, put##name, get##name },
156 ENCODINGS(TAB)
157#undef TAB
158 { 0, 0, 0 }
159};
160
161const encodeops *getencoding(const char *ename)
162{
163 const encodeops *e;
164
165 for (e = encodingtab; e->name; e++) {
141c1284 166 if (STRCMP(ename, ==, e->name))
18b3351a
MW
167 return (e);
168 }
169 return (0);
170}
171
172/*----- File hashing ------------------------------------------------------*/
173
f5e91c02
MW
174enum {
175 FHETY_DIR,
176 FHETY_FILE
177};
178
179typedef struct fhent {
180 struct fhent *next;
181 unsigned ty;
182 struct fhent *sub;
183 char name[1];
184} fhdir;
185
f377eee1
MW
186/* --- @gethash@ --- *
187 *
188 * Arguments: @const char *name@ = pointer to name string
189 *
190 * Returns: Pointer to appropriate hash class.
191 *
192 * Use: Chooses a hash function by name.
193 */
194
195const gchash *gethash(const char *name)
196{
197 const gchash *const *g, *gg = 0;
198 size_t sz = strlen(name);
199 for (g = ghashtab; *g; g++) {
141c1284 200 if (STRNCMP(name, ==, (*g)->name, sz)) {
f377eee1
MW
201 if ((*g)->name[sz] == 0) {
202 gg = *g;
203 break;
204 } else if (gg)
205 return (0);
206 else
207 gg = *g;
208 }
209 }
210 return (gg);
211}
212
f5e91c02
MW
213/* --- @describefile@ --- *
214 *
215 * Arguments: @const struct stat *st@ = pointer to file state
216 *
217 * Returns: A snappy one-word description of the file.
218 */
219
220const char *describefile(const struct stat *st)
221{
222 switch (st->st_mode & S_IFMT) {
223 case S_IFBLK: return ("block-special");
224 case S_IFCHR: return ("char-special");
225 case S_IFIFO: return ("fifo");
226 case S_IFREG: return ("file");
227 case S_IFLNK: return ("symlink");
228 case S_IFDIR: return ("directory");
229 case S_IFSOCK: return ("socket");
230 default: return ("unknown");
231 }
232}
233
07290a45
MW
234/* --- @fhash_init@ ---*
235 *
236 * Arguments: @fhashstate *fh@ = pointer to fhash state to initialize
237 * @const gchash *gch@ = hash class to set
238 * @unsigned f@ initial flags to set
239 *
240 * Returns: ---
241 *
242 * Use: Initializes an @fhashstate@ structure.
243 */
244
245void fhash_init(fhashstate *fh, const gchash *gch, unsigned f)
f5e91c02 246 { fh->f = f; fh->gch = gch; fh->ents = 0; }
07290a45
MW
247
248/* --- @fhash_free@ --- *
249 *
250 * Arguments: @fhashstate *fh@ = pointer to fhash state to free
251 *
252 * Returns: ---
253 *
254 * Use: Frees an fhash state.
255 */
256
f5e91c02
MW
257static void freefhents(struct fhent *fhe)
258{
259 struct fhent *ffhe;
260
261 for (; fhe; fhe = ffhe) {
262 ffhe = fhe->next;
263 freefhents(fhe->sub);
264 xfree(fhe);
265 }
266}
267
268void fhash_free(fhashstate *fh)
269 { freefhents(fh->ents); }
07290a45 270
18b3351a
MW
271/* --- @fhash@ --- *
272 *
07290a45 273 * Arguments: @fhashstate *fh@ = pointer to fhash state
18b3351a
MW
274 * @const char *file@ = file name to be hashed (null for stdin)
275 * @void *buf@ = pointer to hash output buffer
276 *
277 * Returns: Zero if it worked, nonzero on error.
278 *
279 * Use: Hashes a file.
280 */
281
07290a45 282int fhash(fhashstate *fh, const char *file, void *buf)
18b3351a
MW
283{
284 FILE *fp;
285 char fbuf[1024 * 128];
286 size_t sz;
287 ghash *h;
288 int rc = 0;
f5e91c02
MW
289 struct fhent *fhe, **ffhe;
290 const char *p, *q;
291 size_t n;
18b3351a
MW
292 fprogress ff;
293
141c1284 294 if (!file || STRCMP(file, ==, "-"))
18b3351a 295 fp = stdin;
07290a45 296 else if ((fp = fopen(file, fh->f & FHF_BINARY ? "rb" : "r")) == 0)
18b3351a
MW
297 return (-1);
298
07290a45 299 if (fh->f & FHF_PROGRESS) {
95ccefe3 300 if (fprogress_init(&ff, file ? file : "<stdin>", fp)) return (-1);
18b3351a
MW
301 }
302
f5e91c02
MW
303 if (fh->f & FHF_JUNK) {
304 p = file;
141c1284 305 if (STRNCMP(p, ==, "./", 2)) p += 2;
f5e91c02
MW
306 q = p;
307 ffhe = &fh->ents;
308 for (;;) {
309 if (*q == '/' || *q == 0) {
310 n = q - p;
311 for (; *ffhe; ffhe = &(*ffhe)->next) {
312 fhe = *ffhe;
141c1284 313 if (STRNCMP(p, ==, fhe->name, n) && fhe->name[n] == 0)
f5e91c02
MW
314 goto found;
315 }
316 fhe = xmalloc(offsetof(struct fhent, name) + n + 1);
317 fhe->next = 0;
318 fhe->ty = *q == '/' ? FHETY_DIR : FHETY_FILE;
319 fhe->sub = 0;
320 *ffhe = fhe;
321 memcpy(fhe->name, p, n); fhe->name[n] = 0;
322 found:
323 if (!*q) break;
324 while (*++q == '/');
325 p = q;
326 ffhe = &fhe->sub;
327 } else
328 q++;
329 }
330 }
331
07290a45 332 h = GH_INIT(fh->gch);
18b3351a
MW
333 while ((sz = fread(fbuf, 1, sizeof(fbuf), fp)) > 0) {
334 GH_HASH(h, fbuf, sz);
07290a45 335 if (fh->f & FHF_PROGRESS) fprogress_update(&ff, sz);
18b3351a
MW
336 }
337 if (ferror(fp)) rc = -1;
338 if (fp != stdin) fclose(fp);
07290a45 339 if (fh->f & FHF_PROGRESS) fprogress_done(&ff);
18b3351a
MW
340 GH_DONE(h, buf);
341 GH_DESTROY(h);
342 return (rc);
343}
344
f5e91c02
MW
345/* --- @fhash_junk@ --- *
346 *
347 * Arguments: @fhashstate *fh@ = pointer to fhash state
348 * @void (*func)(const char *, const struct stat *, void *)@
349 * @void *p@ = pointer to pass to function
350 *
351 * Returns: Positive if any junk was found, negative on error, zero if
352 * everything was fine.
353 *
354 * Use: Reports junk files in any directories covered by the hash
355 * state.
356 */
357
358struct fhjunk {
359 int (*func)(const char *, const struct stat *, void *);
360 void *p;
361 dstr *d;
362};
363
364static int fhjunk(struct fhjunk *fhj, struct fhent *ents)
365{
366 DIR *dp;
367 int rc = 0, rrc;
368 struct stat st;
369 struct dirent *d;
370 const char *dname;
371 size_t n = fhj->d->len;
372 struct fhent *fhe;
373
374 dname = n ? fhj->d->buf : ".";
375 if ((dp = opendir(dname)) == 0) {
376 moan("failed to open directory `%s': %s", dname, strerror(errno));
377 rc = -1;
378 goto subs;
379 }
380 if (n) {
381 dstr_putc(fhj->d, '/');
382 n++;
383 }
384 while (errno = 0, (d = readdir(dp)) != 0) {
141c1284 385 if (STRCMP(d->d_name, ==, ".") || STRCMP(d->d_name, ==, ".."))
f5e91c02
MW
386 continue;
387 for (fhe = ents; fhe; fhe = fhe->next) {
141c1284 388 if (STRCMP(d->d_name, ==, fhe->name)) goto found;
f5e91c02
MW
389 }
390 fhj->d->len = n;
391 dstr_puts(fhj->d, d->d_name);
392 if (!lstat(fhj->d->buf, &st)) {
393 if (!rc) rc = 1;
394 rrc = fhj->func(fhj->d->buf, &st, fhj->p);
395 } else {
396 rc = -1;
397 rrc = fhj->func(fhj->d->buf, 0, fhj->p);
398 }
399 if (rrc < 0) rc = -1;
400 found:;
401 }
402 closedir(dp);
403 if (errno) {
404 moan("failed to read directory `%s': %s", dname, strerror(errno));
405 rc = -1;
406 }
407
408subs:
409 for (fhe = ents; fhe; fhe = fhe->next) {
410 if (fhe->ty == FHETY_DIR) {
411 fhj->d->len = n;
412 dstr_puts(fhj->d, fhe->name);
413 rrc = fhjunk(fhj, fhe->sub);
414 if (rrc < 0) rc = -1;
415 else if (!rc) rc = rrc;
416 }
417 }
418
419 return (rc);
420}
421
422int fhash_junk(fhashstate *fh,
423 int (*func)(const char *, const struct stat *, void *),
424 void *p)
425{
426 dstr d = DSTR_INIT;
427 struct fhjunk fhj;
428 int rc;
429
430 fhj.func = func;
431 fhj.p = p;
432 fhj.d = &d;
433 rc = fhjunk(&fhj, fh->ents);
434 dstr_destroy(&d);
435 return (rc);
436}
437
f377eee1
MW
438/* --- @hfparse@ --- *
439 *
440 * Arguments: @hfpctx *hfp@ = pointer to the context structure
441 *
442 * Returns: A code indicating what happened.
443 *
444 * Use: Parses a line from the input file.
445 */
446
447int hfparse(hfpctx *hfp)
448{
449 char *p, *q;
450 const gchash *gch;
451 const encodeops *ee;
452 dstr *d = hfp->dline;
453 size_t hsz;
454
455 /* --- Fetch the input line and get ready to parse --- */
456
457 DRESET(d);
458 if (dstr_putline(d, hfp->fp) == EOF) return (HF_EOF);
459 p = d->buf;
460
461 /* --- Parse magic comments --- */
462
463 if (*p == '#') {
464 p++;
465 if ((q = str_getword(&p)) == 0) return (HF_BAD);
141c1284 466 if (STRCMP(q, ==, "hash")) {
f377eee1
MW
467 if ((q = str_getword(&p)) == 0) return (HF_BAD);
468 if ((gch = gethash(q)) == 0) return (HF_BAD);
469 hfp->gch = gch;
470 return (HF_HASH);
141c1284 471 } else if (STRCMP(q, ==, "encoding")) {
f377eee1
MW
472 if ((q = str_getword(&p)) == 0) return (HF_BAD);
473 if ((ee = getencoding(q)) == 0) return (HF_BAD);
474 hfp->ee = ee;
475 return (HF_ENC);
141c1284 476 } else if (STRCMP(q, ==, "escape")) {
f377eee1
MW
477 hfp->f |= HFF_ESCAPE;
478 return (HF_ESC);
479 }
480 return (HF_BAD);
481 }
482
483 /* --- Otherwise it's a file line --- */
484
485 q = p;
486 while (*p && *p != ' ') p++;
487 if (!*p) return (HF_BAD);
488 *p++ = 0;
489 hsz = hfp->gch->hashsz;
490 if (hfp->ee->get(q, hfp->hbuf, hsz, 0) < hsz) return (HF_BAD);
491 switch (*p) {
492 case '*': hfp->f |= FHF_BINARY; break;
493 case ' ': hfp->f &= ~FHF_BINARY; break;
494 default: return (HF_BAD);
495 }
496 p++;
497
498 DRESET(hfp->dfile);
499 if (hfp->f & HFF_ESCAPE)
500 getstring(&p, hfp->dfile, GSF_STRING);
501 else {
502 dstr_putm(hfp->dfile, p, d->len - (p - d->buf));
503 dstr_putz(hfp->dfile);
504 }
505
506 return (HF_FILE);
507}
508
18b3351a
MW
509/*----- String I/O --------------------------------------------------------*/
510
511/* --- @getstring@ --- *
512 *
513 * Arguments: @void *in@ = input source
514 * @dstr *d@ = destination string
515 * @unsigned f@ = input flags
516 *
517 * Returns: Zero if OK, nonzero on end-of-file.
518 *
519 * Use: Reads a filename (or something similar) from a stream.
520 */
521
522static int nextch_file(void *in)
523 { FILE *fp = in; return (getc(fp)); }
524
525static int nextch_string(void *in)
526 { const unsigned char **p = in; return (*(*p)++); }
527
528int getstring(void *in, dstr *d, unsigned f)
529{
530 int ch;
531 int eofch = (f & GSF_STRING) ? 0 : EOF;
532 int (*nextch)(void *) = (f & GSF_STRING) ? nextch_string : nextch_file;
533 int q = 0;
534
535 /* --- Raw: just read exactly what's written up to a null byte --- */
536
537 if (f & GSF_RAW) {
538 if ((ch = nextch(in)) == eofch)
539 return (EOF);
540 for (;;) {
541 if (!ch)
542 break;
543 DPUTC(d, ch);
544 if ((ch = nextch(in)) == eofch)
545 break;
546 }
547 DPUTZ(d);
548 return (0);
549 }
550
551 /* --- Skip as far as whitespace --- *
552 *
553 * Also skip past comments.
554 */
555
556again:
557 ch = nextch(in);
141c1284 558 while (ISSPACE(ch))
18b3351a
MW
559 ch = nextch(in);
560 if (ch == '#') {
561 do ch = nextch(in); while (ch != '\n' && ch != eofch);
562 goto again;
563 }
564 if (ch == eofch)
565 return (EOF);
566
567 /* --- If the character is a quote then read a quoted string --- */
568
569 switch (ch) {
570 case '`':
571 ch = '\'';
572 case '\'':
573 case '\"':
574 q = ch;
575 ch = nextch(in);
576 break;
577 }
578
579 /* --- Now read all sorts of interesting things --- */
580
581 for (;;) {
582
583 /* --- Handle an escaped thing --- */
584
585 if (ch == '\\') {
586 ch = nextch(in);
587 if (ch == eofch)
588 break;
589 switch (ch) {
590 case 'a': ch = '\a'; break;
591 case 'b': ch = '\b'; break;
592 case 'f': ch = '\f'; break;
593 case 'n': ch = '\n'; break;
594 case 'r': ch = '\r'; break;
595 case 't': ch = '\t'; break;
596 case 'v': ch = '\v'; break;
597 }
598 DPUTC(d, ch);
599 ch = nextch(in);
600 continue;
601 }
602
603 /* --- If it's a quote or some other end marker then stop --- */
604
605 if (ch == q)
606 break;
141c1284 607 if (!q && ISSPACE(ch))
18b3351a
MW
608 break;
609
610 /* --- Otherwise contribute and continue --- */
611
612 DPUTC(d, ch);
613 if ((ch = nextch(in)) == eofch)
614 break;
615 }
616
617 /* --- Done --- */
618
619 DPUTZ(d);
620 return (0);
621}
622
623/* --- @putstring@ --- *
624 *
625 * Arguments: @FILE *fp@ = stream to write on
626 * @const char *p@ = pointer to text
627 * @unsigned f@ = output flags
628 *
629 * Returns: ---
630 *
631 * Use: Emits a string to a stream.
632 */
633
634void putstring(FILE *fp, const char *p, unsigned f)
635{
636 size_t sz = strlen(p);
637 unsigned qq;
638 const char *q;
639
640 /* --- Just write the string null terminated if raw --- */
641
642 if (f & GSF_RAW) {
643 fwrite(p, 1, sz + 1, fp);
644 return;
645 }
646
647 /* --- Check for any dodgy characters --- */
648
649 qq = 0;
650 for (q = p; *q; q++) {
141c1284 651 if (ISSPACE(*q)) {
18b3351a
MW
652 qq = '\"';
653 break;
654 }
655 }
656
657 if (qq)
658 putc(qq, fp);
659
660 /* --- Emit the string --- */
661
662 for (q = p; *q; q++) {
663 switch (*q) {
664 case '\a': fputc('\\', fp); fputc('a', fp); break;
665 case '\b': fputc('\\', fp); fputc('b', fp); break;
666 case '\f': fputc('\\', fp); fputc('f', fp); break;
667 case '\n': fputc('\\', fp); fputc('n', fp); break;
668 case '\r': fputc('\\', fp); fputc('r', fp); break;
669 case '\t': fputc('\\', fp); fputc('t', fp); break;
670 case '\v': fputc('\\', fp); fputc('v', fp); break;
671 case '`': fputc('\\', fp); fputc('`', fp); break;
672 case '\'': fputc('\\', fp); fputc('\'', fp); break;
673 case '\"': fputc('\\', fp); fputc('\"', fp); break;
674 default:
675 putc(*q, fp);
676 break;
677 }
678 }
679
680 /* --- Done --- */
681
682 if (qq)
683 putc(qq, fp);
684}
685
686/*----- That's all, folks -------------------------------------------------*/