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 int cf_item_count(void)
58 struct cfitem *sect, *item;
60 for (sect = cfsection; sect; sect = sect->var)
61 for (item = sect+1; sect->type; sect++)
66 struct cfitem *cf_get_item(byte *sect, byte *name)
71 while(item && strcasecmp(item->name,sect))
73 if(!item) /* unknown section */
76 for(item++; item->type && strcasecmp(item->name,name); item++);
78 return item; /* item->type == 0 if not found */
81 byte *cf_set_item(byte *sect, byte *name, byte *value)
86 item=cf_get_item(sect,name);
87 if(!item) /* ignore unknown section */
97 *((uns *) item->var) = strtoul(value, &end, 0);
99 msg = "Invalid number";
104 *((byte **) item->var) = cfg_stralloc(value);
107 msg = ((ci_func) item->var)(item, cfg_stralloc(value));
110 msg = "Unknown keyword";
117 static int cf_subread(byte *filename,int level)
121 byte def_section[BUFFER];
125 if(level>=MAX_LEVEL){
126 log(L_ERROR,"Too many (%d) nested files when reading %s",level,filename);
130 fd=open(filename,O_RDONLY, 0666);
132 log(L_ERROR,"Cannot open configuration file %s: %m",filename);
143 if(!bgets(b,buf,BUFFER))
148 while(c>buf && Cspace(c[-1]))
151 while(*c && Cspace(*c))
157 strcpy(def_section,c+1);
158 c=strchr(def_section,']');
162 msg="Garbage after ]";
171 byte *sect,*name,*value;
174 while(*c && !Cspace(*c))
176 while(*c && Cspace(*c))
180 if(!strcasecmp(name,"include")){
181 if(!cf_subread(value,level+1)){
182 msg="Included from here";
195 msg=cf_set_item(sect,name,value);
201 } /* for every line */
204 log(L_ERROR,"%s, line %d: %s",filename,line,msg);
209 void cf_read(byte *filename)
211 if(!cf_subread(filename,0))
212 die("Reading config file %s failed",filename);
215 int cf_getopt(int argc,char * const argv[],
216 const char *shortopts,const struct option *longopts,
222 res=getopt_long(argc,argv,shortopts,longopts,longindex);
224 byte *sect,*name,*value;
231 msg="Missing argument";
246 msg=cf_set_item(sect,name,value);
249 die("Invalid command line argument %s.%s=%s: %s",sect,name,value,msg);
253 }else{ /* unhandled option */