Merge branch 'debian'
[hcoop/debian/courier-authlib.git] / makedat / makedatprog.c
1 /*
2 ** Copyright 1998 - 1999 Double Precision, Inc.
3 ** See COPYING for distribution information.
4 */
5
6 #if HAVE_CONFIG_H
7 #include "config.h"
8 #endif
9 #if HAVE_UNISTD_H
10 #include <unistd.h>
11 #endif
12 #include <stdlib.h>
13 #include <string.h>
14 #include <stdio.h>
15 #include "dbobj.h"
16
17 static const char rcsid[]="$Id: makedatprog.c,v 1.4 1999/12/06 13:22:17 mrsam Exp $";
18
19 static int addgdbm(char *p, struct dbobj *o)
20 {
21 char *key, *val;
22
23 if (!*p || *p == '#')
24 return (0);
25
26 key=p;
27 if ( (val=strchr(p, '\t')) == 0) val="";
28 else *val++=0;
29
30 if (*key)
31 {
32 if (!*val) val="1";
33 if (dbobj_store(o, key, strlen(key), val, strlen(val), "I"))
34 {
35 fprintf(stderr, "Cannot store record for %s - duplicate or out of disk space.\n", key);
36 return (-1);
37 }
38 }
39 return (0);
40 }
41
42 static int buildgdbm(FILE *i, struct dbobj *o)
43 {
44 char *buf=0;
45 size_t bufsize, buflen;
46
47 bufsize=0;
48 buflen=0;
49
50 for (;;)
51 {
52 int c;
53
54 buflen=0;
55 for (;;)
56 {
57 if (buflen >= bufsize)
58 {
59 bufsize += 256;
60 buf= buf ? realloc(buf, bufsize):
61 malloc(bufsize);
62 if (!buf)
63 {
64 perror("malloc");
65 return (-1);
66 }
67 }
68 c=getc(i);
69 if (c == '\n' || c == EOF) break;
70 buf[buflen++]=c;
71 }
72 buf[buflen]=0;
73 if (c == EOF) return (-1);
74
75 if (strcmp(buf, ".") == 0) return (0);
76 if (addgdbm(buf, o)) return (-1);
77 }
78 }
79
80 int main(int argc, char **argv)
81 {
82 FILE *i;
83 struct dbobj obj;
84
85 if (argc < 4)
86 {
87 fprintf(stderr, "Usage: %s textfile tmpfile gdbmfile\n",
88 argv[0]);
89 exit(1);
90 }
91 if (strcmp(argv[1], "-") == 0)
92 i= stdin;
93 else
94 {
95 if ((i=fopen(argv[1], "r")) == 0)
96 {
97 perror(argv[1]);
98 exit(1);
99 }
100 }
101
102 dbobj_init(&obj);
103
104 if (dbobj_open(&obj, argv[2], "N"))
105 {
106 fprintf(stderr, "Cannot create %s\n", argv[2]);
107 exit (1);
108 }
109
110 if (buildgdbm(i, &obj))
111 {
112 dbobj_close(&obj);
113 unlink(argv[2]);
114 exit (1);
115 }
116
117 dbobj_close(&obj);
118
119 if (rename(argv[2], argv[3]))
120 {
121 perror("rename");
122 unlink(argv[2]);
123 exit(1);
124 }
125 exit(0);
126 return (0);
127 }