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 static void CONSTRUCTOR
30 cfpool = mp_new(4096);
36 return mp_alloc(cfpool, size);
43 byte *k = cfg_malloc(l + 1);
48 void cf_register(struct cfitem *items)
50 if(items[0].type!=CT_SECTION)
51 die("Invalid configuration section, first item must be of type CT_SECTION");
52 items[0].var=cfsection;
56 struct cfitem *cf_get_item(byte *sect, byte *name)
61 while(item && strcasecmp(item->name,sect))
63 if(!item) /* unknown section */
66 for(item++; item->type && strcasecmp(item->name,name); item++);
68 return item; /* item->type == 0 if not found */
71 byte *cf_set_item(byte *sect, byte *name, byte *value)
76 item=cf_get_item(sect,name);
77 if(!item) /* ignore unknown section */
87 *((uns *) item->var) = strtoul(value, &end, 0);
89 msg = "Invalid number";
94 *((byte **) item->var) = cfg_stralloc(value);
97 msg = ((ci_func) item->var)(item, cfg_stralloc(value));
100 msg = "Unknown keyword";
107 static int cf_subread(byte *filename,int level)
111 byte def_section[BUFFER];
115 if(level>=MAX_LEVEL){
116 log(L_ERROR,"Too many (%d) nested files when reading %s",level,filename);
120 fd=open(filename,O_RDONLY, 0666);
122 log(L_ERROR,"Cannot open configuration file %s: %m",filename);
133 if(!bgets(b,buf,BUFFER))
138 while(c>buf && Cspace(c[-1]))
141 while(*c && Cspace(*c))
147 strcpy(def_section,c+1);
148 c=strchr(def_section,']');
152 msg="Garbage after ]";
161 byte *sect,*name,*value;
164 while(*c && !Cspace(*c))
166 while(*c && Cspace(*c))
170 if(!strcasecmp(name,"include")){
171 if(!cf_subread(value,level+1)){
172 msg="Included from here";
185 msg=cf_set_item(sect,name,value);
191 } /* for every line */
194 log(L_ERROR,"%s, line %d: %s",filename,line,msg);
199 void cf_read(byte *filename)
201 if(!cf_subread(filename,0))
202 die("Reading config file %s failed",filename);
205 int cf_getopt(int argc,char * const argv[],
206 const char *shortopts,const struct option *longopts,
212 res=getopt_long(argc,argv,shortopts,longopts,longindex);
214 byte *sect,*name,*value;
221 msg="Missing argument";
236 msg=cf_set_item(sect,name,value);
239 die("Invalid command line argument %s.%s=%s: %s",sect,name,value,msg);
243 }else{ /* unhandled option */