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)
53 die("Invalid configuration section, first item must be of type CT_SECTION");
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)
73 while(item && strcasecmp(item->name,sect))
75 if(!item) /* unknown section */
78 for(item++; item->type && strcasecmp(item->name,name); item++);
80 return item; /* item->type == 0 if not found */
83 byte *cf_set_item(byte *sect, byte *name, byte *value)
89 return "Empty section name";
90 item=cf_get_item(sect,name);
91 if(!item) /* ignore unknown section */
101 *((uns *) item->var) = strtoul(value, &end, 0);
103 msg = "Invalid number";
108 *((byte **) item->var) = cfg_stralloc(value);
111 msg = ((ci_func) item->var)(item, cfg_stralloc(value));
114 msg = "Unknown keyword";
121 static int cf_subread(byte *filename,int level)
125 byte def_section[BUFFER];
129 if(level>=MAX_LEVEL){
130 log(L_ERROR,"Too many (%d) nested files when reading %s",level,filename);
134 fd=open(filename,O_RDONLY, 0666);
136 log(L_ERROR,"Cannot open configuration file %s: %m",filename);
147 if(!bgets(b,buf,BUFFER))
152 while(c>buf && Cspace(c[-1]))
155 while(*c && Cspace(*c))
161 strcpy(def_section,c+1);
162 c=strchr(def_section,']');
166 msg="Garbage after ]";
175 byte *sect,*name,*value;
178 while(*c && !Cspace(*c))
180 while(*c && Cspace(*c))
184 if(!strcasecmp(name,"include")){
185 if(!cf_subread(value,level+1)){
186 msg="Included from here";
199 msg=cf_set_item(sect,name,value);
205 } /* for every line */
208 log(L_ERROR,"%s, line %d: %s",filename,line,msg);
213 void cf_read(byte *filename)
215 if(!cf_subread(filename,0))
216 die("Reading config file %s failed",filename);
220 int cf_getopt(int argc,char * const argv[],
221 const char *shortopts,const struct option *longopts,
227 res=getopt_long(argc,argv,shortopts,longopts,longindex);
229 byte *sect,*name,*value;
236 msg="Missing argument";
253 msg=cf_set_item(sect,name,value);
256 die("Invalid command line argument %s.%s=%s: %s",sect,name,value,msg);
261 /* unhandled option or end of options */