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 byte *cf_set_item(byte *sect, byte *name, byte *value)
62 while(item && strcasecmp(item->name,sect))
64 if(!item) /* ignore unknown section */
67 for(item++; item->type && strcasecmp(item->name,name); item++);
76 *((uns *) item->var) = strtoul(value, &end, 0);
78 msg = "Invalid number";
83 *((byte **) item->var) = cfg_stralloc(value);
86 msg = ((ci_func) item->var)(item, cfg_stralloc(value));
89 msg = "Unknown keyword";
96 static int cf_subread(byte *filename,int level)
100 byte def_section[BUFFER];
104 if(level>=MAX_LEVEL){
105 log(L_ERROR,"Too many (%d) nested files when reading %s",level,filename);
109 fd=open(filename,O_RDONLY, 0666);
111 log(L_ERROR,"Cannot open configuration file %s: %m",filename);
122 if(!bgets(b,buf,BUFFER))
127 while(c>buf && Cspace(c[-1]))
130 while(*c && Cspace(*c))
136 strcpy(def_section,c+1);
137 c=strchr(def_section,']');
141 msg="Garbage after ]";
150 byte *sect,*name,*value;
153 while(*c && !Cspace(*c))
155 while(*c && Cspace(*c))
159 if(!strcasecmp(name,"include")){
160 if(!cf_subread(value,level+1)){
161 msg="Included from here";
174 msg=cf_set_item(sect,name,value);
180 } /* for every line */
183 log(L_ERROR,"%s, line %d: %s",filename,line,msg);
188 void cf_read(byte *filename)
190 if(!cf_subread(filename,0))
191 die("Reading config file %s failed",filename);
194 int cf_getopt(int argc,char * const argv[],
195 const char *shortopts,const struct option *longopts,
201 res=getopt_long(argc,argv,shortopts,longopts,longindex);
203 byte *sect,*name,*value;
210 msg="Missing argument";
225 msg=cf_set_item(sect,name,value);
228 die("Invalid command line argument %s.%s=%s: %s",sect,name,value,msg);
232 }else{ /* unhandled option */