ciniparser.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /* Copyright (c) 2000-2007 by Nicolas Devillard.
  2. * Copyright (x) 2009 by Tim Post <tinkertim@gmail.com>
  3. * MIT License
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a
  6. * copy of this software and associated documentation files (the "Software"),
  7. * to deal in the Software without restriction, including without limitation
  8. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. * and/or sell copies of the Software, and to permit persons to whom the
  10. * Software is furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  21. * DEALINGS IN THE SOFTWARE.
  22. */
  23. /** @addtogroup ciniparser
  24. * @{
  25. */
  26. /**
  27. * @file ciniparser.c
  28. * @author N. Devillard
  29. * @date Sep 2007
  30. * @version 3.0
  31. * @brief Parser for ini files.
  32. */
  33. #include <ctype.h>
  34. #include <ccan/ciniparser/ciniparser.h>
  35. #define ASCIILINESZ (1024)
  36. #define INI_INVALID_KEY ((char*) NULL)
  37. /**
  38. * This enum stores the status for each parsed line (internal use only).
  39. */
  40. typedef enum _line_status_ {
  41. LINE_UNPROCESSED,
  42. LINE_ERROR,
  43. LINE_EMPTY,
  44. LINE_COMMENT,
  45. LINE_SECTION,
  46. LINE_VALUE
  47. } line_status;
  48. /**
  49. * @brief Convert a string to lowercase.
  50. * @param s String to convert.
  51. * @return ptr to statically allocated string.
  52. *
  53. * This function returns a pointer to a statically allocated string
  54. * containing a lowercased version of the input string. Do not free
  55. * or modify the returned string! Since the returned string is statically
  56. * allocated, it will be modified at each function call (not re-entrant).
  57. */
  58. static char *strlwc(const char *s)
  59. {
  60. static char l[ASCIILINESZ+1];
  61. int i;
  62. if (s == NULL)
  63. return NULL;
  64. for (i = 0; s[i] && i < ASCIILINESZ; i++)
  65. l[i] = tolower(s[i]);
  66. l[i] = '\0';
  67. return l;
  68. }
  69. /**
  70. * @brief Remove blanks at the beginning and the end of a string.
  71. * @param s String to parse.
  72. * @return ptr to statically allocated string.
  73. *
  74. * This function returns a pointer to a statically allocated string,
  75. * which is identical to the input string, except that all blank
  76. * characters at the end and the beg. of the string have been removed.
  77. * Do not free or modify the returned string! Since the returned string
  78. * is statically allocated, it will be modified at each function call
  79. * (not re-entrant).
  80. */
  81. static char *strstrip(const char *s)
  82. {
  83. static char l[ASCIILINESZ+1];
  84. unsigned int i, numspc;
  85. if (s == NULL)
  86. return NULL;
  87. while (isspace(*s))
  88. s++;
  89. for (i = numspc = 0; s[i] && i < ASCIILINESZ; i++) {
  90. l[i] = s[i];
  91. if (isspace(l[i]))
  92. numspc++;
  93. else
  94. numspc = 0;
  95. }
  96. l[i - numspc] = '\0';
  97. return l;
  98. }
  99. /**
  100. * @brief Load a single line from an INI file
  101. * @param input_line Input line, may be concatenated multi-line input
  102. * @param section Output space to store section
  103. * @param key Output space to store key
  104. * @param value Output space to store value
  105. * @return line_status value
  106. */
  107. static
  108. line_status ciniparser_line(char *input_line, char *section,
  109. char *key, char *value)
  110. {
  111. line_status sta;
  112. char line[ASCIILINESZ+1];
  113. int len;
  114. strcpy(line, strstrip(input_line));
  115. len = (int) strlen(line);
  116. sta = LINE_UNPROCESSED;
  117. if (len < 1) {
  118. /* Empty line */
  119. sta = LINE_EMPTY;
  120. } else if (line[0] == '#') {
  121. /* Comment line */
  122. sta = LINE_COMMENT;
  123. } else if (line[0] == '[' && line[len-1] == ']') {
  124. /* Section name */
  125. sscanf(line, "[%[^]]", section);
  126. strcpy(section, strstrip(section));
  127. strcpy(section, strlwc(section));
  128. sta = LINE_SECTION;
  129. } else if (sscanf (line, "%[^=] = \"%[^\"]\"", key, value) == 2
  130. || sscanf (line, "%[^=] = '%[^\']'", key, value) == 2
  131. || sscanf (line, "%[^=] = %[^;#]", key, value) == 2) {
  132. /* Usual key=value, with or without comments */
  133. strcpy(key, strstrip(key));
  134. strcpy(key, strlwc(key));
  135. strcpy(value, strstrip(value));
  136. /*
  137. * sscanf cannot handle '' or "" as empty values
  138. * this is done here
  139. */
  140. if (!strcmp(value, "\"\"") || (!strcmp(value, "''"))) {
  141. value[0] = 0;
  142. }
  143. sta = LINE_VALUE;
  144. } else if (sscanf(line, "%[^=] = %[;#]", key, value) == 2
  145. || sscanf(line, "%[^=] %[=]", key, value) == 2) {
  146. /*
  147. * Special cases:
  148. * key=
  149. * key=;
  150. * key=#
  151. */
  152. strcpy(key, strstrip(key));
  153. strcpy(key, strlwc(key));
  154. value[0] = 0;
  155. sta = LINE_VALUE;
  156. } else {
  157. /* Generate syntax error */
  158. sta = LINE_ERROR;
  159. }
  160. return sta;
  161. }
  162. /* The remaining public functions are documented in ciniparser.h */
  163. int ciniparser_getnsec(dictionary *d)
  164. {
  165. int i;
  166. int nsec;
  167. if (d == NULL)
  168. return -1;
  169. nsec = 0;
  170. for (i = 0; i < d->size; i++) {
  171. if (d->key[i] == NULL)
  172. continue;
  173. if (strchr(d->key[i], ':') == NULL) {
  174. nsec ++;
  175. }
  176. }
  177. return nsec;
  178. }
  179. char *ciniparser_getsecname(dictionary *d, int n)
  180. {
  181. int i;
  182. int foundsec;
  183. if (d == NULL || n < 0)
  184. return NULL;
  185. if (n == 0)
  186. n ++;
  187. foundsec = 0;
  188. for (i = 0; i < d->size; i++) {
  189. if (d->key[i] == NULL)
  190. continue;
  191. if (! strchr(d->key[i], ':')) {
  192. foundsec++;
  193. if (foundsec >= n)
  194. break;
  195. }
  196. }
  197. if (foundsec == n) {
  198. return d->key[i];
  199. }
  200. return (char *) NULL;
  201. }
  202. void ciniparser_dump(dictionary *d, FILE *f)
  203. {
  204. int i;
  205. if (d == NULL || f == NULL)
  206. return;
  207. for (i = 0; i < d->size; i++) {
  208. if (d->key[i] == NULL)
  209. continue;
  210. if (d->val[i] != NULL) {
  211. fprintf(f, "[%s]=[%s]\n", d->key[i], d->val[i]);
  212. } else {
  213. fprintf(f, "[%s]=UNDEF\n", d->key[i]);
  214. }
  215. }
  216. return;
  217. }
  218. void ciniparser_dump_ini(dictionary *d, FILE *f)
  219. {
  220. int i, j;
  221. char keym[ASCIILINESZ+1];
  222. int nsec;
  223. char *secname;
  224. int seclen;
  225. if (d == NULL || f == NULL)
  226. return;
  227. memset(keym, 0, ASCIILINESZ + 1);
  228. nsec = ciniparser_getnsec(d);
  229. if (nsec < 1) {
  230. /* No section in file: dump all keys as they are */
  231. for (i = 0; i < d->size; i++) {
  232. if (d->key[i] == NULL)
  233. continue;
  234. fprintf(f, "%s = %s\n", d->key[i], d->val[i]);
  235. }
  236. return;
  237. }
  238. for (i = 0; i < nsec; i++) {
  239. secname = ciniparser_getsecname(d, i);
  240. seclen = (int)strlen(secname);
  241. fprintf(f, "\n[%s]\n", secname);
  242. snprintf(keym, ASCIILINESZ + 1, "%s:", secname);
  243. for (j = 0; j < d->size; j++) {
  244. if (d->key[j] == NULL)
  245. continue;
  246. if (!strncmp(d->key[j], keym, seclen+1)) {
  247. fprintf(f, "%-30s = %s\n",
  248. d->key[j]+seclen+1,
  249. d->val[j] ? d->val[j] : "");
  250. }
  251. }
  252. }
  253. fprintf(f, "\n");
  254. return;
  255. }
  256. char *ciniparser_getstring(dictionary *d, const char *key, char *def)
  257. {
  258. char *lc_key;
  259. char *sval;
  260. if (d == NULL || key == NULL)
  261. return def;
  262. lc_key = strlwc(key);
  263. sval = dictionary_get(d, lc_key, def);
  264. return sval;
  265. }
  266. int ciniparser_getint(dictionary *d, const char *key, int notfound)
  267. {
  268. char *str;
  269. str = ciniparser_getstring(d, key, INI_INVALID_KEY);
  270. if (str == INI_INVALID_KEY)
  271. return notfound;
  272. return (int) strtol(str, NULL, 10);
  273. }
  274. double ciniparser_getdouble(dictionary *d, char *key, double notfound)
  275. {
  276. char *str;
  277. str = ciniparser_getstring(d, key, INI_INVALID_KEY);
  278. if (str == INI_INVALID_KEY)
  279. return notfound;
  280. return atof(str);
  281. }
  282. int ciniparser_getboolean(dictionary *d, const char *key, int notfound)
  283. {
  284. char *c;
  285. int ret;
  286. c = ciniparser_getstring(d, key, INI_INVALID_KEY);
  287. if (c == INI_INVALID_KEY)
  288. return notfound;
  289. switch(c[0]) {
  290. case 'y': case 'Y': case '1': case 't': case 'T':
  291. ret = 1;
  292. break;
  293. case 'n': case 'N': case '0': case 'f': case 'F':
  294. ret = 0;
  295. break;
  296. default:
  297. ret = notfound;
  298. break;
  299. }
  300. return ret;
  301. }
  302. int ciniparser_find_entry(dictionary *ini, char *entry)
  303. {
  304. int found = 0;
  305. if (ciniparser_getstring(ini, entry, INI_INVALID_KEY) != INI_INVALID_KEY) {
  306. found = 1;
  307. }
  308. return found;
  309. }
  310. int ciniparser_set(dictionary *d, char *entry, char *val)
  311. {
  312. return dictionary_set(d, strlwc(entry), val);
  313. }
  314. void ciniparser_unset(dictionary *ini, char *entry)
  315. {
  316. dictionary_unset(ini, strlwc(entry));
  317. }
  318. dictionary *ciniparser_load(const char *ininame)
  319. {
  320. FILE *in;
  321. char line[ASCIILINESZ+1];
  322. char section[ASCIILINESZ+1];
  323. char key[ASCIILINESZ+1];
  324. char tmp[ASCIILINESZ+1];
  325. char val[ASCIILINESZ+1];
  326. int last = 0, len, lineno = 0, errs = 0;
  327. dictionary *dict;
  328. if ((in = fopen(ininame, "r")) == NULL) {
  329. fprintf(stderr, "ciniparser: cannot open %s\n", ininame);
  330. return NULL;
  331. }
  332. dict = dictionary_new(0);
  333. if (!dict) {
  334. fclose(in);
  335. return NULL;
  336. }
  337. memset(line, 0, ASCIILINESZ + 1);
  338. memset(section, 0, ASCIILINESZ + 1);
  339. memset(key, 0, ASCIILINESZ + 1);
  340. memset(val, 0, ASCIILINESZ + 1);
  341. last = 0;
  342. while (fgets(line+last, ASCIILINESZ-last, in)!=NULL) {
  343. lineno++;
  344. len = (int) strlen(line)-1;
  345. /* Safety check against buffer overflows */
  346. if (line[len] != '\n') {
  347. fprintf(stderr,
  348. "ciniparser: input line too long in %s (%d)\n",
  349. ininame,
  350. lineno);
  351. dictionary_del(dict);
  352. fclose(in);
  353. return NULL;
  354. }
  355. /* Get rid of \n and spaces at end of line */
  356. while ((len >= 0) &&
  357. ((line[len] == '\n') || (isspace(line[len])))) {
  358. line[len] = 0;
  359. len--;
  360. }
  361. /* Detect multi-line */
  362. if (line[len] == '\\') {
  363. /* Multi-line value */
  364. last = len;
  365. continue;
  366. } else {
  367. last = 0;
  368. }
  369. switch (ciniparser_line(line, section, key, val)) {
  370. case LINE_EMPTY:
  371. case LINE_COMMENT:
  372. break;
  373. case LINE_SECTION:
  374. errs = dictionary_set(dict, section, NULL);
  375. break;
  376. case LINE_VALUE:
  377. snprintf(tmp, ASCIILINESZ + 1, "%s:%s", section, key);
  378. errs = dictionary_set(dict, tmp, val);
  379. break;
  380. case LINE_ERROR:
  381. fprintf(stderr, "ciniparser: syntax error in %s (%d):\n",
  382. ininame, lineno);
  383. fprintf(stderr, "-> %s\n", line);
  384. errs++;
  385. break;
  386. default:
  387. break;
  388. }
  389. memset(line, 0, ASCIILINESZ);
  390. last = 0;
  391. if (errs < 0) {
  392. fprintf(stderr, "ciniparser: memory allocation failure\n");
  393. break;
  394. }
  395. }
  396. if (errs) {
  397. dictionary_del(dict);
  398. dict = NULL;
  399. }
  400. fclose(in);
  401. return dict;
  402. }
  403. void ciniparser_freedict(dictionary *d)
  404. {
  405. dictionary_del(d);
  406. }
  407. /** @}
  408. */