2 * Sherlock Library -- Reading configuration files
4 * (c) 2001 Robert Spalek <robert@ucw.cz>
15 #include "lib/chartype.h"
16 #include "lib/fastbuf.h"
17 #include "lib/pools.h"
24 static struct cfitem *cfsection;
25 static struct mempool *cfpool;
27 byte *cfdeffile = DEFAULT_CONFIG;
29 static void CONSTRUCTOR
32 cfpool = mp_new(4096);
38 return mp_alloc(cfpool, size);
45 byte *k = cfg_malloc(l + 1);
50 void cf_register(struct cfitem *items)
52 if(items[0].type!=CT_SECTION && items[0].type!=CT_INCOMPLETE_SECTION)
53 die("cf_register: Invalid section type");
54 items[0].var=cfsection;
58 int cf_item_count(void)
60 struct cfitem *sect, *item;
62 for (sect = cfsection; sect; sect = sect->var)
63 for (item = sect+1; item->type; item++)
68 struct cfitem *cf_get_item(byte *sect, byte *name)
70 struct cfitem *item, *section;
73 while(item && strcasecmp(item->name,sect))
75 if(!item) /* unknown section */
79 for(item++; item->type && strcasecmp(item->name,name); item++);
80 if (!item->type && section->type == CT_INCOMPLETE_SECTION)
83 return item; /* item->type == 0 if not found */
86 byte *cf_set_item(byte *sect, byte *name, byte *value)
92 return "Empty section name";
93 item=cf_get_item(sect,name);
94 if(!item) /* ignore unknown section */
102 msg="Missing number";
104 *((uns *) item->var) = strtoul(value, &end, 0);
106 msg = "Invalid number";
111 *((byte **) item->var) = cfg_stralloc(value);
114 msg = ((ci_func) item->var)(item, cfg_stralloc(value));
117 msg = "Unknown keyword";
124 static int cf_subread(byte *filename,int level)
128 byte def_section[BUFFER];
132 if(level>=MAX_LEVEL){
133 log(L_ERROR,"Too many (%d) nested files when reading %s",level,filename);
137 fd=open(filename,O_RDONLY, 0666);
139 log(L_ERROR,"Cannot open configuration file %s: %m",filename);
150 if(!bgets(b,buf,BUFFER))
155 while(c>buf && Cspace(c[-1]))
158 while(*c && Cspace(*c))
164 strcpy(def_section,c+1);
165 c=strchr(def_section,']');
169 msg="Garbage after ]";
178 byte *sect,*name,*value;
181 while(*c && !Cspace(*c))
183 while(*c && Cspace(*c))
187 if(!strcasecmp(name,"include")){
188 if(!cf_subread(value,level+1)){
189 msg="Included from here";
202 msg=cf_set_item(sect,name,value);
208 } /* for every line */
211 log(L_ERROR,"%s, line %d: %s",filename,line,msg);
216 void cf_read(byte *filename)
218 if(!cf_subread(filename,0))
219 die("Reading config file %s failed",filename);
223 int cf_getopt(int argc,char * const argv[],
224 const char *shortopts,const struct option *longopts,
230 res=getopt_long(argc,argv,shortopts,longopts,longindex);
232 byte *sect,*name,*value;
239 msg="Missing argument";
256 msg=cf_set_item(sect,name,value);
259 die("Invalid command line argument %s.%s=%s: %s",sect,name,value,msg);
264 /* unhandled option or end of options */