iniparser.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. /*-------------------------------------------------------------------------*/
  2. /**
  3. @file iniparser.c
  4. @author N. Devillard
  5. @brief Parser for ini files.
  6. */
  7. /*--------------------------------------------------------------------------*/
  8. /*---------------------------- Includes ------------------------------------*/
  9. #include <ctype.h>
  10. #include <stdarg.h>
  11. #include "iniparser.h"
  12. /*---------------------------- Defines -------------------------------------*/
  13. #define ASCIILINESZ (1024)
  14. #define INI_INVALID_KEY ((char*)-1)
  15. /*---------------------------------------------------------------------------
  16. Private to this module
  17. ---------------------------------------------------------------------------*/
  18. /**
  19. * This enum stores the status for each parsed line (internal use only).
  20. */
  21. typedef enum _line_status_ {
  22. LINE_UNPROCESSED,
  23. LINE_ERROR,
  24. LINE_EMPTY,
  25. LINE_COMMENT,
  26. LINE_SECTION,
  27. LINE_VALUE
  28. } line_status ;
  29. /*-------------------------------------------------------------------------*/
  30. /**
  31. @brief Convert a string to lowercase.
  32. @param in String to convert.
  33. @param out Output buffer.
  34. @param len Size of the out buffer.
  35. @return ptr to the out buffer or NULL if an error occured.
  36. This function convert a string into lowercase.
  37. At most len - 1 elements of the input string will be converted.
  38. */
  39. /*--------------------------------------------------------------------------*/
  40. static const char * strlwc(const char * in, char *out, unsigned len)
  41. {
  42. unsigned i ;
  43. if (in == NULL || out == NULL || len == 0) return NULL ;
  44. i = 0 ;
  45. while (in[i] != '\0' && i < len - 1) {
  46. out[i] = (char)tolower((int)in[i]);
  47. i++ ;
  48. }
  49. out[i] = '\0';
  50. return out ;
  51. }
  52. /*-------------------------------------------------------------------------*/
  53. /**
  54. @brief Duplicate a string
  55. @param s String to duplicate
  56. @return Pointer to a newly allocated string, to be freed with free()
  57. This is a replacement for strdup(). This implementation is provided
  58. for systems that do not have it.
  59. */
  60. /*--------------------------------------------------------------------------*/
  61. static char * xstrdup(const char * s)
  62. {
  63. char * t ;
  64. size_t len ;
  65. if (!s)
  66. return NULL ;
  67. len = strlen(s) + 1 ;
  68. t = (char*) malloc(len) ;
  69. if (t) {
  70. memcpy(t, s, len) ;
  71. }
  72. return t ;
  73. }
  74. /*-------------------------------------------------------------------------*/
  75. /**
  76. @brief Remove blanks at the beginning and the end of a string.
  77. @param str String to parse and alter.
  78. @return unsigned New size of the string.
  79. */
  80. /*--------------------------------------------------------------------------*/
  81. static unsigned strstrip(char * s)
  82. {
  83. char *last = NULL ;
  84. char *dest = s;
  85. if (s == NULL) return 0;
  86. last = s + strlen(s);
  87. while (isspace((int)*s) && *s) s++;
  88. while (last > s) {
  89. if (!isspace((int) * (last - 1)))
  90. break ;
  91. last -- ;
  92. }
  93. *last = (char)0;
  94. memmove(dest, s, last - s + 1);
  95. return last - s;
  96. }
  97. /*-------------------------------------------------------------------------*/
  98. /**
  99. @brief Default error callback for iniparser: wraps `fprintf(stderr, ...)`.
  100. */
  101. /*--------------------------------------------------------------------------*/
  102. static int default_error_callback(const char *format, ...)
  103. {
  104. int ret;
  105. va_list argptr;
  106. va_start(argptr, format);
  107. ret = vfprintf(stderr, format, argptr);
  108. va_end(argptr);
  109. return ret;
  110. }
  111. static int (*iniparser_error_callback)(const char*, ...) = default_error_callback;
  112. /*-------------------------------------------------------------------------*/
  113. /**
  114. @brief Configure a function to receive the error messages.
  115. @param errback Function to call.
  116. By default, the error will be printed on stderr. If a null pointer is passed
  117. as errback the error callback will be switched back to default.
  118. */
  119. /*--------------------------------------------------------------------------*/
  120. void iniparser_set_error_callback(int (*errback)(const char *, ...))
  121. {
  122. if (errback) {
  123. iniparser_error_callback = errback;
  124. } else {
  125. iniparser_error_callback = default_error_callback;
  126. }
  127. }
  128. /*-------------------------------------------------------------------------*/
  129. /**
  130. @brief Get number of sections in a dictionary
  131. @param d Dictionary to examine
  132. @return int Number of sections found in dictionary
  133. This function returns the number of sections found in a dictionary.
  134. The test to recognize sections is done on the string stored in the
  135. dictionary: a section name is given as "section" whereas a key is
  136. stored as "section:key", thus the test looks for entries that do not
  137. contain a colon.
  138. This clearly fails in the case a section name contains a colon, but
  139. this should simply be avoided.
  140. This function returns -1 in case of error.
  141. */
  142. /*--------------------------------------------------------------------------*/
  143. int iniparser_getnsec(const dictionary * d)
  144. {
  145. int i ;
  146. int nsec ;
  147. if (d == NULL) return -1 ;
  148. nsec = 0 ;
  149. for (i = 0 ; i < d->size ; i++) {
  150. if (d->key[i] == NULL)
  151. continue ;
  152. if (strchr(d->key[i], ':') == NULL) {
  153. nsec ++ ;
  154. }
  155. }
  156. return nsec ;
  157. }
  158. /*-------------------------------------------------------------------------*/
  159. /**
  160. @brief Get name for section n in a dictionary.
  161. @param d Dictionary to examine
  162. @param n Section number (from 0 to nsec-1).
  163. @return Pointer to char string
  164. This function locates the n-th section in a dictionary and returns
  165. its name as a pointer to a string statically allocated inside the
  166. dictionary. Do not free or modify the returned string!
  167. This function returns NULL in case of error.
  168. */
  169. /*--------------------------------------------------------------------------*/
  170. const char * iniparser_getsecname(const dictionary * d, int n)
  171. {
  172. int i ;
  173. int foundsec ;
  174. if (d == NULL || n < 0) return NULL ;
  175. foundsec = 0 ;
  176. for (i = 0 ; i < d->size ; i++) {
  177. if (d->key[i] == NULL)
  178. continue ;
  179. if (strchr(d->key[i], ':') == NULL) {
  180. foundsec++ ;
  181. if (foundsec > n)
  182. break ;
  183. }
  184. }
  185. if (foundsec <= n) {
  186. return NULL ;
  187. }
  188. return d->key[i] ;
  189. }
  190. /*-------------------------------------------------------------------------*/
  191. /**
  192. @brief Dump a dictionary to an opened file pointer.
  193. @param d Dictionary to dump.
  194. @param f Opened file pointer to dump to.
  195. @return void
  196. This function prints out the contents of a dictionary, one element by
  197. line, onto the provided file pointer. It is OK to specify @c stderr
  198. or @c stdout as output files. This function is meant for debugging
  199. purposes mostly.
  200. */
  201. /*--------------------------------------------------------------------------*/
  202. void iniparser_dump(const dictionary * d, FILE * f)
  203. {
  204. int i ;
  205. if (d == NULL || f == NULL) return ;
  206. for (i = 0 ; i < d->size ; i++) {
  207. if (d->key[i] == NULL)
  208. continue ;
  209. if (d->val[i] != NULL) {
  210. fprintf(f, "[%s]=[%s]\n", d->key[i], d->val[i]);
  211. } else {
  212. fprintf(f, "[%s]=UNDEF\n", d->key[i]);
  213. }
  214. }
  215. return ;
  216. }
  217. /*-------------------------------------------------------------------------*/
  218. /**
  219. @brief Save a dictionary to a loadable ini file
  220. @param d Dictionary to dump
  221. @param f Opened file pointer to dump to
  222. @return void
  223. This function dumps a given dictionary into a loadable ini file.
  224. It is Ok to specify @c stderr or @c stdout as output files.
  225. */
  226. /*--------------------------------------------------------------------------*/
  227. void iniparser_dump_ini(const dictionary * d, FILE * f)
  228. {
  229. int i ;
  230. int nsec ;
  231. const char * secname ;
  232. if (d == NULL || f == NULL) return ;
  233. nsec = iniparser_getnsec(d);
  234. if (nsec < 1) {
  235. /* No section in file: dump all keys as they are */
  236. for (i = 0 ; i < d->size ; i++) {
  237. if (d->key[i] == NULL)
  238. continue ;
  239. fprintf(f, "%s = %s\n", d->key[i], d->val[i]);
  240. }
  241. return ;
  242. }
  243. for (i = 0 ; i < nsec ; i++) {
  244. secname = iniparser_getsecname(d, i) ;
  245. iniparser_dumpsection_ini(d, secname, f);
  246. }
  247. fprintf(f, "\n");
  248. return ;
  249. }
  250. /*-------------------------------------------------------------------------*/
  251. /**
  252. @brief Save a dictionary section to a loadable ini file
  253. @param d Dictionary to dump
  254. @param s Section name of dictionary to dump
  255. @param f Opened file pointer to dump to
  256. @return void
  257. This function dumps a given section of a given dictionary into a loadable ini
  258. file. It is Ok to specify @c stderr or @c stdout as output files.
  259. */
  260. /*--------------------------------------------------------------------------*/
  261. void iniparser_dumpsection_ini(const dictionary * d, const char * s, FILE * f)
  262. {
  263. int j ;
  264. char keym[ASCIILINESZ + 1];
  265. int seclen ;
  266. if (d == NULL || f == NULL) return ;
  267. if (! iniparser_find_entry(d, s)) return ;
  268. seclen = (int)strlen(s);
  269. fprintf(f, "\n[%s]\n", s);
  270. sprintf(keym, "%s:", s);
  271. for (j = 0 ; j < d->size ; j++) {
  272. if (d->key[j] == NULL)
  273. continue ;
  274. if (!strncmp(d->key[j], keym, seclen + 1)) {
  275. fprintf(f,
  276. "%-30s = %s\n",
  277. d->key[j] + seclen + 1,
  278. d->val[j] ? d->val[j] : "");
  279. }
  280. }
  281. fprintf(f, "\n");
  282. return ;
  283. }
  284. /*-------------------------------------------------------------------------*/
  285. /**
  286. @brief Get the number of keys in a section of a dictionary.
  287. @param d Dictionary to examine
  288. @param s Section name of dictionary to examine
  289. @return Number of keys in section
  290. */
  291. /*--------------------------------------------------------------------------*/
  292. int iniparser_getsecnkeys(const dictionary * d, const char * s)
  293. {
  294. int seclen, nkeys ;
  295. char keym[ASCIILINESZ + 1];
  296. int j ;
  297. nkeys = 0;
  298. if (d == NULL) return nkeys;
  299. if (! iniparser_find_entry(d, s)) return nkeys;
  300. seclen = (int)strlen(s);
  301. strlwc(s, keym, sizeof(keym));
  302. keym[seclen] = ':';
  303. for (j = 0 ; j < d->size ; j++) {
  304. if (d->key[j] == NULL)
  305. continue ;
  306. if (!strncmp(d->key[j], keym, seclen + 1))
  307. nkeys++;
  308. }
  309. return nkeys;
  310. }
  311. /*-------------------------------------------------------------------------*/
  312. /**
  313. @brief Get the number of keys in a section of a dictionary.
  314. @param d Dictionary to examine
  315. @param s Section name of dictionary to examine
  316. @param keys Already allocated array to store the keys in
  317. @return The pointer passed as `keys` argument or NULL in case of error
  318. This function queries a dictionary and finds all keys in a given section.
  319. The keys argument should be an array of pointers which size has been
  320. determined by calling `iniparser_getsecnkeys` function prior to this one.
  321. Each pointer in the returned char pointer-to-pointer is pointing to
  322. a string allocated in the dictionary; do not free or modify them.
  323. */
  324. /*--------------------------------------------------------------------------*/
  325. const char ** iniparser_getseckeys(const dictionary * d, const char * s, const char ** keys)
  326. {
  327. int i, j, seclen ;
  328. char keym[ASCIILINESZ + 1];
  329. if (d == NULL || keys == NULL) return NULL;
  330. if (! iniparser_find_entry(d, s)) return NULL;
  331. seclen = (int)strlen(s);
  332. strlwc(s, keym, sizeof(keym));
  333. keym[seclen] = ':';
  334. i = 0;
  335. for (j = 0 ; j < d->size ; j++) {
  336. if (d->key[j] == NULL)
  337. continue ;
  338. if (!strncmp(d->key[j], keym, seclen + 1)) {
  339. keys[i] = d->key[j];
  340. i++;
  341. }
  342. }
  343. return keys;
  344. }
  345. /*-------------------------------------------------------------------------*/
  346. /**
  347. @brief Get the string associated to a key
  348. @param d Dictionary to search
  349. @param key Key string to look for
  350. @param def Default value to return if key not found.
  351. @return pointer to statically allocated character string
  352. This function queries a dictionary for a key. A key as read from an
  353. ini file is given as "section:key". If the key cannot be found,
  354. the pointer passed as 'def' is returned.
  355. The returned char pointer is pointing to a string allocated in
  356. the dictionary, do not free or modify it.
  357. */
  358. /*--------------------------------------------------------------------------*/
  359. const char * iniparser_getstring(const dictionary * d, const char * key, const char * def)
  360. {
  361. const char * lc_key ;
  362. const char * sval ;
  363. char tmp_str[ASCIILINESZ + 1];
  364. if (d == NULL || key == NULL)
  365. return def ;
  366. lc_key = strlwc(key, tmp_str, sizeof(tmp_str));
  367. sval = dictionary_get(d, lc_key, def);
  368. return sval ;
  369. }
  370. /*-------------------------------------------------------------------------*/
  371. /**
  372. @brief Get the string associated to a key, convert to an long int
  373. @param d Dictionary to search
  374. @param key Key string to look for
  375. @param notfound Value to return in case of error
  376. @return long integer
  377. This function queries a dictionary for a key. A key as read from an
  378. ini file is given as "section:key". If the key cannot be found,
  379. the notfound value is returned.
  380. Supported values for integers include the usual C notation
  381. so decimal, octal (starting with 0) and hexadecimal (starting with 0x)
  382. are supported. Examples:
  383. "42" -> 42
  384. "042" -> 34 (octal -> decimal)
  385. "0x42" -> 66 (hexa -> decimal)
  386. Warning: the conversion may overflow in various ways. Conversion is
  387. totally outsourced to strtol(), see the associated man page for overflow
  388. handling.
  389. Credits: Thanks to A. Becker for suggesting strtol()
  390. */
  391. /*--------------------------------------------------------------------------*/
  392. long int iniparser_getlongint(const dictionary * d, const char * key, long int notfound)
  393. {
  394. const char * str ;
  395. str = iniparser_getstring(d, key, INI_INVALID_KEY);
  396. if (str == INI_INVALID_KEY) return notfound ;
  397. return strtol(str, NULL, 0);
  398. }
  399. /*-------------------------------------------------------------------------*/
  400. /**
  401. @brief Get the string associated to a key, convert to an int
  402. @param d Dictionary to search
  403. @param key Key string to look for
  404. @param notfound Value to return in case of error
  405. @return integer
  406. This function queries a dictionary for a key. A key as read from an
  407. ini file is given as "section:key". If the key cannot be found,
  408. the notfound value is returned.
  409. Supported values for integers include the usual C notation
  410. so decimal, octal (starting with 0) and hexadecimal (starting with 0x)
  411. are supported. Examples:
  412. "42" -> 42
  413. "042" -> 34 (octal -> decimal)
  414. "0x42" -> 66 (hexa -> decimal)
  415. Warning: the conversion may overflow in various ways. Conversion is
  416. totally outsourced to strtol(), see the associated man page for overflow
  417. handling.
  418. Credits: Thanks to A. Becker for suggesting strtol()
  419. */
  420. /*--------------------------------------------------------------------------*/
  421. int iniparser_getint(const dictionary * d, const char * key, int notfound)
  422. {
  423. return (int)iniparser_getlongint(d, key, notfound);
  424. }
  425. /*-------------------------------------------------------------------------*/
  426. /**
  427. @brief Get the string associated to a key, convert to a double
  428. @param d Dictionary to search
  429. @param key Key string to look for
  430. @param notfound Value to return in case of error
  431. @return double
  432. This function queries a dictionary for a key. A key as read from an
  433. ini file is given as "section:key". If the key cannot be found,
  434. the notfound value is returned.
  435. */
  436. /*--------------------------------------------------------------------------*/
  437. double iniparser_getdouble(const dictionary * d, const char * key, double notfound)
  438. {
  439. const char * str ;
  440. str = iniparser_getstring(d, key, INI_INVALID_KEY);
  441. if (str == INI_INVALID_KEY) return notfound ;
  442. return atof(str);
  443. }
  444. /*-------------------------------------------------------------------------*/
  445. /**
  446. @brief Get the string associated to a key, convert to a boolean
  447. @param d Dictionary to search
  448. @param key Key string to look for
  449. @param notfound Value to return in case of error
  450. @return integer
  451. This function queries a dictionary for a key. A key as read from an
  452. ini file is given as "section:key". If the key cannot be found,
  453. the notfound value is returned.
  454. A true boolean is found if one of the following is matched:
  455. - A string starting with 'y'
  456. - A string starting with 'Y'
  457. - A string starting with 't'
  458. - A string starting with 'T'
  459. - A string starting with '1'
  460. A false boolean is found if one of the following is matched:
  461. - A string starting with 'n'
  462. - A string starting with 'N'
  463. - A string starting with 'f'
  464. - A string starting with 'F'
  465. - A string starting with '0'
  466. The notfound value returned if no boolean is identified, does not
  467. necessarily have to be 0 or 1.
  468. */
  469. /*--------------------------------------------------------------------------*/
  470. int iniparser_getboolean(const dictionary * d, const char * key, int notfound)
  471. {
  472. int ret ;
  473. const char * c ;
  474. c = iniparser_getstring(d, key, INI_INVALID_KEY);
  475. if (c == INI_INVALID_KEY) return notfound ;
  476. if (c[0] == 'y' || c[0] == 'Y' || c[0] == '1' || c[0] == 't' || c[0] == 'T') {
  477. ret = 1 ;
  478. } else if (c[0] == 'n' || c[0] == 'N' || c[0] == '0' || c[0] == 'f' || c[0] == 'F') {
  479. ret = 0 ;
  480. } else {
  481. ret = notfound ;
  482. }
  483. return ret;
  484. }
  485. /*-------------------------------------------------------------------------*/
  486. /**
  487. @brief Finds out if a given entry exists in a dictionary
  488. @param ini Dictionary to search
  489. @param entry Name of the entry to look for
  490. @return integer 1 if entry exists, 0 otherwise
  491. Finds out if a given entry exists in the dictionary. Since sections
  492. are stored as keys with NULL associated values, this is the only way
  493. of querying for the presence of sections in a dictionary.
  494. */
  495. /*--------------------------------------------------------------------------*/
  496. int iniparser_find_entry(const dictionary * ini, const char * entry)
  497. {
  498. int found = 0 ;
  499. if (iniparser_getstring(ini, entry, INI_INVALID_KEY) != INI_INVALID_KEY) {
  500. found = 1 ;
  501. }
  502. return found ;
  503. }
  504. /*-------------------------------------------------------------------------*/
  505. /**
  506. @brief Set an entry in a dictionary.
  507. @param ini Dictionary to modify.
  508. @param entry Entry to modify (entry name)
  509. @param val New value to associate to the entry.
  510. @return int 0 if Ok, -1 otherwise.
  511. If the given entry can be found in the dictionary, it is modified to
  512. contain the provided value. If it cannot be found, the entry is created.
  513. It is Ok to set val to NULL.
  514. */
  515. /*--------------------------------------------------------------------------*/
  516. int iniparser_set(dictionary * ini, const char * entry, const char * val)
  517. {
  518. char tmp_str[ASCIILINESZ + 1];
  519. return dictionary_set(ini, strlwc(entry, tmp_str, sizeof(tmp_str)), val) ;
  520. }
  521. /*-------------------------------------------------------------------------*/
  522. /**
  523. @brief Delete an entry in a dictionary
  524. @param ini Dictionary to modify
  525. @param entry Entry to delete (entry name)
  526. @return void
  527. If the given entry can be found, it is deleted from the dictionary.
  528. */
  529. /*--------------------------------------------------------------------------*/
  530. void iniparser_unset(dictionary * ini, const char * entry)
  531. {
  532. char tmp_str[ASCIILINESZ + 1];
  533. dictionary_unset(ini, strlwc(entry, tmp_str, sizeof(tmp_str)));
  534. }
  535. /*-------------------------------------------------------------------------*/
  536. /**
  537. @brief Load a single line from an INI file
  538. @param input_line Input line, may be concatenated multi-line input
  539. @param section Output space to store section
  540. @param key Output space to store key
  541. @param value Output space to store value
  542. @return line_status value
  543. */
  544. /*--------------------------------------------------------------------------*/
  545. static line_status iniparser_line(
  546. const char * input_line,
  547. char * section,
  548. char * key,
  549. char * value)
  550. {
  551. line_status sta ;
  552. char * line = NULL;
  553. size_t len ;
  554. line = xstrdup(input_line);
  555. len = strstrip(line);
  556. sta = LINE_UNPROCESSED ;
  557. if (len < 1) {
  558. /* Empty line */
  559. sta = LINE_EMPTY ;
  560. } else if (line[0] == '#' || line[0] == ';') {
  561. /* Comment line */
  562. sta = LINE_COMMENT ;
  563. } else if (line[0] == '[' && line[len - 1] == ']') {
  564. /* Section name */
  565. sscanf(line, "[%[^]]", section);
  566. strstrip(section);
  567. strlwc(section, section, len);
  568. sta = LINE_SECTION ;
  569. } else if (sscanf (line, "%[^=] = \"%[^\"]\"", key, value) == 2
  570. || sscanf (line, "%[^=] = '%[^\']'", key, value) == 2) {
  571. /* Usual key=value with quotes, with or without comments */
  572. strstrip(key);
  573. strlwc(key, key, len);
  574. /* Don't strip spaces from values surrounded with quotes */
  575. sta = LINE_VALUE ;
  576. } else if (sscanf (line, "%[^=] = %[^;#]", key, value) == 2) {
  577. /* Usual key=value without quotes, with or without comments */
  578. strstrip(key);
  579. strlwc(key, key, len);
  580. strstrip(value);
  581. /*
  582. * sscanf cannot handle '' or "" as empty values
  583. * this is done here
  584. */
  585. if (!strcmp(value, "\"\"") || (!strcmp(value, "''"))) {
  586. value[0] = 0 ;
  587. }
  588. sta = LINE_VALUE ;
  589. } else if (sscanf(line, "%[^=] = %[;#]", key, value) == 2
  590. || sscanf(line, "%[^=] %[=]", key, value) == 2) {
  591. /*
  592. * Special cases:
  593. * key=
  594. * key=;
  595. * key=#
  596. */
  597. strstrip(key);
  598. strlwc(key, key, len);
  599. value[0] = 0 ;
  600. sta = LINE_VALUE ;
  601. } else {
  602. /* Generate syntax error */
  603. sta = LINE_ERROR ;
  604. }
  605. free(line);
  606. return sta ;
  607. }
  608. /*-------------------------------------------------------------------------*/
  609. /**
  610. @brief Parse an ini file and return an allocated dictionary object
  611. @param ininame Name of the ini file to read.
  612. @return Pointer to newly allocated dictionary
  613. This is the parser for ini files. This function is called, providing
  614. the name of the file to be read. It returns a dictionary object that
  615. should not be accessed directly, but through accessor functions
  616. instead.
  617. The returned dictionary must be freed using iniparser_freedict().
  618. */
  619. /*--------------------------------------------------------------------------*/
  620. dictionary * iniparser_load(const char * ininame)
  621. {
  622. FILE * in ;
  623. char line [ASCIILINESZ + 1] ;
  624. char section [ASCIILINESZ + 1] ;
  625. char key [ASCIILINESZ + 1] ;
  626. char tmp [(ASCIILINESZ * 2) + 2] ;
  627. char val [ASCIILINESZ + 1] ;
  628. int last = 0 ;
  629. int len ;
  630. int lineno = 0 ;
  631. int errs = 0;
  632. int mem_err = 0;
  633. dictionary * dict ;
  634. if ((in = fopen(ininame, "r")) == NULL) {
  635. iniparser_error_callback("iniparser: cannot open %s\n", ininame);
  636. return NULL ;
  637. }
  638. dict = dictionary_new(0) ;
  639. if (!dict) {
  640. fclose(in);
  641. return NULL ;
  642. }
  643. memset(line, 0, ASCIILINESZ);
  644. memset(section, 0, ASCIILINESZ);
  645. memset(key, 0, ASCIILINESZ);
  646. memset(val, 0, ASCIILINESZ);
  647. last = 0 ;
  648. while (fgets(line + last, ASCIILINESZ - last, in) != NULL) {
  649. lineno++ ;
  650. len = (int)strlen(line) - 1;
  651. if (len <= 0)
  652. continue;
  653. /* Safety check against buffer overflows */
  654. if (line[len] != '\n' && !feof(in)) {
  655. iniparser_error_callback(
  656. "iniparser: input line too long in %s (%d)\n",
  657. ininame,
  658. lineno);
  659. dictionary_del(dict);
  660. fclose(in);
  661. return NULL ;
  662. }
  663. /* Get rid of \n and spaces at end of line */
  664. while ((len >= 0) &&
  665. ((line[len] == '\n') || (isspace(line[len])))) {
  666. line[len] = 0 ;
  667. len-- ;
  668. }
  669. if (len < 0) { /* Line was entirely \n and/or spaces */
  670. len = 0;
  671. }
  672. /* Detect multi-line */
  673. if (line[len] == '\\') {
  674. /* Multi-line value */
  675. last = len ;
  676. continue ;
  677. } else {
  678. last = 0 ;
  679. }
  680. switch (iniparser_line(line, section, key, val)) {
  681. case LINE_EMPTY:
  682. case LINE_COMMENT:
  683. break ;
  684. case LINE_SECTION:
  685. mem_err = dictionary_set(dict, section, NULL);
  686. break ;
  687. case LINE_VALUE:
  688. sprintf(tmp, "%s:%s", section, key);
  689. mem_err = dictionary_set(dict, tmp, val);
  690. break ;
  691. case LINE_ERROR:
  692. iniparser_error_callback(
  693. "iniparser: syntax error in %s (%d):\n-> %s\n",
  694. ininame,
  695. lineno,
  696. line);
  697. errs++ ;
  698. break;
  699. default:
  700. break ;
  701. }
  702. memset(line, 0, ASCIILINESZ);
  703. last = 0;
  704. if (mem_err < 0) {
  705. iniparser_error_callback("iniparser: memory allocation failure\n");
  706. break ;
  707. }
  708. }
  709. if (errs) {
  710. dictionary_del(dict);
  711. dict = NULL ;
  712. }
  713. fclose(in);
  714. return dict ;
  715. }
  716. /*-------------------------------------------------------------------------*/
  717. /**
  718. @brief Free all memory associated to an ini dictionary
  719. @param d Dictionary to free
  720. @return void
  721. Free all memory associated to an ini dictionary.
  722. It is mandatory to call this function before the dictionary object
  723. gets out of the current context.
  724. */
  725. /*--------------------------------------------------------------------------*/
  726. void iniparser_freedict(dictionary * d)
  727. {
  728. dictionary_del(d);
  729. }