ctm_input.c revision 2926
1/*
2 * ----------------------------------------------------------------------------
3 * "THE BEER-WARE LICENSE" (Revision 42):
4 * <phk@login.dknet.dk> wrote this file.  As long as you retain this notice you
5 * can do whatever you want with this stuff. If we meet some day, and you think
6 * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
7 * ----------------------------------------------------------------------------
8 *
9 * $Id$
10 *
11 */
12
13#include "ctm.h"
14
15/*---------------------------------------------------------------------------*/
16char *
17String(char *s)
18{
19    char *p = malloc(strlen(s) + 1);
20    strcpy(p,s);
21    return p;
22}
23/*---------------------------------------------------------------------------*/
24void
25Fatal_(int ln, char *fn, char *kind)
26{
27    if(Verbose > 2)
28	fprintf(stderr,"Fatal error. (%s:%d)\n",fn,ln);
29    fprintf(stderr,"%s Fatal error: %s\n",FileName, kind);
30}
31#define Fatal(foo) Fatal_(__LINE__,__FILE__,foo)
32#define Assert() Fatal_(__LINE__,__FILE__,"Assert failed.")
33
34/*---------------------------------------------------------------------------*/
35/* get next field, check that the terminating whitespace is what we expect */
36u_char *
37Ffield(FILE *fd, MD5_CTX *ctx,u_char term)
38{
39    static u_char buf[BUFSIZ];
40    int i,l;
41
42    for(l=0;;) {
43	if((i=getc(fd)) == EOF) {
44	    Fatal("Truncated patch.");
45	    return 0;
46	}
47	buf[l++] = i;
48	if(isspace(i))
49	    break;
50	if(l >= sizeof buf) {
51	    Fatal("Corrupt patch.");
52	    printf("Token is too long.\n");
53	    return 0;
54	}
55    }
56    buf[l] = '\0';
57    MD5Update(ctx,buf,l);
58    if(buf[l-1] != term) {
59        Fatal("Corrupt patch.");
60	fprintf(stderr,"Expected \"%s\" but didn't find it.\n",
61	    term == '\n' ? "\\n" : " ");
62	return 0;
63    }
64    buf[--l] = '\0';
65    return buf;
66}
67
68int
69Fbytecnt(FILE *fd, MD5_CTX *ctx, u_char term)
70{
71    u_char *p,*q;
72    int u_chars;
73
74    p = Ffield(fd,ctx,term);
75    if(!p) return -1;
76    for(q=p;*q;q++)
77	if(!isdigit(*q)) {
78	    Fatal("Bytecount contains non-digit.");
79	    return -1;
80	}
81    u_chars=atoi(p);
82    if(u_chars > MAXSIZE) {
83	Fatal("Bytecount too large.");
84	return -1;
85    }
86    return u_chars;
87}
88
89u_char *
90Fdata(FILE *fd, int u_chars, MD5_CTX *ctx)
91{
92    u_char *p = Malloc(u_chars+1);
93
94    if(u_chars+1 != fread(p,1,u_chars+1,fd)) {
95	Fatal("Truncated patch.");
96	return 0;
97    }
98    MD5Update(ctx,p,u_chars+1);
99    if(p[u_chars] != '\n') {
100	if(Verbose > 3)
101	    printf("FileData wasn't followed by a newline.\n");
102        Fatal("Corrupt patch.");
103	return 0;
104    }
105    p[u_chars] = '\0';
106    return p;
107}
108