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; sect->type; sect++)
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)
88 item=cf_get_item(sect,name);
89 if(!item) /* ignore unknown section */
99 *((uns *) item->var) = strtoul(value, &end, 0);
101 msg = "Invalid number";
106 *((byte **) item->var) = cfg_stralloc(value);
109 msg = ((ci_func) item->var)(item, cfg_stralloc(value));
112 msg = "Unknown keyword";
119 static int cf_subread(byte *filename,int level)
123 byte def_section[BUFFER];
127 if(level>=MAX_LEVEL){
128 log(L_ERROR,"Too many (%d) nested files when reading %s",level,filename);
132 fd=open(filename,O_RDONLY, 0666);
134 log(L_ERROR,"Cannot open configuration file %s: %m",filename);
145 if(!bgets(b,buf,BUFFER))
150 while(c>buf && Cspace(c[-1]))
153 while(*c && Cspace(*c))
159 strcpy(def_section,c+1);
160 c=strchr(def_section,']');
164 msg="Garbage after ]";
173 byte *sect,*name,*value;
176 while(*c && !Cspace(*c))
178 while(*c && Cspace(*c))
182 if(!strcasecmp(name,"include")){
183 if(!cf_subread(value,level+1)){
184 msg="Included from here";
197 msg=cf_set_item(sect,name,value);
203 } /* for every line */
206 log(L_ERROR,"%s, line %d: %s",filename,line,msg);
211 void cf_read(byte *filename)
213 if(!cf_subread(filename,0))
214 die("Reading config file %s failed",filename);
218 int cf_getopt(int argc,char * const argv[],
219 const char *shortopts,const struct option *longopts,
225 res=getopt_long(argc,argv,shortopts,longopts,longindex);
227 byte *sect,*name,*value;
234 msg="Missing argument";
251 msg=cf_set_item(sect,name,value);
254 die("Invalid command line argument %s.%s=%s: %s",sect,name,value,msg);
262 }else{ /* unhandled option */