9base

revived minimalist port of Plan 9 userland to Unix
git clone git://git.suckless.org/9base
Log | Files | Refs | README | LICENSE

sha1sum.c (982B)


      1 #include <u.h>
      2 #include <libc.h>
      3 #include <bio.h>
      4 #include <libsec.h>
      5 
      6 static int
      7 digestfmt(Fmt *fmt)
      8 {
      9 	char buf[SHA1dlen*2+1];
     10 	uchar *p;
     11 	int i;
     12 
     13 	p = va_arg(fmt->args, uchar*);
     14 	for(i=0; i<SHA1dlen; i++)
     15 		sprint(buf+2*i, "%.2x", p[i]);
     16 	return fmtstrcpy(fmt, buf);
     17 }
     18 
     19 static void
     20 sum(int fd, char *name)
     21 {
     22 	int n;
     23 	uchar buf[8192], digest[SHA1dlen];
     24 	DigestState *s;
     25 
     26 	s = sha1(nil, 0, nil, nil);
     27 	while((n = read(fd, buf, sizeof buf)) > 0)
     28 		sha1(buf, n, nil, s);
     29 	sha1(nil, 0, digest, s);
     30 	if(name == nil)
     31 		print("%M\n", digest);
     32 	else
     33 		print("%M\t%s\n", digest, name);
     34 }
     35 
     36 void
     37 main(int argc, char *argv[])
     38 {
     39 	int i, fd;
     40 
     41 	ARGBEGIN{
     42 	default:
     43 		fprint(2, "usage: sha1sum [file...]\n");
     44 		exits("usage");
     45 	}ARGEND
     46 
     47 	fmtinstall('M', digestfmt);
     48 
     49 	if(argc == 0)
     50 		sum(0, nil);
     51 	else for(i = 0; i < argc; i++){
     52 		fd = open(argv[i], OREAD);
     53 		if(fd < 0){
     54 			fprint(2, "sha1sum: can't open %s: %r\n", argv[i]);
     55 			continue;
     56 		}
     57 		sum(fd, argv[i]);
     58 		close(fd);
     59 	}
     60 	exits(nil);
     61 }