iniparser.c 28 KB

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