common.c (2014B)
1 #include "cli/common.h" 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 7 #ifndef VERSION 8 #define VERSION "n/a" 9 #endif 10 11 long fremaining(FILE *fd) { 12 long current = ftell(fd); 13 fseek(fd, 0, SEEK_END); 14 long end = ftell(fd); 15 fseek(fd, current, SEEK_SET); 16 return end - current; 17 } 18 19 struct Format *supercop_find_format(const char *name) { 20 struct Format *fmt = supercop_formats; 21 if (!name) return NULL; 22 while (fmt) { 23 if (fmt->name && strcmp(fmt->name, name) == 0) return fmt; 24 fmt = fmt->next; 25 } 26 return NULL; 27 } 28 29 struct KeyPair *readKeyFile(const char *filename) { 30 struct Format *fmt = supercop_formats; 31 FILE *fd = fopen(filename, "r"); 32 unsigned char *buf; 33 struct KeyPair *kp; 34 35 if (!fd) { 36 fprintf(stderr, "Could not open key file\n"); 37 exit(1); 38 } 39 40 // Read whole file 41 long fsize = fremaining(fd); 42 buf = calloc(1, fsize + 1); 43 fread(buf, 1, fsize, fd); 44 45 // Auto-detect format 46 while(fmt) { 47 if (!fmt->detect(buf, fsize)) { 48 fmt = fmt->next; 49 continue; 50 } 51 kp = fmt->decode(buf, fsize); 52 if (!kp) { 53 fmt = fmt->next; 54 continue; 55 } 56 free(buf); 57 fclose(fd); 58 return kp; 59 } 60 61 free(buf); 62 fclose(fd); 63 return NULL; 64 } 65 66 FILE *supercop_open_message(const char *message, const char *messageFile) { 67 FILE *fmessage = stdin; 68 69 if (message) { 70 fmessage = tmpfile(); 71 fwrite(message, 1, strlen(message), fmessage); 72 fseek(fmessage, 0, SEEK_SET); 73 } 74 75 if (messageFile) { 76 if (message) fclose(fmessage); 77 fmessage = fopen(messageFile, "r"); 78 if (!fmessage) { 79 fprintf(stderr, "Could not open message file\n"); 80 exit(1); 81 } 82 } 83 84 return fmessage; 85 } 86 87 FILE *supercop_parse_signature(const char *hex) { 88 FILE *fsignature = tmpfile(); 89 const char *pos = hex; 90 unsigned char c; 91 92 while(*pos) { 93 sscanf(pos, "%2hhx", &c); 94 fputc(c, fsignature); 95 pos += 2; 96 } 97 fseek(fsignature, 0, SEEK_SET); 98 99 return fsignature; 100 } 101 102 void print_version(void) { 103 fprintf(stdout, "%s\n", VERSION); 104 }