config.c 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2010, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief Configuration File Parser
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. *
  24. * Includes the Asterisk Realtime API - ARA
  25. * See http://wiki.asterisk.org
  26. */
  27. /*** MODULEINFO
  28. <support_level>core</support_level>
  29. ***/
  30. #include "asterisk.h"
  31. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  32. #include "asterisk/paths.h" /* use ast_config_AST_CONFIG_DIR */
  33. #include "asterisk/network.h" /* we do some sockaddr manipulation here */
  34. #include <time.h>
  35. #include <sys/stat.h>
  36. #include <math.h> /* HUGE_VAL */
  37. #define AST_INCLUDE_GLOB 1
  38. #include "asterisk/config.h"
  39. #include "asterisk/cli.h"
  40. #include "asterisk/lock.h"
  41. #include "asterisk/utils.h"
  42. #include "asterisk/channel.h"
  43. #include "asterisk/app.h"
  44. #include "asterisk/astobj2.h"
  45. #include "asterisk/strings.h" /* for the ast_str_*() API */
  46. #include "asterisk/netsock2.h"
  47. #define MAX_NESTED_COMMENTS 128
  48. #define COMMENT_START ";--"
  49. #define COMMENT_END "--;"
  50. #define COMMENT_META ';'
  51. #define COMMENT_TAG '-'
  52. /*!
  53. * Define the minimum filename space to reserve for each
  54. * ast_variable in case the filename is renamed later by
  55. * ast_include_rename().
  56. */
  57. #define MIN_VARIABLE_FNAME_SPACE 40
  58. static char *extconfig_conf = "extconfig.conf";
  59. static struct ao2_container *cfg_hooks;
  60. static void config_hook_exec(const char *filename, const char *module, const struct ast_config *cfg);
  61. /*! \brief Structure to keep comments for rewriting configuration files */
  62. struct ast_comment {
  63. struct ast_comment *next;
  64. /*! Comment body allocated after struct. */
  65. char cmt[0];
  66. };
  67. /*! \brief Hold the mtime for config files, so if we don't need to reread our config, don't. */
  68. struct cache_file_include {
  69. AST_LIST_ENTRY(cache_file_include) list;
  70. /*! Filename or wildcard pattern as specified by the including file. */
  71. char include[0];
  72. };
  73. struct cache_file_mtime {
  74. AST_LIST_ENTRY(cache_file_mtime) list;
  75. AST_LIST_HEAD_NOLOCK(includes, cache_file_include) includes;
  76. unsigned int has_exec:1;
  77. /*! stat() file size */
  78. unsigned long stat_size;
  79. /*! stat() file modtime nanoseconds */
  80. unsigned long stat_mtime_nsec;
  81. /*! stat() file modtime seconds since epoc */
  82. time_t stat_mtime;
  83. /*! String stuffed in filename[] after the filename string. */
  84. const char *who_asked;
  85. /*! Filename and who_asked stuffed after it. */
  86. char filename[0];
  87. };
  88. /*! Cached file mtime list. */
  89. static AST_LIST_HEAD_STATIC(cfmtime_head, cache_file_mtime);
  90. static int init_appendbuf(void *data)
  91. {
  92. struct ast_str **str = data;
  93. *str = ast_str_create(16);
  94. return *str ? 0 : -1;
  95. }
  96. AST_THREADSTORAGE_CUSTOM(appendbuf, init_appendbuf, ast_free_ptr);
  97. /* comment buffers are better implemented using the ast_str_*() API */
  98. #define CB_SIZE 250 /* initial size of comment buffers */
  99. static void CB_ADD(struct ast_str **cb, const char *str)
  100. {
  101. ast_str_append(cb, 0, "%s", str);
  102. }
  103. static void CB_ADD_LEN(struct ast_str **cb, const char *str, int len)
  104. {
  105. char *s = ast_alloca(len + 1);
  106. memcpy(s, str, len);
  107. s[len] = '\0';
  108. ast_str_append(cb, 0, "%s", s);
  109. }
  110. static void CB_RESET(struct ast_str *cb, struct ast_str *llb)
  111. {
  112. if (cb) {
  113. ast_str_reset(cb);
  114. }
  115. if (llb) {
  116. ast_str_reset(llb);
  117. }
  118. }
  119. static struct ast_comment *ALLOC_COMMENT(struct ast_str *buffer)
  120. {
  121. struct ast_comment *x = NULL;
  122. if (!buffer || !ast_str_strlen(buffer)) {
  123. return NULL;
  124. }
  125. if ((x = ast_calloc(1, sizeof(*x) + ast_str_strlen(buffer) + 1))) {
  126. strcpy(x->cmt, ast_str_buffer(buffer)); /* SAFE */
  127. }
  128. return x;
  129. }
  130. /* I need to keep track of each config file, and all its inclusions,
  131. so that we can track blank lines in each */
  132. struct inclfile {
  133. char *fname;
  134. int lineno;
  135. };
  136. static int hash_string(const void *obj, const int flags)
  137. {
  138. char *str = ((struct inclfile *) obj)->fname;
  139. int total;
  140. for (total = 0; *str; str++) {
  141. unsigned int tmp = total;
  142. total <<= 1; /* multiply by 2 */
  143. total += tmp; /* multiply by 3 */
  144. total <<= 2; /* multiply by 12 */
  145. total += tmp; /* multiply by 13 */
  146. total += ((unsigned int) (*str));
  147. }
  148. if (total < 0) {
  149. total = -total;
  150. }
  151. return total;
  152. }
  153. static int hashtab_compare_strings(void *a, void *b, int flags)
  154. {
  155. const struct inclfile *ae = a, *be = b;
  156. return !strcmp(ae->fname, be->fname) ? CMP_MATCH | CMP_STOP : 0;
  157. }
  158. static struct ast_config_map {
  159. struct ast_config_map *next;
  160. int priority;
  161. /*! Stored in stuff[] at struct end. */
  162. const char *name;
  163. /*! Stored in stuff[] at struct end. */
  164. const char *driver;
  165. /*! Stored in stuff[] at struct end. */
  166. const char *database;
  167. /*! Stored in stuff[] at struct end. */
  168. const char *table;
  169. /*! Contents of name, driver, database, and table in that order stuffed here. */
  170. char stuff[0];
  171. } *config_maps = NULL;
  172. AST_MUTEX_DEFINE_STATIC(config_lock);
  173. static struct ast_config_engine *config_engine_list;
  174. #define MAX_INCLUDE_LEVEL 10
  175. struct ast_category_template_instance {
  176. char name[80]; /* redundant? */
  177. const struct ast_category *inst;
  178. AST_LIST_ENTRY(ast_category_template_instance) next;
  179. };
  180. struct ast_category {
  181. char name[80];
  182. int ignored; /*!< do not let user of the config see this category -- set by (!) after the category decl; a template */
  183. int include_level;
  184. /*!
  185. * \brief The file name from whence this declaration was read
  186. * \note Will never be NULL
  187. */
  188. char *file;
  189. int lineno;
  190. AST_LIST_HEAD_NOLOCK(template_instance_list, ast_category_template_instance) template_instances;
  191. struct ast_comment *precomments;
  192. struct ast_comment *sameline;
  193. struct ast_comment *trailing; /*!< the last object in the list will get assigned any trailing comments when EOF is hit */
  194. /*! First category variable in the list. */
  195. struct ast_variable *root;
  196. /*! Last category variable in the list. */
  197. struct ast_variable *last;
  198. /*! Next node in the list. */
  199. struct ast_category *next;
  200. };
  201. struct ast_config {
  202. /*! First config category in the list. */
  203. struct ast_category *root;
  204. /*! Last config category in the list. */
  205. struct ast_category *last;
  206. struct ast_category *current;
  207. struct ast_category *last_browse; /*!< used to cache the last category supplied via category_browse */
  208. int include_level;
  209. int max_include_level;
  210. struct ast_config_include *includes; /*!< a list of inclusions, which should describe the entire tree */
  211. };
  212. struct ast_config_include {
  213. /*!
  214. * \brief file name in which the include occurs
  215. * \note Will never be NULL
  216. */
  217. char *include_location_file;
  218. int include_location_lineno; /*!< lineno where include occurred */
  219. int exec; /*!< set to non-zero if its a #exec statement */
  220. /*!
  221. * \brief if it's an exec, you'll have both the /var/tmp to read, and the original script
  222. * \note Will never be NULL if exec is non-zero
  223. */
  224. char *exec_file;
  225. /*!
  226. * \brief file name included
  227. * \note Will never be NULL
  228. */
  229. char *included_file;
  230. int inclusion_count; /*!< if the file is included more than once, a running count thereof -- but, worry not,
  231. we explode the instances and will include those-- so all entries will be unique */
  232. int output; /*!< a flag to indicate if the inclusion has been output */
  233. struct ast_config_include *next; /*!< ptr to next inclusion in the list */
  234. };
  235. static void ast_variable_destroy(struct ast_variable *doomed);
  236. static void ast_includes_destroy(struct ast_config_include *incls);
  237. #ifdef MALLOC_DEBUG
  238. struct ast_variable *_ast_variable_new(const char *name, const char *value, const char *filename, const char *file, const char *func, int lineno)
  239. #else
  240. struct ast_variable *ast_variable_new(const char *name, const char *value, const char *filename)
  241. #endif
  242. {
  243. struct ast_variable *variable;
  244. int name_len = strlen(name) + 1;
  245. int val_len = strlen(value) + 1;
  246. int fn_len = strlen(filename) + 1;
  247. /* Ensure a minimum length in case the filename is changed later. */
  248. if (fn_len < MIN_VARIABLE_FNAME_SPACE) {
  249. fn_len = MIN_VARIABLE_FNAME_SPACE;
  250. }
  251. if (
  252. #ifdef MALLOC_DEBUG
  253. (variable = __ast_calloc(1, fn_len + name_len + val_len + sizeof(*variable), file, lineno, func))
  254. #else
  255. (variable = ast_calloc(1, fn_len + name_len + val_len + sizeof(*variable)))
  256. #endif
  257. ) {
  258. char *dst = variable->stuff; /* writable space starts here */
  259. /* Put file first so ast_include_rename() can calculate space available. */
  260. variable->file = strcpy(dst, filename);
  261. dst += fn_len;
  262. variable->name = strcpy(dst, name);
  263. dst += name_len;
  264. variable->value = strcpy(dst, value);
  265. }
  266. return variable;
  267. }
  268. /*!
  269. * \internal
  270. * \brief Move the contents from the source to the destination variable.
  271. *
  272. * \param dst_var Destination variable node
  273. * \param src_var Source variable node
  274. *
  275. * \return Nothing
  276. */
  277. static void ast_variable_move(struct ast_variable *dst_var, struct ast_variable *src_var)
  278. {
  279. dst_var->lineno = src_var->lineno;
  280. dst_var->object = src_var->object;
  281. dst_var->blanklines = src_var->blanklines;
  282. dst_var->precomments = src_var->precomments;
  283. src_var->precomments = NULL;
  284. dst_var->sameline = src_var->sameline;
  285. src_var->sameline = NULL;
  286. dst_var->trailing = src_var->trailing;
  287. src_var->trailing = NULL;
  288. }
  289. struct ast_config_include *ast_include_new(struct ast_config *conf, const char *from_file, const char *included_file, int is_exec, const char *exec_file, int from_lineno, char *real_included_file_name, int real_included_file_name_size)
  290. {
  291. /* a file should be included ONCE. Otherwise, if one of the instances is changed,
  292. * then all be changed. -- how do we know to include it? -- Handling modified
  293. * instances is possible, I'd have
  294. * to create a new master for each instance. */
  295. struct ast_config_include *inc;
  296. struct stat statbuf;
  297. inc = ast_include_find(conf, included_file);
  298. if (inc) {
  299. do {
  300. inc->inclusion_count++;
  301. snprintf(real_included_file_name, real_included_file_name_size, "%s~~%d", included_file, inc->inclusion_count);
  302. } while (stat(real_included_file_name, &statbuf) == 0);
  303. ast_log(LOG_WARNING,"'%s', line %d: Same File included more than once! This data will be saved in %s if saved back to disk.\n", from_file, from_lineno, real_included_file_name);
  304. } else
  305. *real_included_file_name = 0;
  306. inc = ast_calloc(1,sizeof(struct ast_config_include));
  307. if (!inc) {
  308. return NULL;
  309. }
  310. inc->include_location_file = ast_strdup(from_file);
  311. inc->include_location_lineno = from_lineno;
  312. if (!ast_strlen_zero(real_included_file_name))
  313. inc->included_file = ast_strdup(real_included_file_name);
  314. else
  315. inc->included_file = ast_strdup(included_file);
  316. inc->exec = is_exec;
  317. if (is_exec)
  318. inc->exec_file = ast_strdup(exec_file);
  319. if (!inc->include_location_file
  320. || !inc->included_file
  321. || (is_exec && !inc->exec_file)) {
  322. ast_includes_destroy(inc);
  323. return NULL;
  324. }
  325. /* attach this new struct to the conf struct */
  326. inc->next = conf->includes;
  327. conf->includes = inc;
  328. return inc;
  329. }
  330. void ast_include_rename(struct ast_config *conf, const char *from_file, const char *to_file)
  331. {
  332. struct ast_config_include *incl;
  333. struct ast_category *cat;
  334. char *str;
  335. int from_len = strlen(from_file);
  336. int to_len = strlen(to_file);
  337. if (strcmp(from_file, to_file) == 0) /* no use wasting time if the name is the same */
  338. return;
  339. /* the manager code allows you to read in one config file, then
  340. * write it back out under a different name. But, the new arrangement
  341. * ties output lines to the file name. So, before you try to write
  342. * the config file to disk, better riffle thru the data and make sure
  343. * the file names are changed.
  344. */
  345. /* file names are on categories, includes (of course), and on variables. So,
  346. * traverse all this and swap names */
  347. for (incl = conf->includes; incl; incl=incl->next) {
  348. if (strcmp(incl->include_location_file,from_file) == 0) {
  349. if (from_len >= to_len)
  350. strcpy(incl->include_location_file, to_file);
  351. else {
  352. /* Keep the old filename if the allocation fails. */
  353. str = ast_strdup(to_file);
  354. if (str) {
  355. ast_free(incl->include_location_file);
  356. incl->include_location_file = str;
  357. }
  358. }
  359. }
  360. }
  361. for (cat = conf->root; cat; cat = cat->next) {
  362. struct ast_variable **prev;
  363. struct ast_variable *v;
  364. struct ast_variable *new_var;
  365. if (strcmp(cat->file,from_file) == 0) {
  366. if (from_len >= to_len)
  367. strcpy(cat->file, to_file);
  368. else {
  369. /* Keep the old filename if the allocation fails. */
  370. str = ast_strdup(to_file);
  371. if (str) {
  372. ast_free(cat->file);
  373. cat->file = str;
  374. }
  375. }
  376. }
  377. for (prev = &cat->root, v = cat->root; v; prev = &v->next, v = v->next) {
  378. if (strcmp(v->file, from_file)) {
  379. continue;
  380. }
  381. /*
  382. * Calculate actual space available. The file string is
  383. * intentionally stuffed before the name string just so we can
  384. * do this.
  385. */
  386. if (to_len < v->name - v->file) {
  387. /* The new name will fit in the available space. */
  388. str = (char *) v->file;/* Stupid compiler complains about discarding qualifiers even though I used a cast. */
  389. strcpy(str, to_file);/* SAFE */
  390. continue;
  391. }
  392. /* Keep the old filename if the allocation fails. */
  393. new_var = ast_variable_new(v->name, v->value, to_file);
  394. if (!new_var) {
  395. continue;
  396. }
  397. /* Move items from the old list node to the replacement node. */
  398. ast_variable_move(new_var, v);
  399. /* Replace the old node in the list with the new node. */
  400. new_var->next = v->next;
  401. if (cat->last == v) {
  402. cat->last = new_var;
  403. }
  404. *prev = new_var;
  405. ast_variable_destroy(v);
  406. v = new_var;
  407. }
  408. }
  409. }
  410. struct ast_config_include *ast_include_find(struct ast_config *conf, const char *included_file)
  411. {
  412. struct ast_config_include *x;
  413. for (x=conf->includes;x;x=x->next) {
  414. if (strcmp(x->included_file,included_file) == 0)
  415. return x;
  416. }
  417. return 0;
  418. }
  419. void ast_variable_append(struct ast_category *category, struct ast_variable *variable)
  420. {
  421. if (!variable)
  422. return;
  423. if (category->last)
  424. category->last->next = variable;
  425. else
  426. category->root = variable;
  427. category->last = variable;
  428. while (category->last->next)
  429. category->last = category->last->next;
  430. }
  431. void ast_variable_insert(struct ast_category *category, struct ast_variable *variable, const char *line)
  432. {
  433. struct ast_variable *cur = category->root;
  434. int lineno;
  435. int insertline;
  436. if (!variable || sscanf(line, "%30d", &insertline) != 1) {
  437. return;
  438. }
  439. if (!insertline) {
  440. variable->next = category->root;
  441. category->root = variable;
  442. } else {
  443. for (lineno = 1; lineno < insertline; lineno++) {
  444. cur = cur->next;
  445. if (!cur->next) {
  446. break;
  447. }
  448. }
  449. variable->next = cur->next;
  450. cur->next = variable;
  451. }
  452. }
  453. static void ast_comment_destroy(struct ast_comment **comment)
  454. {
  455. struct ast_comment *n, *p;
  456. for (p = *comment; p; p = n) {
  457. n = p->next;
  458. ast_free(p);
  459. }
  460. *comment = NULL;
  461. }
  462. static void ast_variable_destroy(struct ast_variable *doomed)
  463. {
  464. ast_comment_destroy(&doomed->precomments);
  465. ast_comment_destroy(&doomed->sameline);
  466. ast_comment_destroy(&doomed->trailing);
  467. ast_free(doomed);
  468. }
  469. struct ast_variable *ast_variables_dup(struct ast_variable *var)
  470. {
  471. struct ast_variable *cloned;
  472. struct ast_variable *tmp;
  473. if (!(cloned = ast_variable_new(var->name, var->value, var->file))) {
  474. return NULL;
  475. }
  476. tmp = cloned;
  477. while ((var = var->next)) {
  478. if (!(tmp->next = ast_variable_new(var->name, var->value, var->file))) {
  479. ast_variables_destroy(cloned);
  480. return NULL;
  481. }
  482. tmp = tmp->next;
  483. }
  484. return cloned;
  485. }
  486. struct ast_variable *ast_variables_reverse(struct ast_variable *var)
  487. {
  488. struct ast_variable *var1, *var2;
  489. var1 = var;
  490. if (!var1 || !var1->next) {
  491. return var1;
  492. }
  493. var2 = var1->next;
  494. var1->next = NULL;
  495. while (var2) {
  496. struct ast_variable *next = var2->next;
  497. var2->next = var1;
  498. var1 = var2;
  499. var2 = next;
  500. }
  501. return var1;
  502. }
  503. void ast_variables_destroy(struct ast_variable *v)
  504. {
  505. struct ast_variable *vn;
  506. while (v) {
  507. vn = v;
  508. v = v->next;
  509. ast_variable_destroy(vn);
  510. }
  511. }
  512. struct ast_variable *ast_variable_browse(const struct ast_config *config, const char *category)
  513. {
  514. struct ast_category *cat = NULL;
  515. if (!category) {
  516. return NULL;
  517. }
  518. if (config->last_browse && (config->last_browse->name == category)) {
  519. cat = config->last_browse;
  520. } else {
  521. cat = ast_category_get(config, category);
  522. }
  523. return (cat) ? cat->root : NULL;
  524. }
  525. const char *ast_config_option(struct ast_config *cfg, const char *cat, const char *var)
  526. {
  527. const char *tmp;
  528. tmp = ast_variable_retrieve(cfg, cat, var);
  529. if (!tmp) {
  530. tmp = ast_variable_retrieve(cfg, "general", var);
  531. }
  532. return tmp;
  533. }
  534. const char *ast_variable_retrieve(const struct ast_config *config, const char *category, const char *variable)
  535. {
  536. struct ast_variable *v;
  537. if (category) {
  538. for (v = ast_variable_browse(config, category); v; v = v->next) {
  539. if (!strcasecmp(variable, v->name)) {
  540. return v->value;
  541. }
  542. }
  543. } else {
  544. struct ast_category *cat;
  545. for (cat = config->root; cat; cat = cat->next) {
  546. for (v = cat->root; v; v = v->next) {
  547. if (!strcasecmp(variable, v->name)) {
  548. return v->value;
  549. }
  550. }
  551. }
  552. }
  553. return NULL;
  554. }
  555. static struct ast_variable *variable_clone(const struct ast_variable *old)
  556. {
  557. struct ast_variable *new = ast_variable_new(old->name, old->value, old->file);
  558. if (new) {
  559. new->lineno = old->lineno;
  560. new->object = old->object;
  561. new->blanklines = old->blanklines;
  562. /* TODO: clone comments? */
  563. }
  564. return new;
  565. }
  566. static void move_variables(struct ast_category *old, struct ast_category *new)
  567. {
  568. struct ast_variable *var = old->root;
  569. old->root = NULL;
  570. /* we can just move the entire list in a single op */
  571. ast_variable_append(new, var);
  572. }
  573. struct ast_category *ast_category_new(const char *name, const char *in_file, int lineno)
  574. {
  575. struct ast_category *category;
  576. category = ast_calloc(1, sizeof(*category));
  577. if (!category) {
  578. return NULL;
  579. }
  580. category->file = ast_strdup(in_file);
  581. if (!category->file) {
  582. ast_category_destroy(category);
  583. return NULL;
  584. }
  585. ast_copy_string(category->name, name, sizeof(category->name));
  586. category->lineno = lineno; /* if you don't know the lineno, set it to 999999 or something real big */
  587. return category;
  588. }
  589. static struct ast_category *category_get(const struct ast_config *config, const char *category_name, int ignored)
  590. {
  591. struct ast_category *cat;
  592. /* try exact match first, then case-insensitive match */
  593. for (cat = config->root; cat; cat = cat->next) {
  594. if (cat->name == category_name && (ignored || !cat->ignored))
  595. return cat;
  596. }
  597. for (cat = config->root; cat; cat = cat->next) {
  598. if (!strcasecmp(cat->name, category_name) && (ignored || !cat->ignored))
  599. return cat;
  600. }
  601. return NULL;
  602. }
  603. struct ast_category *ast_category_get(const struct ast_config *config, const char *category_name)
  604. {
  605. return category_get(config, category_name, 0);
  606. }
  607. int ast_category_exist(const struct ast_config *config, const char *category_name)
  608. {
  609. return !!ast_category_get(config, category_name);
  610. }
  611. void ast_category_append(struct ast_config *config, struct ast_category *category)
  612. {
  613. if (config->last)
  614. config->last->next = category;
  615. else
  616. config->root = category;
  617. category->include_level = config->include_level;
  618. config->last = category;
  619. config->current = category;
  620. }
  621. int ast_category_insert(struct ast_config *config, struct ast_category *cat, const char *match)
  622. {
  623. struct ast_category *cur_category;
  624. if (!config || !cat || !match) {
  625. return -1;
  626. }
  627. if (!strcasecmp(config->root->name, match)) {
  628. cat->next = config->root;
  629. config->root = cat;
  630. return 0;
  631. }
  632. for (cur_category = config->root; cur_category && cur_category->next;
  633. cur_category = cur_category->next) {
  634. if (!strcasecmp(cur_category->next->name, match)) {
  635. cat->next = cur_category->next;
  636. cur_category->next = cat;
  637. return 0;
  638. }
  639. }
  640. return -1;
  641. }
  642. static void ast_destroy_template_list(struct ast_category *cat)
  643. {
  644. struct ast_category_template_instance *x;
  645. while ((x = AST_LIST_REMOVE_HEAD(&cat->template_instances, next)))
  646. ast_free(x);
  647. }
  648. void ast_category_destroy(struct ast_category *cat)
  649. {
  650. ast_variables_destroy(cat->root);
  651. cat->root = NULL;
  652. cat->last = NULL;
  653. ast_comment_destroy(&cat->precomments);
  654. ast_comment_destroy(&cat->sameline);
  655. ast_comment_destroy(&cat->trailing);
  656. ast_destroy_template_list(cat);
  657. ast_free(cat->file);
  658. ast_free(cat);
  659. }
  660. static void ast_includes_destroy(struct ast_config_include *incls)
  661. {
  662. struct ast_config_include *incl,*inclnext;
  663. for (incl=incls; incl; incl = inclnext) {
  664. inclnext = incl->next;
  665. ast_free(incl->include_location_file);
  666. ast_free(incl->exec_file);
  667. ast_free(incl->included_file);
  668. ast_free(incl);
  669. }
  670. }
  671. static struct ast_category *next_available_category(struct ast_category *cat)
  672. {
  673. for (; cat && cat->ignored; cat = cat->next);
  674. return cat;
  675. }
  676. /*! return the first var of a category */
  677. struct ast_variable *ast_category_first(struct ast_category *cat)
  678. {
  679. return (cat) ? cat->root : NULL;
  680. }
  681. struct ast_variable *ast_category_root(struct ast_config *config, char *cat)
  682. {
  683. struct ast_category *category = ast_category_get(config, cat);
  684. if (category)
  685. return category->root;
  686. return NULL;
  687. }
  688. void ast_config_sort_categories(struct ast_config *config, int descending,
  689. int (*comparator)(struct ast_category *p, struct ast_category *q))
  690. {
  691. /*
  692. * The contents of this function are adapted from
  693. * an example of linked list merge sorting
  694. * copyright 2001 Simon Tatham.
  695. *
  696. * Permission is hereby granted, free of charge, to any person
  697. * obtaining a copy of this software and associated documentation
  698. * files (the "Software"), to deal in the Software without
  699. * restriction, including without limitation the rights to use,
  700. * copy, modify, merge, publish, distribute, sublicense, and/or
  701. * sell copies of the Software, and to permit persons to whom the
  702. * Software is furnished to do so, subject to the following
  703. * conditions:
  704. *
  705. * The above copyright notice and this permission notice shall be
  706. * included in all copies or substantial portions of the Software.
  707. *
  708. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  709. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  710. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  711. * NONINFRINGEMENT. IN NO EVENT SHALL SIMON TATHAM BE LIABLE FOR
  712. * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  713. * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  714. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  715. * SOFTWARE.
  716. */
  717. int insize = 1;
  718. struct ast_category *p, *q, *e, *tail;
  719. int nmerges, psize, qsize, i;
  720. /* If the descending flag was sent, we'll apply inversion to the comparison function's return. */
  721. if (descending) {
  722. descending = -1;
  723. } else {
  724. descending = 1;
  725. }
  726. if (!config->root) {
  727. return;
  728. }
  729. while (1) {
  730. p = config->root;
  731. config->root = NULL;
  732. tail = NULL;
  733. nmerges = 0; /* count number of merges we do in this pass */
  734. while (p) {
  735. nmerges++; /* there exists a merge to be done */
  736. /* step `insize' places along from p */
  737. q = p;
  738. psize = 0;
  739. for (i = 0; i < insize; i++) {
  740. psize++;
  741. q = q->next;
  742. if (!q) {
  743. break;
  744. }
  745. }
  746. /* if q hasn't fallen off end, we have two lists to merge */
  747. qsize = insize;
  748. /* now we have two lists; merge them */
  749. while (psize > 0 || (qsize > 0 && q)) {
  750. /* decide whether next element of merge comes from p or q */
  751. if (psize == 0) {
  752. /* p is empty; e must come from q. */
  753. e = q;
  754. q = q->next;
  755. qsize--;
  756. } else if (qsize == 0 || !q) {
  757. /* q is empty; e must come from p. */
  758. e = p; p = p->next; psize--;
  759. } else if ((comparator(p,q) * descending) <= 0) {
  760. /* First element of p is lower (or same) e must come from p. */
  761. e = p;
  762. p = p->next;
  763. psize--;
  764. } else {
  765. /* First element of q is lower; e must come from q. */
  766. e = q;
  767. q = q->next;
  768. qsize--;
  769. }
  770. /* add the next element to the merged list */
  771. if (tail) {
  772. tail->next = e;
  773. } else {
  774. config->root = e;
  775. }
  776. tail = e;
  777. }
  778. /* now p has stepped `insize' places along, and q has too */
  779. p = q;
  780. }
  781. tail->next = NULL;
  782. /* If we have done only one merge, we're finished. */
  783. if (nmerges <= 1) { /* allow for nmerges==0, the empty list case */
  784. return;
  785. }
  786. /* Otherwise repeat, merging lists twice the size */
  787. insize *= 2;
  788. }
  789. }
  790. char *ast_category_browse(struct ast_config *config, const char *prev)
  791. {
  792. struct ast_category *cat;
  793. if (!prev) {
  794. /* First time browse. */
  795. cat = config->root;
  796. } else if (config->last_browse && (config->last_browse->name == prev)) {
  797. /* Simple last browse found. */
  798. cat = config->last_browse->next;
  799. } else {
  800. /*
  801. * Config changed since last browse.
  802. *
  803. * First try cheap last browse search. (Rebrowsing a different
  804. * previous category?)
  805. */
  806. for (cat = config->root; cat; cat = cat->next) {
  807. if (cat->name == prev) {
  808. /* Found it. */
  809. cat = cat->next;
  810. break;
  811. }
  812. }
  813. if (!cat) {
  814. /*
  815. * Have to do it the hard way. (Last category was deleted and
  816. * re-added?)
  817. */
  818. for (cat = config->root; cat; cat = cat->next) {
  819. if (!strcasecmp(cat->name, prev)) {
  820. /* Found it. */
  821. cat = cat->next;
  822. break;
  823. }
  824. }
  825. }
  826. }
  827. if (cat)
  828. cat = next_available_category(cat);
  829. config->last_browse = cat;
  830. return (cat) ? cat->name : NULL;
  831. }
  832. struct ast_variable *ast_category_detach_variables(struct ast_category *cat)
  833. {
  834. struct ast_variable *v;
  835. v = cat->root;
  836. cat->root = NULL;
  837. cat->last = NULL;
  838. return v;
  839. }
  840. void ast_category_rename(struct ast_category *cat, const char *name)
  841. {
  842. ast_copy_string(cat->name, name, sizeof(cat->name));
  843. }
  844. static void inherit_category(struct ast_category *new, const struct ast_category *base)
  845. {
  846. struct ast_variable *var;
  847. struct ast_category_template_instance *x;
  848. x = ast_calloc(1, sizeof(*x));
  849. if (!x) {
  850. return;
  851. }
  852. strcpy(x->name, base->name);
  853. x->inst = base;
  854. AST_LIST_INSERT_TAIL(&new->template_instances, x, next);
  855. for (var = base->root; var; var = var->next)
  856. ast_variable_append(new, variable_clone(var));
  857. }
  858. struct ast_config *ast_config_new(void)
  859. {
  860. struct ast_config *config;
  861. if ((config = ast_calloc(1, sizeof(*config))))
  862. config->max_include_level = MAX_INCLUDE_LEVEL;
  863. return config;
  864. }
  865. int ast_variable_delete(struct ast_category *category, const char *variable, const char *match, const char *line)
  866. {
  867. struct ast_variable *cur, *prev=NULL, *curn;
  868. int res = -1;
  869. int num_item = 0;
  870. int req_item;
  871. req_item = -1;
  872. if (!ast_strlen_zero(line)) {
  873. /* Requesting to delete by item number. */
  874. if (sscanf(line, "%30d", &req_item) != 1
  875. || req_item < 0) {
  876. /* Invalid item number to delete. */
  877. return -1;
  878. }
  879. }
  880. prev = NULL;
  881. cur = category->root;
  882. while (cur) {
  883. curn = cur->next;
  884. /* Delete by item number or by variable name with optional value. */
  885. if ((0 <= req_item && num_item == req_item)
  886. || (req_item < 0 && !strcasecmp(cur->name, variable)
  887. && (ast_strlen_zero(match) || !strcasecmp(cur->value, match)))) {
  888. if (prev) {
  889. prev->next = cur->next;
  890. if (cur == category->last)
  891. category->last = prev;
  892. } else {
  893. category->root = cur->next;
  894. if (cur == category->last)
  895. category->last = NULL;
  896. }
  897. ast_variable_destroy(cur);
  898. res = 0;
  899. } else
  900. prev = cur;
  901. cur = curn;
  902. ++num_item;
  903. }
  904. return res;
  905. }
  906. int ast_variable_update(struct ast_category *category, const char *variable,
  907. const char *value, const char *match, unsigned int object)
  908. {
  909. struct ast_variable *cur, *prev=NULL, *newer=NULL;
  910. for (cur = category->root; cur; prev = cur, cur = cur->next) {
  911. if (strcasecmp(cur->name, variable) ||
  912. (!ast_strlen_zero(match) && strcasecmp(cur->value, match)))
  913. continue;
  914. if (!(newer = ast_variable_new(variable, value, cur->file)))
  915. return -1;
  916. ast_variable_move(newer, cur);
  917. newer->object = newer->object || object;
  918. /* Replace the old node in the list with the new node. */
  919. newer->next = cur->next;
  920. if (prev)
  921. prev->next = newer;
  922. else
  923. category->root = newer;
  924. if (category->last == cur)
  925. category->last = newer;
  926. ast_variable_destroy(cur);
  927. return 0;
  928. }
  929. /* Could not find variable to update */
  930. return -1;
  931. }
  932. int ast_category_delete(struct ast_config *cfg, const char *category)
  933. {
  934. struct ast_category *prev=NULL, *cat;
  935. cat = cfg->root;
  936. while (cat) {
  937. if (cat->name == category) {
  938. if (prev) {
  939. prev->next = cat->next;
  940. if (cat == cfg->last)
  941. cfg->last = prev;
  942. } else {
  943. cfg->root = cat->next;
  944. if (cat == cfg->last)
  945. cfg->last = NULL;
  946. }
  947. ast_category_destroy(cat);
  948. return 0;
  949. }
  950. prev = cat;
  951. cat = cat->next;
  952. }
  953. prev = NULL;
  954. cat = cfg->root;
  955. while (cat) {
  956. if (!strcasecmp(cat->name, category)) {
  957. if (prev) {
  958. prev->next = cat->next;
  959. if (cat == cfg->last)
  960. cfg->last = prev;
  961. } else {
  962. cfg->root = cat->next;
  963. if (cat == cfg->last)
  964. cfg->last = NULL;
  965. }
  966. ast_category_destroy(cat);
  967. return 0;
  968. }
  969. prev = cat;
  970. cat = cat->next;
  971. }
  972. return -1;
  973. }
  974. int ast_category_empty(struct ast_config *cfg, const char *category)
  975. {
  976. struct ast_category *cat;
  977. for (cat = cfg->root; cat; cat = cat->next) {
  978. if (strcasecmp(cat->name, category))
  979. continue;
  980. ast_variables_destroy(cat->root);
  981. cat->root = NULL;
  982. cat->last = NULL;
  983. return 0;
  984. }
  985. return -1;
  986. }
  987. void ast_config_destroy(struct ast_config *cfg)
  988. {
  989. struct ast_category *cat, *catn;
  990. if (!cfg)
  991. return;
  992. ast_includes_destroy(cfg->includes);
  993. cat = cfg->root;
  994. while (cat) {
  995. catn = cat;
  996. cat = cat->next;
  997. ast_category_destroy(catn);
  998. }
  999. ast_free(cfg);
  1000. }
  1001. struct ast_category *ast_config_get_current_category(const struct ast_config *cfg)
  1002. {
  1003. return cfg->current;
  1004. }
  1005. void ast_config_set_current_category(struct ast_config *cfg, const struct ast_category *cat)
  1006. {
  1007. /* cast below is just to silence compiler warning about dropping "const" */
  1008. cfg->current = (struct ast_category *) cat;
  1009. }
  1010. /*!
  1011. * \internal
  1012. * \brief Create a new cfmtime list node.
  1013. *
  1014. * \param filename Config filename caching.
  1015. * \param who_asked Who wanted to know.
  1016. *
  1017. * \retval cfmtime New node on success.
  1018. * \retval NULL on error.
  1019. */
  1020. static struct cache_file_mtime *cfmtime_new(const char *filename, const char *who_asked)
  1021. {
  1022. struct cache_file_mtime *cfmtime;
  1023. char *dst;
  1024. cfmtime = ast_calloc(1,
  1025. sizeof(*cfmtime) + strlen(filename) + 1 + strlen(who_asked) + 1);
  1026. if (!cfmtime) {
  1027. return NULL;
  1028. }
  1029. dst = cfmtime->filename; /* writable space starts here */
  1030. strcpy(dst, filename); /* Safe */
  1031. dst += strlen(dst) + 1;
  1032. cfmtime->who_asked = strcpy(dst, who_asked); /* Safe */
  1033. return cfmtime;
  1034. }
  1035. enum config_cache_attribute_enum {
  1036. ATTRIBUTE_INCLUDE = 0,
  1037. ATTRIBUTE_EXEC = 1,
  1038. };
  1039. /*!
  1040. * \internal
  1041. * \brief Save the stat() data to the cached file modtime struct.
  1042. *
  1043. * \param cfmtime Cached file modtime.
  1044. * \param statbuf Buffer filled in by stat().
  1045. *
  1046. * \return Nothing
  1047. */
  1048. static void cfmstat_save(struct cache_file_mtime *cfmtime, struct stat *statbuf)
  1049. {
  1050. cfmtime->stat_size = statbuf->st_size;
  1051. #if defined(HAVE_STRUCT_STAT_ST_MTIM)
  1052. cfmtime->stat_mtime_nsec = statbuf->st_mtim.tv_nsec;
  1053. #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
  1054. cfmtime->stat_mtime_nsec = statbuf->st_mtimensec;
  1055. #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
  1056. cfmtime->stat_mtime_nsec = statbuf->st_mtimespec.tv_nsec;
  1057. #else
  1058. cfmtime->stat_mtime_nsec = 0;
  1059. #endif
  1060. cfmtime->stat_mtime = statbuf->st_mtime;
  1061. }
  1062. /*!
  1063. * \internal
  1064. * \brief Compare the stat() data with the cached file modtime struct.
  1065. *
  1066. * \param cfmtime Cached file modtime.
  1067. * \param statbuf Buffer filled in by stat().
  1068. *
  1069. * \retval non-zero if different.
  1070. */
  1071. static int cfmstat_cmp(struct cache_file_mtime *cfmtime, struct stat *statbuf)
  1072. {
  1073. struct cache_file_mtime cfm_buf;
  1074. cfmstat_save(&cfm_buf, statbuf);
  1075. return cfmtime->stat_size != cfm_buf.stat_size
  1076. || cfmtime->stat_mtime != cfm_buf.stat_mtime
  1077. || cfmtime->stat_mtime_nsec != cfm_buf.stat_mtime_nsec;
  1078. }
  1079. /*!
  1080. * \internal
  1081. * \brief Clear the cached file modtime include list.
  1082. *
  1083. * \param cfmtime Cached file modtime.
  1084. *
  1085. * \note cfmtime_head is assumed already locked.
  1086. *
  1087. * \return Nothing
  1088. */
  1089. static void config_cache_flush_includes(struct cache_file_mtime *cfmtime)
  1090. {
  1091. struct cache_file_include *cfinclude;
  1092. while ((cfinclude = AST_LIST_REMOVE_HEAD(&cfmtime->includes, list))) {
  1093. ast_free(cfinclude);
  1094. }
  1095. }
  1096. /*!
  1097. * \internal
  1098. * \brief Destroy the given cached file modtime entry.
  1099. *
  1100. * \param cfmtime Cached file modtime.
  1101. *
  1102. * \note cfmtime_head is assumed already locked.
  1103. *
  1104. * \return Nothing
  1105. */
  1106. static void config_cache_destroy_entry(struct cache_file_mtime *cfmtime)
  1107. {
  1108. config_cache_flush_includes(cfmtime);
  1109. ast_free(cfmtime);
  1110. }
  1111. /*!
  1112. * \internal
  1113. * \brief Remove and destroy the config cache entry for the filename and who_asked.
  1114. *
  1115. * \param filename Config filename.
  1116. * \param who_asked Which module asked.
  1117. *
  1118. * \return Nothing
  1119. */
  1120. static void config_cache_remove(const char *filename, const char *who_asked)
  1121. {
  1122. struct cache_file_mtime *cfmtime;
  1123. AST_LIST_LOCK(&cfmtime_head);
  1124. AST_LIST_TRAVERSE_SAFE_BEGIN(&cfmtime_head, cfmtime, list) {
  1125. if (!strcmp(cfmtime->filename, filename)
  1126. && !strcmp(cfmtime->who_asked, who_asked)) {
  1127. AST_LIST_REMOVE_CURRENT(list);
  1128. config_cache_destroy_entry(cfmtime);
  1129. break;
  1130. }
  1131. }
  1132. AST_LIST_TRAVERSE_SAFE_END;
  1133. AST_LIST_UNLOCK(&cfmtime_head);
  1134. }
  1135. static void config_cache_attribute(const char *configfile, enum config_cache_attribute_enum attrtype, const char *filename, const char *who_asked)
  1136. {
  1137. struct cache_file_mtime *cfmtime;
  1138. struct cache_file_include *cfinclude;
  1139. /* Find our cached entry for this configuration file */
  1140. AST_LIST_LOCK(&cfmtime_head);
  1141. AST_LIST_TRAVERSE(&cfmtime_head, cfmtime, list) {
  1142. if (!strcmp(cfmtime->filename, configfile) && !strcmp(cfmtime->who_asked, who_asked))
  1143. break;
  1144. }
  1145. if (!cfmtime) {
  1146. cfmtime = cfmtime_new(configfile, who_asked);
  1147. if (!cfmtime) {
  1148. AST_LIST_UNLOCK(&cfmtime_head);
  1149. return;
  1150. }
  1151. /* Note that the file mtime is initialized to 0, i.e. 1970 */
  1152. AST_LIST_INSERT_SORTALPHA(&cfmtime_head, cfmtime, list, filename);
  1153. }
  1154. switch (attrtype) {
  1155. case ATTRIBUTE_INCLUDE:
  1156. AST_LIST_TRAVERSE(&cfmtime->includes, cfinclude, list) {
  1157. if (!strcmp(cfinclude->include, filename)) {
  1158. AST_LIST_UNLOCK(&cfmtime_head);
  1159. return;
  1160. }
  1161. }
  1162. cfinclude = ast_calloc(1, sizeof(*cfinclude) + strlen(filename) + 1);
  1163. if (!cfinclude) {
  1164. AST_LIST_UNLOCK(&cfmtime_head);
  1165. return;
  1166. }
  1167. strcpy(cfinclude->include, filename); /* Safe */
  1168. AST_LIST_INSERT_TAIL(&cfmtime->includes, cfinclude, list);
  1169. break;
  1170. case ATTRIBUTE_EXEC:
  1171. cfmtime->has_exec = 1;
  1172. break;
  1173. }
  1174. AST_LIST_UNLOCK(&cfmtime_head);
  1175. }
  1176. /*! \brief parse one line in the configuration.
  1177. * \verbatim
  1178. * We can have a category header [foo](...)
  1179. * a directive #include / #exec
  1180. * or a regular line name = value
  1181. * \endverbatim
  1182. */
  1183. static int process_text_line(struct ast_config *cfg, struct ast_category **cat,
  1184. char *buf, int lineno, const char *configfile, struct ast_flags flags,
  1185. struct ast_str *comment_buffer,
  1186. struct ast_str *lline_buffer,
  1187. const char *suggested_include_file,
  1188. struct ast_category **last_cat, struct ast_variable **last_var, const char *who_asked)
  1189. {
  1190. char *c;
  1191. char *cur = buf;
  1192. struct ast_variable *v;
  1193. char cmd[512], exec_file[512];
  1194. /* Actually parse the entry */
  1195. if (cur[0] == '[') { /* A category header */
  1196. /* format is one of the following:
  1197. * [foo] define a new category named 'foo'
  1198. * [foo](!) define a new template category named 'foo'
  1199. * [foo](+) append to category 'foo', error if foo does not exist.
  1200. * [foo](a) define a new category and inherit from category or template a.
  1201. * You can put a comma-separated list of categories and templates
  1202. * and '!' and '+' between parentheses, with obvious meaning.
  1203. */
  1204. struct ast_category *newcat = NULL;
  1205. char *catname;
  1206. c = strchr(cur, ']');
  1207. if (!c) {
  1208. ast_log(LOG_WARNING, "parse error: no closing ']', line %d of %s\n", lineno, configfile);
  1209. return -1;
  1210. }
  1211. *c++ = '\0';
  1212. cur++;
  1213. if (*c++ != '(')
  1214. c = NULL;
  1215. catname = cur;
  1216. if (!(*cat = newcat = ast_category_new(catname,
  1217. S_OR(suggested_include_file, cfg->include_level == 1 ? "" : configfile),
  1218. lineno))) {
  1219. return -1;
  1220. }
  1221. (*cat)->lineno = lineno;
  1222. *last_var = 0;
  1223. *last_cat = newcat;
  1224. /* add comments */
  1225. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS))
  1226. newcat->precomments = ALLOC_COMMENT(comment_buffer);
  1227. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS))
  1228. newcat->sameline = ALLOC_COMMENT(lline_buffer);
  1229. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS))
  1230. CB_RESET(comment_buffer, lline_buffer);
  1231. /* If there are options or categories to inherit from, process them now */
  1232. if (c) {
  1233. if (!(cur = strchr(c, ')'))) {
  1234. ast_log(LOG_WARNING, "parse error: no closing ')', line %d of %s\n", lineno, configfile);
  1235. return -1;
  1236. }
  1237. *cur = '\0';
  1238. while ((cur = strsep(&c, ","))) {
  1239. if (!strcasecmp(cur, "!")) {
  1240. (*cat)->ignored = 1;
  1241. } else if (!strcasecmp(cur, "+")) {
  1242. *cat = category_get(cfg, catname, 1);
  1243. if (!(*cat)) {
  1244. if (newcat)
  1245. ast_category_destroy(newcat);
  1246. ast_log(LOG_WARNING, "Category addition requested, but category '%s' does not exist, line %d of %s\n", catname, lineno, configfile);
  1247. return -1;
  1248. }
  1249. if (newcat) {
  1250. move_variables(newcat, *cat);
  1251. ast_category_destroy(newcat);
  1252. newcat = NULL;
  1253. }
  1254. } else {
  1255. struct ast_category *base;
  1256. base = category_get(cfg, cur, 1);
  1257. if (!base) {
  1258. ast_log(LOG_WARNING, "Inheritance requested, but category '%s' does not exist, line %d of %s\n", cur, lineno, configfile);
  1259. return -1;
  1260. }
  1261. inherit_category(*cat, base);
  1262. }
  1263. }
  1264. }
  1265. if (newcat)
  1266. ast_category_append(cfg, *cat);
  1267. } else if (cur[0] == '#') { /* A directive - #include or #exec */
  1268. char *cur2;
  1269. char real_inclusion_name[256];
  1270. int do_include = 0; /* otherwise, it is exec */
  1271. int try_include = 0;
  1272. cur++;
  1273. c = cur;
  1274. while (*c && (*c > 32)) {
  1275. c++;
  1276. }
  1277. if (*c) {
  1278. *c = '\0';
  1279. /* Find real argument */
  1280. c = ast_strip(c + 1);
  1281. if (!(*c)) {
  1282. c = NULL;
  1283. }
  1284. } else {
  1285. c = NULL;
  1286. }
  1287. if (!strcasecmp(cur, "include")) {
  1288. do_include = 1;
  1289. } else if (!strcasecmp(cur, "tryinclude")) {
  1290. do_include = 1;
  1291. try_include = 1;
  1292. } else if (!strcasecmp(cur, "exec")) {
  1293. if (!ast_opt_exec_includes) {
  1294. ast_log(LOG_WARNING, "Cannot perform #exec unless execincludes option is enabled in asterisk.conf (options section)!\n");
  1295. return 0; /* XXX is this correct ? or we should return -1 ? */
  1296. }
  1297. } else {
  1298. ast_log(LOG_WARNING, "Unknown directive '#%s' at line %d of %s\n", cur, lineno, configfile);
  1299. return 0; /* XXX is this correct ? or we should return -1 ? */
  1300. }
  1301. if (c == NULL) {
  1302. ast_log(LOG_WARNING, "Directive '#%s' needs an argument (%s) at line %d of %s\n",
  1303. do_include ? "include / tryinclude" : "exec",
  1304. do_include ? "filename" : "/path/to/executable",
  1305. lineno,
  1306. configfile);
  1307. return 0; /* XXX is this correct ? or we should return -1 ? */
  1308. }
  1309. cur = c;
  1310. /* Strip off leading and trailing "'s and <>'s */
  1311. /* Dequote */
  1312. if ((*c == '"') || (*c == '<')) {
  1313. char quote_char = *c;
  1314. if (quote_char == '<') {
  1315. quote_char = '>';
  1316. }
  1317. if (*(c + strlen(c) - 1) == quote_char) {
  1318. cur++;
  1319. *(c + strlen(c) - 1) = '\0';
  1320. }
  1321. }
  1322. cur2 = cur;
  1323. /* #exec </path/to/executable>
  1324. We create a tmp file, then we #include it, then we delete it. */
  1325. if (!do_include) {
  1326. struct timeval now = ast_tvnow();
  1327. if (!ast_test_flag(&flags, CONFIG_FLAG_NOCACHE))
  1328. config_cache_attribute(configfile, ATTRIBUTE_EXEC, NULL, who_asked);
  1329. snprintf(exec_file, sizeof(exec_file), "/var/tmp/exec.%d%d.%ld", (int)now.tv_sec, (int)now.tv_usec, (long)pthread_self());
  1330. snprintf(cmd, sizeof(cmd), "%s > %s 2>&1", cur, exec_file);
  1331. ast_safe_system(cmd);
  1332. cur = exec_file;
  1333. } else {
  1334. if (!ast_test_flag(&flags, CONFIG_FLAG_NOCACHE))
  1335. config_cache_attribute(configfile, ATTRIBUTE_INCLUDE, cur, who_asked);
  1336. exec_file[0] = '\0';
  1337. }
  1338. /* A #include */
  1339. /* record this inclusion */
  1340. ast_include_new(cfg, cfg->include_level == 1 ? "" : configfile, cur, !do_include, cur2, lineno, real_inclusion_name, sizeof(real_inclusion_name));
  1341. do_include = ast_config_internal_load(cur, cfg, flags, real_inclusion_name, who_asked) ? 1 : 0;
  1342. if (!ast_strlen_zero(exec_file))
  1343. unlink(exec_file);
  1344. if (!do_include && !try_include) {
  1345. ast_log(LOG_ERROR, "The file '%s' was listed as a #include but it does not exist.\n", cur);
  1346. return -1;
  1347. }
  1348. /* XXX otherwise what ? the default return is 0 anyways */
  1349. } else {
  1350. /* Just a line (variable = value) */
  1351. int object = 0;
  1352. int is_escaped;
  1353. if (!(*cat)) {
  1354. ast_log(LOG_WARNING,
  1355. "parse error: No category context for line %d of %s\n", lineno, configfile);
  1356. return -1;
  1357. }
  1358. is_escaped = cur[0] == '\\';
  1359. if (is_escaped) {
  1360. /* First character is escaped. */
  1361. ++cur;
  1362. if (cur[0] < 33) {
  1363. ast_log(LOG_ERROR, "Invalid escape in line %d of %s\n", lineno, configfile);
  1364. return -1;
  1365. }
  1366. }
  1367. c = strchr(cur + is_escaped, '=');
  1368. if (c && c > cur + is_escaped && (*(c - 1) == '+')) {
  1369. struct ast_variable *var, *replace = NULL;
  1370. struct ast_str **str = ast_threadstorage_get(&appendbuf, sizeof(*str));
  1371. if (!str || !*str) {
  1372. return -1;
  1373. }
  1374. *(c - 1) = '\0';
  1375. c++;
  1376. cur = ast_strip(cur);
  1377. /* Must iterate through category until we find last variable of same name (since there could be multiple) */
  1378. for (var = ast_category_first(*cat); var; var = var->next) {
  1379. if (!strcmp(var->name, cur)) {
  1380. replace = var;
  1381. }
  1382. }
  1383. if (!replace) {
  1384. /* Nothing to replace; just set a variable normally. */
  1385. goto set_new_variable;
  1386. }
  1387. ast_str_set(str, 0, "%s", replace->value);
  1388. ast_str_append(str, 0, "%s", c);
  1389. ast_str_trim_blanks(*str);
  1390. ast_variable_update(*cat, replace->name, ast_skip_blanks(ast_str_buffer(*str)), replace->value, object);
  1391. } else if (c) {
  1392. *c = 0;
  1393. c++;
  1394. /* Ignore > in => */
  1395. if (*c== '>') {
  1396. object = 1;
  1397. c++;
  1398. }
  1399. cur = ast_strip(cur);
  1400. set_new_variable:
  1401. if (ast_strlen_zero(cur)) {
  1402. ast_log(LOG_WARNING, "No variable name in line %d of %s\n", lineno, configfile);
  1403. } else if ((v = ast_variable_new(cur, ast_strip(c), S_OR(suggested_include_file, cfg->include_level == 1 ? "" : configfile)))) {
  1404. v->lineno = lineno;
  1405. v->object = object;
  1406. *last_cat = 0;
  1407. *last_var = v;
  1408. /* Put and reset comments */
  1409. v->blanklines = 0;
  1410. ast_variable_append(*cat, v);
  1411. /* add comments */
  1412. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS))
  1413. v->precomments = ALLOC_COMMENT(comment_buffer);
  1414. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS))
  1415. v->sameline = ALLOC_COMMENT(lline_buffer);
  1416. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS))
  1417. CB_RESET(comment_buffer, lline_buffer);
  1418. } else {
  1419. return -1;
  1420. }
  1421. } else {
  1422. ast_log(LOG_WARNING, "No '=' (equal sign) in line %d of %s\n", lineno, configfile);
  1423. }
  1424. }
  1425. return 0;
  1426. }
  1427. static struct ast_config *config_text_file_load(const char *database, const char *table, const char *filename, struct ast_config *cfg, struct ast_flags flags, const char *suggested_include_file, const char *who_asked)
  1428. {
  1429. char fn[256];
  1430. #if defined(LOW_MEMORY)
  1431. char buf[512];
  1432. #else
  1433. char buf[8192];
  1434. #endif
  1435. char *new_buf, *comment_p, *process_buf;
  1436. FILE *f;
  1437. int lineno=0;
  1438. int comment = 0, nest[MAX_NESTED_COMMENTS];
  1439. struct ast_category *cat = NULL;
  1440. int count = 0;
  1441. struct stat statbuf;
  1442. struct cache_file_mtime *cfmtime = NULL;
  1443. struct cache_file_include *cfinclude;
  1444. struct ast_variable *last_var = 0;
  1445. struct ast_category *last_cat = 0;
  1446. /*! Growable string buffer */
  1447. struct ast_str *comment_buffer = NULL; /*!< this will be a comment collector.*/
  1448. struct ast_str *lline_buffer = NULL; /*!< A buffer for stuff behind the ; */
  1449. if (cfg)
  1450. cat = ast_config_get_current_category(cfg);
  1451. if (filename[0] == '/') {
  1452. ast_copy_string(fn, filename, sizeof(fn));
  1453. } else {
  1454. snprintf(fn, sizeof(fn), "%s/%s", ast_config_AST_CONFIG_DIR, filename);
  1455. }
  1456. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS)) {
  1457. comment_buffer = ast_str_create(CB_SIZE);
  1458. if (comment_buffer)
  1459. lline_buffer = ast_str_create(CB_SIZE);
  1460. if (!lline_buffer) {
  1461. ast_free(comment_buffer);
  1462. ast_log(LOG_ERROR, "Failed to initialize the comment buffer!\n");
  1463. return NULL;
  1464. }
  1465. }
  1466. #ifdef AST_INCLUDE_GLOB
  1467. {
  1468. int glob_ret;
  1469. glob_t globbuf;
  1470. globbuf.gl_offs = 0; /* initialize it to silence gcc */
  1471. glob_ret = glob(fn, MY_GLOB_FLAGS, NULL, &globbuf);
  1472. if (glob_ret == GLOB_NOSPACE) {
  1473. ast_log(LOG_WARNING,
  1474. "Glob Expansion of pattern '%s' failed: Not enough memory\n", fn);
  1475. } else if (glob_ret == GLOB_ABORTED) {
  1476. ast_log(LOG_WARNING,
  1477. "Glob Expansion of pattern '%s' failed: Read error\n", fn);
  1478. } else {
  1479. /* loop over expanded files */
  1480. int i;
  1481. if (!cfg && (globbuf.gl_pathc != 1 || strcmp(fn, globbuf.gl_pathv[0]))) {
  1482. /*
  1483. * We just want a file changed answer and since we cannot
  1484. * tell if a file was deleted with wildcard matching we will
  1485. * assume that something has always changed. Also without
  1486. * a lot of refactoring we couldn't check more than one file
  1487. * for changes in the glob loop anyway.
  1488. */
  1489. globfree(&globbuf);
  1490. ast_free(comment_buffer);
  1491. ast_free(lline_buffer);
  1492. return NULL;
  1493. }
  1494. for (i=0; i<globbuf.gl_pathc; i++) {
  1495. ast_copy_string(fn, globbuf.gl_pathv[i], sizeof(fn));
  1496. #endif
  1497. /*
  1498. * The following is not a loop, but just a convenient way to define a block
  1499. * (using do { } while(0) ), and be able to exit from it with 'continue'
  1500. * or 'break' in case of errors. Nice trick.
  1501. */
  1502. do {
  1503. if (stat(fn, &statbuf)) {
  1504. if (!ast_test_flag(&flags, CONFIG_FLAG_NOCACHE)) {
  1505. config_cache_remove(fn, who_asked);
  1506. }
  1507. continue;
  1508. }
  1509. if (!S_ISREG(statbuf.st_mode)) {
  1510. ast_log(LOG_WARNING, "'%s' is not a regular file, ignoring\n", fn);
  1511. if (!ast_test_flag(&flags, CONFIG_FLAG_NOCACHE)) {
  1512. config_cache_remove(fn, who_asked);
  1513. }
  1514. continue;
  1515. }
  1516. if (!ast_test_flag(&flags, CONFIG_FLAG_NOCACHE)) {
  1517. /* Find our cached entry for this configuration file */
  1518. AST_LIST_LOCK(&cfmtime_head);
  1519. AST_LIST_TRAVERSE(&cfmtime_head, cfmtime, list) {
  1520. if (!strcmp(cfmtime->filename, fn) && !strcmp(cfmtime->who_asked, who_asked))
  1521. break;
  1522. }
  1523. if (!cfmtime) {
  1524. cfmtime = cfmtime_new(fn, who_asked);
  1525. if (!cfmtime) {
  1526. AST_LIST_UNLOCK(&cfmtime_head);
  1527. continue;
  1528. }
  1529. /* Note that the file mtime is initialized to 0, i.e. 1970 */
  1530. AST_LIST_INSERT_SORTALPHA(&cfmtime_head, cfmtime, list, filename);
  1531. }
  1532. }
  1533. if (cfmtime
  1534. && !cfmtime->has_exec
  1535. && !cfmstat_cmp(cfmtime, &statbuf)
  1536. && ast_test_flag(&flags, CONFIG_FLAG_FILEUNCHANGED)) {
  1537. int unchanged = 1;
  1538. /* File is unchanged, what about the (cached) includes (if any)? */
  1539. AST_LIST_TRAVERSE(&cfmtime->includes, cfinclude, list) {
  1540. if (!config_text_file_load(NULL, NULL, cfinclude->include,
  1541. NULL, flags, "", who_asked)) {
  1542. /* One change is enough to short-circuit and reload the whole shebang */
  1543. unchanged = 0;
  1544. break;
  1545. }
  1546. }
  1547. if (unchanged) {
  1548. AST_LIST_UNLOCK(&cfmtime_head);
  1549. #ifdef AST_INCLUDE_GLOB
  1550. globfree(&globbuf);
  1551. #endif
  1552. ast_free(comment_buffer);
  1553. ast_free(lline_buffer);
  1554. return CONFIG_STATUS_FILEUNCHANGED;
  1555. }
  1556. }
  1557. /* If cfg is NULL, then we just want a file changed answer. */
  1558. if (cfg == NULL) {
  1559. if (cfmtime) {
  1560. AST_LIST_UNLOCK(&cfmtime_head);
  1561. }
  1562. continue;
  1563. }
  1564. if (cfmtime) {
  1565. /* Forget about what we thought we knew about this file's includes. */
  1566. cfmtime->has_exec = 0;
  1567. config_cache_flush_includes(cfmtime);
  1568. cfmstat_save(cfmtime, &statbuf);
  1569. AST_LIST_UNLOCK(&cfmtime_head);
  1570. }
  1571. if (!(f = fopen(fn, "r"))) {
  1572. ast_debug(1, "No file to parse: %s\n", fn);
  1573. ast_verb(2, "Parsing '%s': Not found (%s)\n", fn, strerror(errno));
  1574. continue;
  1575. }
  1576. count++;
  1577. /* If we get to this point, then we're loading regardless */
  1578. ast_clear_flag(&flags, CONFIG_FLAG_FILEUNCHANGED);
  1579. ast_debug(1, "Parsing %s\n", fn);
  1580. ast_verb(2, "Parsing '%s': Found\n", fn);
  1581. while (!feof(f)) {
  1582. lineno++;
  1583. if (fgets(buf, sizeof(buf), f)) {
  1584. /* Skip lines that are too long */
  1585. if (strlen(buf) == sizeof(buf) - 1 && buf[sizeof(buf) - 1] != '\n') {
  1586. ast_log(LOG_WARNING, "Line %d too long, skipping. It begins with: %.32s...\n", lineno, buf);
  1587. while (fgets(buf, sizeof(buf), f)) {
  1588. if (strlen(buf) != sizeof(buf) - 1 || buf[sizeof(buf) - 1] == '\n') {
  1589. break;
  1590. }
  1591. }
  1592. continue;
  1593. }
  1594. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS) && lline_buffer && ast_str_strlen(lline_buffer)) {
  1595. CB_ADD(&comment_buffer, ast_str_buffer(lline_buffer)); /* add the current lline buffer to the comment buffer */
  1596. ast_str_reset(lline_buffer); /* erase the lline buffer */
  1597. }
  1598. new_buf = buf;
  1599. if (comment)
  1600. process_buf = NULL;
  1601. else
  1602. process_buf = buf;
  1603. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS) && comment_buffer && ast_str_strlen(comment_buffer) && (ast_strlen_zero(buf) || strlen(buf) == strspn(buf," \t\n\r"))) {
  1604. /* blank line? really? Can we add it to an existing comment and maybe preserve inter- and post- comment spacing? */
  1605. CB_ADD(&comment_buffer, "\n"); /* add a newline to the comment buffer */
  1606. continue; /* go get a new line, then */
  1607. }
  1608. while ((comment_p = strchr(new_buf, COMMENT_META))) {
  1609. if ((comment_p > new_buf) && (*(comment_p - 1) == '\\')) {
  1610. /* Escaped semicolons aren't comments. */
  1611. new_buf = comment_p;
  1612. /* write over the \ and bring the null terminator with us */
  1613. memmove(comment_p - 1, comment_p, strlen(comment_p) + 1);
  1614. } else if (comment_p[1] == COMMENT_TAG && comment_p[2] == COMMENT_TAG && (comment_p[3] != '-')) {
  1615. /* Meta-Comment start detected ";--" */
  1616. if (comment < MAX_NESTED_COMMENTS) {
  1617. *comment_p = '\0';
  1618. new_buf = comment_p + 3;
  1619. comment++;
  1620. nest[comment-1] = lineno;
  1621. } else {
  1622. ast_log(LOG_ERROR, "Maximum nest limit of %d reached.\n", MAX_NESTED_COMMENTS);
  1623. }
  1624. } else if ((comment_p >= new_buf + 2) &&
  1625. (*(comment_p - 1) == COMMENT_TAG) &&
  1626. (*(comment_p - 2) == COMMENT_TAG)) {
  1627. /* Meta-Comment end detected "--;" */
  1628. comment--;
  1629. new_buf = comment_p + 1;
  1630. if (!comment) {
  1631. /* Back to non-comment now */
  1632. if (process_buf) {
  1633. /* Actually have to move what's left over the top, then continue */
  1634. char *oldptr;
  1635. oldptr = process_buf + strlen(process_buf);
  1636. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS)) {
  1637. CB_ADD(&comment_buffer, ";");
  1638. CB_ADD_LEN(&comment_buffer, oldptr+1, new_buf-oldptr-1);
  1639. }
  1640. memmove(oldptr, new_buf, strlen(new_buf) + 1);
  1641. new_buf = oldptr;
  1642. } else
  1643. process_buf = new_buf;
  1644. }
  1645. } else {
  1646. if (!comment) {
  1647. /* If ; is found, and we are not nested in a comment,
  1648. we immediately stop all comment processing */
  1649. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS)) {
  1650. CB_ADD(&lline_buffer, comment_p);
  1651. }
  1652. *comment_p = '\0';
  1653. new_buf = comment_p;
  1654. } else
  1655. new_buf = comment_p + 1;
  1656. }
  1657. }
  1658. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS) && comment && !process_buf ) {
  1659. CB_ADD(&comment_buffer, buf); /* the whole line is a comment, store it */
  1660. }
  1661. if (process_buf) {
  1662. char *buffer = ast_strip(process_buf);
  1663. if (!ast_strlen_zero(buffer)) {
  1664. if (process_text_line(cfg, &cat, buffer, lineno, fn, flags, comment_buffer, lline_buffer, suggested_include_file, &last_cat, &last_var, who_asked)) {
  1665. cfg = CONFIG_STATUS_FILEINVALID;
  1666. break;
  1667. }
  1668. }
  1669. }
  1670. }
  1671. }
  1672. /* end of file-- anything in a comment buffer? */
  1673. if (last_cat) {
  1674. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS) && comment_buffer && ast_str_strlen(comment_buffer)) {
  1675. if (lline_buffer && ast_str_strlen(lline_buffer)) {
  1676. CB_ADD(&comment_buffer, ast_str_buffer(lline_buffer)); /* add the current lline buffer to the comment buffer */
  1677. ast_str_reset(lline_buffer); /* erase the lline buffer */
  1678. }
  1679. last_cat->trailing = ALLOC_COMMENT(comment_buffer);
  1680. }
  1681. } else if (last_var) {
  1682. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS) && comment_buffer && ast_str_strlen(comment_buffer)) {
  1683. if (lline_buffer && ast_str_strlen(lline_buffer)) {
  1684. CB_ADD(&comment_buffer, ast_str_buffer(lline_buffer)); /* add the current lline buffer to the comment buffer */
  1685. ast_str_reset(lline_buffer); /* erase the lline buffer */
  1686. }
  1687. last_var->trailing = ALLOC_COMMENT(comment_buffer);
  1688. }
  1689. } else {
  1690. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS) && comment_buffer && ast_str_strlen(comment_buffer)) {
  1691. ast_debug(1, "Nothing to attach comments to, discarded: %s\n", ast_str_buffer(comment_buffer));
  1692. }
  1693. }
  1694. if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS))
  1695. CB_RESET(comment_buffer, lline_buffer);
  1696. fclose(f);
  1697. } while (0);
  1698. if (comment) {
  1699. ast_log(LOG_WARNING,"Unterminated comment detected beginning on line %d\n", nest[comment - 1]);
  1700. }
  1701. #ifdef AST_INCLUDE_GLOB
  1702. if (cfg == NULL || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
  1703. break;
  1704. }
  1705. }
  1706. globfree(&globbuf);
  1707. }
  1708. }
  1709. #endif
  1710. ast_free(comment_buffer);
  1711. ast_free(lline_buffer);
  1712. if (count == 0)
  1713. return NULL;
  1714. return cfg;
  1715. }
  1716. /* NOTE: categories and variables each have a file and lineno attribute. On a save operation, these are used to determine
  1717. which file and line number to write out to. Thus, an entire hierarchy of config files (via #include statements) can be
  1718. recreated. BUT, care must be taken to make sure that every cat and var has the proper file name stored, or you may
  1719. be shocked and mystified as to why things are not showing up in the files!
  1720. Also, All #include/#exec statements are recorded in the "includes" LL in the ast_config structure. The file name
  1721. and line number are stored for each include, plus the name of the file included, so that these statements may be
  1722. included in the output files on a file_save operation.
  1723. The lineno's are really just for relative placement in the file. There is no attempt to make sure that blank lines
  1724. are included to keep the lineno's the same between input and output. The lineno fields are used mainly to determine
  1725. the position of the #include and #exec directives. So, blank lines tend to disappear from a read/rewrite operation,
  1726. and a header gets added.
  1727. vars and category heads are output in the order they are stored in the config file. So, if the software
  1728. shuffles these at all, then the placement of #include directives might get a little mixed up, because the
  1729. file/lineno data probably won't get changed.
  1730. */
  1731. static void gen_header(FILE *f1, const char *configfile, const char *fn, const char *generator)
  1732. {
  1733. char date[256]="";
  1734. time_t t;
  1735. time(&t);
  1736. ast_copy_string(date, ctime(&t), sizeof(date));
  1737. fprintf(f1, ";!\n");
  1738. fprintf(f1, ";! Automatically generated configuration file\n");
  1739. if (strcmp(configfile, fn))
  1740. fprintf(f1, ";! Filename: %s (%s)\n", configfile, fn);
  1741. else
  1742. fprintf(f1, ";! Filename: %s\n", configfile);
  1743. fprintf(f1, ";! Generator: %s\n", generator);
  1744. fprintf(f1, ";! Creation Date: %s", date);
  1745. fprintf(f1, ";!\n");
  1746. }
  1747. static void inclfile_destroy(void *obj)
  1748. {
  1749. const struct inclfile *o = obj;
  1750. ast_free(o->fname);
  1751. }
  1752. static void make_fn(char *fn, size_t fn_size, const char *file, const char *configfile)
  1753. {
  1754. if (ast_strlen_zero(file)) {
  1755. if (configfile[0] == '/') {
  1756. ast_copy_string(fn, configfile, fn_size);
  1757. } else {
  1758. snprintf(fn, fn_size, "%s/%s", ast_config_AST_CONFIG_DIR, configfile);
  1759. }
  1760. } else if (file[0] == '/') {
  1761. ast_copy_string(fn, file, fn_size);
  1762. } else {
  1763. snprintf(fn, fn_size, "%s/%s", ast_config_AST_CONFIG_DIR, file);
  1764. }
  1765. }
  1766. static struct inclfile *set_fn(char *fn, size_t fn_size, const char *file, const char *configfile, struct ao2_container *fileset)
  1767. {
  1768. struct inclfile lookup;
  1769. struct inclfile *fi;
  1770. make_fn(fn, fn_size, file, configfile);
  1771. lookup.fname = fn;
  1772. fi = ao2_find(fileset, &lookup, OBJ_POINTER);
  1773. if (fi) {
  1774. /* Found existing include file scratch pad. */
  1775. return fi;
  1776. }
  1777. /* set up a file scratch pad */
  1778. fi = ao2_alloc(sizeof(struct inclfile), inclfile_destroy);
  1779. if (!fi) {
  1780. /* Scratch pad creation failed. */
  1781. return NULL;
  1782. }
  1783. fi->fname = ast_strdup(fn);
  1784. if (!fi->fname) {
  1785. /* Scratch pad creation failed. */
  1786. ao2_ref(fi, -1);
  1787. return NULL;
  1788. }
  1789. fi->lineno = 1;
  1790. ao2_link(fileset, fi);
  1791. return fi;
  1792. }
  1793. static int count_linefeeds(char *str)
  1794. {
  1795. int count = 0;
  1796. while (*str) {
  1797. if (*str =='\n')
  1798. count++;
  1799. str++;
  1800. }
  1801. return count;
  1802. }
  1803. static int count_linefeeds_in_comments(struct ast_comment *x)
  1804. {
  1805. int count = 0;
  1806. while (x) {
  1807. count += count_linefeeds(x->cmt);
  1808. x = x->next;
  1809. }
  1810. return count;
  1811. }
  1812. static void insert_leading_blank_lines(FILE *fp, struct inclfile *fi, struct ast_comment *precomments, int lineno)
  1813. {
  1814. int precomment_lines;
  1815. int i;
  1816. if (!fi) {
  1817. /* No file scratch pad object so insert no blank lines. */
  1818. return;
  1819. }
  1820. precomment_lines = count_linefeeds_in_comments(precomments);
  1821. /* I don't have to worry about those ;! comments, they are
  1822. stored in the precomments, but not printed back out.
  1823. I did have to make sure that comments following
  1824. the ;! header comments were not also deleted in the process */
  1825. if (lineno - precomment_lines - fi->lineno < 0) { /* insertions can mess up the line numbering and produce negative numbers that mess things up */
  1826. return;
  1827. } else if (lineno == 0) {
  1828. /* Line replacements also mess things up */
  1829. return;
  1830. } else if (lineno - precomment_lines - fi->lineno < 5) {
  1831. /* Only insert less than 5 blank lines; if anything more occurs,
  1832. * it's probably due to context deletion. */
  1833. for (i = fi->lineno; i < lineno - precomment_lines; i++) {
  1834. fprintf(fp, "\n");
  1835. }
  1836. } else {
  1837. /* Deletion occurred - insert a single blank line, for separation of
  1838. * contexts. */
  1839. fprintf(fp, "\n");
  1840. }
  1841. fi->lineno = lineno + 1; /* Advance the file lineno */
  1842. }
  1843. int config_text_file_save(const char *configfile, const struct ast_config *cfg, const char *generator)
  1844. {
  1845. return ast_config_text_file_save(configfile, cfg, generator);
  1846. }
  1847. int ast_config_text_file_save(const char *configfile, const struct ast_config *cfg, const char *generator)
  1848. {
  1849. FILE *f;
  1850. char fn[PATH_MAX];
  1851. struct ast_variable *var;
  1852. struct ast_category *cat;
  1853. struct ast_comment *cmt;
  1854. struct ast_config_include *incl;
  1855. int blanklines = 0;
  1856. struct ao2_container *fileset;
  1857. struct inclfile *fi;
  1858. fileset = ao2_container_alloc(1023, hash_string, hashtab_compare_strings);
  1859. if (!fileset) {
  1860. /* Container creation failed. */
  1861. return -1;
  1862. }
  1863. /* Check all the files for write access before attempting to modify any of them */
  1864. for (incl = cfg->includes; incl; incl = incl->next) {
  1865. /* reset all the output flags in case this isn't our first time saving this data */
  1866. incl->output = 0;
  1867. /* now make sure we have write access */
  1868. if (!incl->exec) {
  1869. make_fn(fn, sizeof(fn), incl->included_file, configfile);
  1870. if (access(fn, R_OK | W_OK)) {
  1871. ast_log(LOG_ERROR, "Unable to write %s (%s)\n", fn, strerror(errno));
  1872. return -1;
  1873. }
  1874. }
  1875. }
  1876. /* now make sure we have write access to the main config file */
  1877. make_fn(fn, sizeof(fn), 0, configfile);
  1878. if (access(fn, R_OK | W_OK)) {
  1879. ast_log(LOG_ERROR, "Unable to write %s (%s)\n", fn, strerror(errno));
  1880. return -1;
  1881. }
  1882. /* Now that we know we have write access to all files, it's safe to start truncating them */
  1883. /* go thru all the inclusions and make sure all the files involved (configfile plus all its inclusions)
  1884. are all truncated to zero bytes and have that nice header*/
  1885. for (incl = cfg->includes; incl; incl = incl->next) {
  1886. if (!incl->exec) { /* leave the execs alone -- we'll write out the #exec directives, but won't zero out the include files or exec files*/
  1887. /* normally, fn is just set to incl->included_file, prepended with config dir if relative */
  1888. fi = set_fn(fn, sizeof(fn), incl->included_file, configfile, fileset);
  1889. f = fopen(fn, "w");
  1890. if (f) {
  1891. gen_header(f, configfile, fn, generator);
  1892. fclose(f); /* this should zero out the file */
  1893. } else {
  1894. ast_log(LOG_ERROR, "Unable to write %s (%s)\n", fn, strerror(errno));
  1895. }
  1896. if (fi) {
  1897. ao2_ref(fi, -1);
  1898. }
  1899. }
  1900. }
  1901. /* just set fn to absolute ver of configfile */
  1902. fi = set_fn(fn, sizeof(fn), 0, configfile, fileset);
  1903. if (
  1904. #ifdef __CYGWIN__
  1905. (f = fopen(fn, "w+"))
  1906. #else
  1907. (f = fopen(fn, "w"))
  1908. #endif
  1909. ) {
  1910. ast_verb(2, "Saving '%s'\n", fn);
  1911. gen_header(f, configfile, fn, generator);
  1912. cat = cfg->root;
  1913. fclose(f);
  1914. if (fi) {
  1915. ao2_ref(fi, -1);
  1916. }
  1917. /* from here out, we open each involved file and concat the stuff we need to add to the end and immediately close... */
  1918. /* since each var, cat, and associated comments can come from any file, we have to be
  1919. mobile, and open each file, print, and close it on an entry-by-entry basis */
  1920. while (cat) {
  1921. fi = set_fn(fn, sizeof(fn), cat->file, configfile, fileset);
  1922. f = fopen(fn, "a");
  1923. if (!f) {
  1924. ast_log(LOG_ERROR, "Unable to write %s (%s)\n", fn, strerror(errno));
  1925. if (fi) {
  1926. ao2_ref(fi, -1);
  1927. }
  1928. ao2_ref(fileset, -1);
  1929. return -1;
  1930. }
  1931. /* dump any includes that happen before this category header */
  1932. for (incl=cfg->includes; incl; incl = incl->next) {
  1933. if (strcmp(incl->include_location_file, cat->file) == 0){
  1934. if (cat->lineno > incl->include_location_lineno && !incl->output) {
  1935. if (incl->exec)
  1936. fprintf(f,"#exec \"%s\"\n", incl->exec_file);
  1937. else
  1938. fprintf(f,"#include \"%s\"\n", incl->included_file);
  1939. incl->output = 1;
  1940. }
  1941. }
  1942. }
  1943. insert_leading_blank_lines(f, fi, cat->precomments, cat->lineno);
  1944. /* Dump section with any appropriate comment */
  1945. for (cmt = cat->precomments; cmt; cmt=cmt->next) {
  1946. char *cmtp = cmt->cmt;
  1947. while (cmtp && *cmtp == ';' && *(cmtp+1) == '!') {
  1948. char *cmtp2 = strchr(cmtp+1, '\n');
  1949. if (cmtp2)
  1950. cmtp = cmtp2+1;
  1951. else cmtp = 0;
  1952. }
  1953. if (cmtp)
  1954. fprintf(f,"%s", cmtp);
  1955. }
  1956. fprintf(f, "[%s]", cat->name);
  1957. if (cat->ignored || !AST_LIST_EMPTY(&cat->template_instances)) {
  1958. fprintf(f, "(");
  1959. if (cat->ignored) {
  1960. fprintf(f, "!");
  1961. }
  1962. if (cat->ignored && !AST_LIST_EMPTY(&cat->template_instances)) {
  1963. fprintf(f, ",");
  1964. }
  1965. if (!AST_LIST_EMPTY(&cat->template_instances)) {
  1966. struct ast_category_template_instance *x;
  1967. AST_LIST_TRAVERSE(&cat->template_instances, x, next) {
  1968. fprintf(f,"%s",x->name);
  1969. if (x != AST_LIST_LAST(&cat->template_instances))
  1970. fprintf(f,",");
  1971. }
  1972. }
  1973. fprintf(f, ")");
  1974. }
  1975. for(cmt = cat->sameline; cmt; cmt=cmt->next)
  1976. {
  1977. fprintf(f,"%s", cmt->cmt);
  1978. }
  1979. if (!cat->sameline)
  1980. fprintf(f,"\n");
  1981. for (cmt = cat->trailing; cmt; cmt=cmt->next) {
  1982. if (cmt->cmt[0] != ';' || cmt->cmt[1] != '!')
  1983. fprintf(f,"%s", cmt->cmt);
  1984. }
  1985. fclose(f);
  1986. if (fi) {
  1987. ao2_ref(fi, -1);
  1988. }
  1989. var = cat->root;
  1990. while (var) {
  1991. struct ast_category_template_instance *x;
  1992. int found = 0;
  1993. AST_LIST_TRAVERSE(&cat->template_instances, x, next) {
  1994. struct ast_variable *v;
  1995. for (v = x->inst->root; v; v = v->next) {
  1996. if (!strcasecmp(var->name, v->name) && !strcmp(var->value, v->value)) {
  1997. found = 1;
  1998. break;
  1999. }
  2000. }
  2001. if (found)
  2002. break;
  2003. }
  2004. if (found) {
  2005. var = var->next;
  2006. continue;
  2007. }
  2008. fi = set_fn(fn, sizeof(fn), var->file, configfile, fileset);
  2009. f = fopen(fn, "a");
  2010. if (!f) {
  2011. ast_debug(1, "Unable to open for writing: %s\n", fn);
  2012. ast_verb(2, "Unable to write %s (%s)\n", fn, strerror(errno));
  2013. if (fi) {
  2014. ao2_ref(fi, -1);
  2015. }
  2016. ao2_ref(fileset, -1);
  2017. return -1;
  2018. }
  2019. /* dump any includes that happen before this category header */
  2020. for (incl=cfg->includes; incl; incl = incl->next) {
  2021. if (strcmp(incl->include_location_file, var->file) == 0){
  2022. if (var->lineno > incl->include_location_lineno && !incl->output) {
  2023. if (incl->exec)
  2024. fprintf(f,"#exec \"%s\"\n", incl->exec_file);
  2025. else
  2026. fprintf(f,"#include \"%s\"\n", incl->included_file);
  2027. incl->output = 1;
  2028. }
  2029. }
  2030. }
  2031. insert_leading_blank_lines(f, fi, var->precomments, var->lineno);
  2032. for (cmt = var->precomments; cmt; cmt=cmt->next) {
  2033. if (cmt->cmt[0] != ';' || cmt->cmt[1] != '!')
  2034. fprintf(f,"%s", cmt->cmt);
  2035. }
  2036. { /* Block for 'escaped' scope */
  2037. int escaped_len = 2 * strlen(var->value) + 1;
  2038. char escaped[escaped_len];
  2039. ast_escape_semicolons(var->value, escaped, escaped_len);
  2040. if (var->sameline) {
  2041. fprintf(f, "%s %s %s %s", var->name, (var->object ? "=>" : "="),
  2042. escaped, var->sameline->cmt);
  2043. } else {
  2044. fprintf(f, "%s %s %s\n", var->name, (var->object ? "=>" : "="),
  2045. escaped);
  2046. }
  2047. }
  2048. for (cmt = var->trailing; cmt; cmt=cmt->next) {
  2049. if (cmt->cmt[0] != ';' || cmt->cmt[1] != '!')
  2050. fprintf(f,"%s", cmt->cmt);
  2051. }
  2052. if (var->blanklines) {
  2053. blanklines = var->blanklines;
  2054. while (blanklines--)
  2055. fprintf(f, "\n");
  2056. }
  2057. fclose(f);
  2058. if (fi) {
  2059. ao2_ref(fi, -1);
  2060. }
  2061. var = var->next;
  2062. }
  2063. cat = cat->next;
  2064. }
  2065. if (!option_debug) {
  2066. ast_verb(2, "Saving '%s': saved\n", fn);
  2067. }
  2068. } else {
  2069. ast_debug(1, "Unable to open for writing: %s\n", fn);
  2070. ast_verb(2, "Unable to write '%s' (%s)\n", fn, strerror(errno));
  2071. if (fi) {
  2072. ao2_ref(fi, -1);
  2073. }
  2074. ao2_ref(fileset, -1);
  2075. return -1;
  2076. }
  2077. /* Now, for files with trailing #include/#exec statements,
  2078. we have to make sure every entry is output */
  2079. for (incl=cfg->includes; incl; incl = incl->next) {
  2080. if (!incl->output) {
  2081. /* open the respective file */
  2082. fi = set_fn(fn, sizeof(fn), incl->include_location_file, configfile, fileset);
  2083. f = fopen(fn, "a");
  2084. if (!f) {
  2085. ast_debug(1, "Unable to open for writing: %s\n", fn);
  2086. ast_verb(2, "Unable to write %s (%s)\n", fn, strerror(errno));
  2087. if (fi) {
  2088. ao2_ref(fi, -1);
  2089. }
  2090. ao2_ref(fileset, -1);
  2091. return -1;
  2092. }
  2093. /* output the respective include */
  2094. if (incl->exec)
  2095. fprintf(f,"#exec \"%s\"\n", incl->exec_file);
  2096. else
  2097. fprintf(f,"#include \"%s\"\n", incl->included_file);
  2098. fclose(f);
  2099. incl->output = 1;
  2100. if (fi) {
  2101. ao2_ref(fi, -1);
  2102. }
  2103. }
  2104. }
  2105. ao2_ref(fileset, -1); /* this should destroy the hash container */
  2106. /* pass new configuration to any config hooks */
  2107. config_hook_exec(configfile, generator, cfg);
  2108. return 0;
  2109. }
  2110. static void clear_config_maps(void)
  2111. {
  2112. struct ast_config_map *map;
  2113. ast_mutex_lock(&config_lock);
  2114. while (config_maps) {
  2115. map = config_maps;
  2116. config_maps = config_maps->next;
  2117. ast_free(map);
  2118. }
  2119. ast_mutex_unlock(&config_lock);
  2120. }
  2121. static int append_mapping(const char *name, const char *driver, const char *database, const char *table, int priority)
  2122. {
  2123. struct ast_config_map *map;
  2124. char *dst;
  2125. int length;
  2126. length = sizeof(*map);
  2127. length += strlen(name) + 1;
  2128. length += strlen(driver) + 1;
  2129. length += strlen(database) + 1;
  2130. if (table)
  2131. length += strlen(table) + 1;
  2132. if (!(map = ast_calloc(1, length)))
  2133. return -1;
  2134. dst = map->stuff; /* writable space starts here */
  2135. map->name = strcpy(dst, name);
  2136. dst += strlen(dst) + 1;
  2137. map->driver = strcpy(dst, driver);
  2138. dst += strlen(dst) + 1;
  2139. map->database = strcpy(dst, database);
  2140. if (table) {
  2141. dst += strlen(dst) + 1;
  2142. map->table = strcpy(dst, table);
  2143. }
  2144. map->priority = priority;
  2145. map->next = config_maps;
  2146. config_maps = map;
  2147. ast_verb(2, "Binding %s to %s/%s/%s\n", map->name, map->driver, map->database, map->table ? map->table : map->name);
  2148. return 0;
  2149. }
  2150. int read_config_maps(void)
  2151. {
  2152. struct ast_config *config, *configtmp;
  2153. struct ast_variable *v;
  2154. char *driver, *table, *database, *textpri, *stringp, *tmp;
  2155. struct ast_flags flags = { CONFIG_FLAG_NOREALTIME };
  2156. int pri;
  2157. clear_config_maps();
  2158. configtmp = ast_config_new();
  2159. if (!configtmp) {
  2160. ast_log(LOG_ERROR, "Unable to allocate memory for new config\n");
  2161. return -1;
  2162. }
  2163. config = ast_config_internal_load(extconfig_conf, configtmp, flags, "", "extconfig");
  2164. if (config == CONFIG_STATUS_FILEINVALID) {
  2165. return -1;
  2166. } else if (!config) {
  2167. ast_config_destroy(configtmp);
  2168. return 0;
  2169. }
  2170. for (v = ast_variable_browse(config, "settings"); v; v = v->next) {
  2171. char buf[512];
  2172. ast_copy_string(buf, v->value, sizeof(buf));
  2173. stringp = buf;
  2174. driver = strsep(&stringp, ",");
  2175. if ((tmp = strchr(stringp, '\"')))
  2176. stringp = tmp;
  2177. /* check if the database text starts with a double quote */
  2178. if (*stringp == '"') {
  2179. stringp++;
  2180. database = strsep(&stringp, "\"");
  2181. strsep(&stringp, ",");
  2182. } else {
  2183. /* apparently this text has no quotes */
  2184. database = strsep(&stringp, ",");
  2185. }
  2186. table = strsep(&stringp, ",");
  2187. textpri = strsep(&stringp, ",");
  2188. if (!textpri || !(pri = atoi(textpri))) {
  2189. pri = 1;
  2190. }
  2191. if (!strcmp(v->name, extconfig_conf)) {
  2192. ast_log(LOG_WARNING, "Cannot bind '%s'!\n", extconfig_conf);
  2193. continue;
  2194. }
  2195. if (!strcmp(v->name, "asterisk.conf")) {
  2196. ast_log(LOG_WARNING, "Cannot bind 'asterisk.conf'!\n");
  2197. continue;
  2198. }
  2199. if (!strcmp(v->name, "logger.conf")) {
  2200. ast_log(LOG_WARNING, "Cannot bind 'logger.conf'!\n");
  2201. continue;
  2202. }
  2203. if (!driver || !database)
  2204. continue;
  2205. if (!strcasecmp(v->name, "sipfriends")) {
  2206. ast_log(LOG_WARNING, "The 'sipfriends' table is obsolete, update your config to use sippeers instead.\n");
  2207. append_mapping("sippeers", driver, database, table ? table : "sipfriends", pri);
  2208. } else if (!strcasecmp(v->name, "iaxfriends")) {
  2209. ast_log(LOG_WARNING, "The 'iaxfriends' table is obsolete, update your config to use iaxusers and iaxpeers, though they can point to the same table.\n");
  2210. append_mapping("iaxusers", driver, database, table ? table : "iaxfriends", pri);
  2211. append_mapping("iaxpeers", driver, database, table ? table : "iaxfriends", pri);
  2212. } else
  2213. append_mapping(v->name, driver, database, table, pri);
  2214. }
  2215. ast_config_destroy(config);
  2216. return 0;
  2217. }
  2218. int ast_config_engine_register(struct ast_config_engine *new)
  2219. {
  2220. struct ast_config_engine *ptr;
  2221. ast_mutex_lock(&config_lock);
  2222. if (!config_engine_list) {
  2223. config_engine_list = new;
  2224. } else {
  2225. for (ptr = config_engine_list; ptr->next; ptr=ptr->next);
  2226. ptr->next = new;
  2227. }
  2228. ast_mutex_unlock(&config_lock);
  2229. ast_log(LOG_NOTICE,"Registered Config Engine %s\n", new->name);
  2230. return 1;
  2231. }
  2232. int ast_config_engine_deregister(struct ast_config_engine *del)
  2233. {
  2234. struct ast_config_engine *ptr, *last=NULL;
  2235. ast_mutex_lock(&config_lock);
  2236. for (ptr = config_engine_list; ptr; ptr=ptr->next) {
  2237. if (ptr == del) {
  2238. if (last)
  2239. last->next = ptr->next;
  2240. else
  2241. config_engine_list = ptr->next;
  2242. break;
  2243. }
  2244. last = ptr;
  2245. }
  2246. ast_mutex_unlock(&config_lock);
  2247. return 0;
  2248. }
  2249. int ast_realtime_is_mapping_defined(const char *family)
  2250. {
  2251. struct ast_config_map *map;
  2252. ast_mutex_lock(&config_lock);
  2253. for (map = config_maps; map; map = map->next) {
  2254. if (!strcasecmp(family, map->name)) {
  2255. ast_mutex_unlock(&config_lock);
  2256. return 1;
  2257. }
  2258. }
  2259. ast_mutex_unlock(&config_lock);
  2260. return 0;
  2261. }
  2262. /*! \brief Find realtime engine for realtime family */
  2263. static struct ast_config_engine *find_engine(const char *family, int priority, char *database, int dbsiz, char *table, int tabsiz)
  2264. {
  2265. struct ast_config_engine *eng, *ret = NULL;
  2266. struct ast_config_map *map;
  2267. ast_mutex_lock(&config_lock);
  2268. for (map = config_maps; map; map = map->next) {
  2269. if (!strcasecmp(family, map->name) && (priority == map->priority)) {
  2270. if (database)
  2271. ast_copy_string(database, map->database, dbsiz);
  2272. if (table)
  2273. ast_copy_string(table, map->table ? map->table : family, tabsiz);
  2274. break;
  2275. }
  2276. }
  2277. /* Check if the required driver (engine) exist */
  2278. if (map) {
  2279. for (eng = config_engine_list; !ret && eng; eng = eng->next) {
  2280. if (!strcasecmp(eng->name, map->driver))
  2281. ret = eng;
  2282. }
  2283. }
  2284. ast_mutex_unlock(&config_lock);
  2285. /* if we found a mapping, but the engine is not available, then issue a warning */
  2286. if (map && !ret)
  2287. ast_log(LOG_WARNING, "Realtime mapping for '%s' found to engine '%s', but the engine is not available\n", map->name, map->driver);
  2288. return ret;
  2289. }
  2290. static struct ast_config_engine text_file_engine = {
  2291. .name = "text",
  2292. .load_func = config_text_file_load,
  2293. };
  2294. struct ast_config *ast_config_copy(const struct ast_config *old)
  2295. {
  2296. struct ast_config *new_config = ast_config_new();
  2297. struct ast_category *cat_iter;
  2298. if (!new_config) {
  2299. return NULL;
  2300. }
  2301. for (cat_iter = old->root; cat_iter; cat_iter = cat_iter->next) {
  2302. struct ast_category *new_cat =
  2303. ast_category_new(cat_iter->name, cat_iter->file, cat_iter->lineno);
  2304. if (!new_cat) {
  2305. goto fail;
  2306. }
  2307. ast_category_append(new_config, new_cat);
  2308. if (cat_iter->root) {
  2309. new_cat->root = ast_variables_dup(cat_iter->root);
  2310. if (!new_cat->root) {
  2311. goto fail;
  2312. }
  2313. new_cat->last = cat_iter->last;
  2314. }
  2315. }
  2316. return new_config;
  2317. fail:
  2318. ast_config_destroy(new_config);
  2319. return NULL;
  2320. }
  2321. struct ast_config *ast_config_internal_load(const char *filename, struct ast_config *cfg, struct ast_flags flags, const char *suggested_include_file, const char *who_asked)
  2322. {
  2323. char db[256];
  2324. char table[256];
  2325. struct ast_config_engine *loader = &text_file_engine;
  2326. struct ast_config *result;
  2327. /* The config file itself bumps include_level by 1 */
  2328. if (cfg->max_include_level > 0 && cfg->include_level == cfg->max_include_level + 1) {
  2329. ast_log(LOG_WARNING, "Maximum Include level (%d) exceeded\n", cfg->max_include_level);
  2330. return NULL;
  2331. }
  2332. cfg->include_level++;
  2333. if (!ast_test_flag(&flags, CONFIG_FLAG_NOREALTIME) && config_engine_list) {
  2334. struct ast_config_engine *eng;
  2335. eng = find_engine(filename, 1, db, sizeof(db), table, sizeof(table));
  2336. if (eng && eng->load_func) {
  2337. loader = eng;
  2338. } else {
  2339. eng = find_engine("global", 1, db, sizeof(db), table, sizeof(table));
  2340. if (eng && eng->load_func)
  2341. loader = eng;
  2342. }
  2343. }
  2344. result = loader->load_func(db, table, filename, cfg, flags, suggested_include_file, who_asked);
  2345. if (result && result != CONFIG_STATUS_FILEINVALID && result != CONFIG_STATUS_FILEUNCHANGED) {
  2346. result->include_level--;
  2347. config_hook_exec(filename, who_asked, result);
  2348. } else if (result != CONFIG_STATUS_FILEINVALID) {
  2349. cfg->include_level--;
  2350. }
  2351. return result;
  2352. }
  2353. struct ast_config *ast_config_load2(const char *filename, const char *who_asked, struct ast_flags flags)
  2354. {
  2355. struct ast_config *cfg;
  2356. struct ast_config *result;
  2357. cfg = ast_config_new();
  2358. if (!cfg)
  2359. return NULL;
  2360. result = ast_config_internal_load(filename, cfg, flags, "", who_asked);
  2361. if (!result || result == CONFIG_STATUS_FILEUNCHANGED || result == CONFIG_STATUS_FILEINVALID)
  2362. ast_config_destroy(cfg);
  2363. return result;
  2364. }
  2365. static struct ast_variable *ast_load_realtime_helper(const char *family, va_list ap)
  2366. {
  2367. struct ast_config_engine *eng;
  2368. char db[256];
  2369. char table[256];
  2370. struct ast_variable *res=NULL;
  2371. int i;
  2372. for (i = 1; ; i++) {
  2373. if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
  2374. if (eng->realtime_func && (res = eng->realtime_func(db, table, ap))) {
  2375. return res;
  2376. }
  2377. } else {
  2378. return NULL;
  2379. }
  2380. }
  2381. return res;
  2382. }
  2383. struct ast_variable *ast_load_realtime_all(const char *family, ...)
  2384. {
  2385. struct ast_variable *res;
  2386. va_list ap;
  2387. va_start(ap, family);
  2388. res = ast_load_realtime_helper(family, ap);
  2389. va_end(ap);
  2390. return res;
  2391. }
  2392. struct ast_variable *ast_load_realtime(const char *family, ...)
  2393. {
  2394. struct ast_variable *res;
  2395. struct ast_variable *cur;
  2396. struct ast_variable **prev;
  2397. va_list ap;
  2398. va_start(ap, family);
  2399. res = ast_load_realtime_helper(family, ap);
  2400. va_end(ap);
  2401. /* Filter the list. */
  2402. prev = &res;
  2403. cur = res;
  2404. while (cur) {
  2405. if (ast_strlen_zero(cur->value)) {
  2406. /* Eliminate empty entries */
  2407. struct ast_variable *next;
  2408. next = cur->next;
  2409. *prev = next;
  2410. ast_variable_destroy(cur);
  2411. cur = next;
  2412. } else {
  2413. /* Make blank entries empty and keep them. */
  2414. if (cur->value[0] == ' ' && cur->value[1] == '\0') {
  2415. char *vptr = (char *) cur->value;
  2416. vptr[0] = '\0';
  2417. }
  2418. prev = &cur->next;
  2419. cur = cur->next;
  2420. }
  2421. }
  2422. return res;
  2423. }
  2424. /*! \brief Check if realtime engine is configured for family */
  2425. int ast_check_realtime(const char *family)
  2426. {
  2427. struct ast_config_engine *eng;
  2428. if (!ast_realtime_enabled()) {
  2429. return 0; /* There are no engines at all so fail early */
  2430. }
  2431. eng = find_engine(family, 1, NULL, 0, NULL, 0);
  2432. if (eng)
  2433. return 1;
  2434. return 0;
  2435. }
  2436. /*! \brief Check if there's any realtime engines loaded */
  2437. int ast_realtime_enabled(void)
  2438. {
  2439. return config_maps ? 1 : 0;
  2440. }
  2441. int ast_realtime_require_field(const char *family, ...)
  2442. {
  2443. struct ast_config_engine *eng;
  2444. char db[256];
  2445. char table[256];
  2446. va_list ap;
  2447. int res = -1, i;
  2448. va_start(ap, family);
  2449. for (i = 1; ; i++) {
  2450. if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
  2451. /* If the require succeeds, it returns 0. */
  2452. if (eng->require_func && !(res = eng->require_func(db, table, ap))) {
  2453. break;
  2454. }
  2455. } else {
  2456. break;
  2457. }
  2458. }
  2459. va_end(ap);
  2460. return res;
  2461. }
  2462. int ast_unload_realtime(const char *family)
  2463. {
  2464. struct ast_config_engine *eng;
  2465. char db[256];
  2466. char table[256];
  2467. int res = -1, i;
  2468. for (i = 1; ; i++) {
  2469. if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
  2470. if (eng->unload_func) {
  2471. /* Do this for ALL engines */
  2472. res = eng->unload_func(db, table);
  2473. }
  2474. } else {
  2475. break;
  2476. }
  2477. }
  2478. return res;
  2479. }
  2480. struct ast_config *ast_load_realtime_multientry(const char *family, ...)
  2481. {
  2482. struct ast_config_engine *eng;
  2483. char db[256];
  2484. char table[256];
  2485. struct ast_config *res = NULL;
  2486. va_list ap;
  2487. int i;
  2488. va_start(ap, family);
  2489. for (i = 1; ; i++) {
  2490. if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
  2491. if (eng->realtime_multi_func && (res = eng->realtime_multi_func(db, table, ap))) {
  2492. /* If we were returned an empty cfg, destroy it and return NULL */
  2493. if (!res->root) {
  2494. ast_config_destroy(res);
  2495. res = NULL;
  2496. }
  2497. break;
  2498. }
  2499. } else {
  2500. break;
  2501. }
  2502. }
  2503. va_end(ap);
  2504. return res;
  2505. }
  2506. int ast_update_realtime(const char *family, const char *keyfield, const char *lookup, ...)
  2507. {
  2508. struct ast_config_engine *eng;
  2509. int res = -1, i;
  2510. char db[256];
  2511. char table[256];
  2512. va_list ap;
  2513. va_start(ap, lookup);
  2514. for (i = 1; ; i++) {
  2515. if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
  2516. /* If the update succeeds, it returns 0. */
  2517. if (eng->update_func && !(res = eng->update_func(db, table, keyfield, lookup, ap))) {
  2518. break;
  2519. }
  2520. } else {
  2521. break;
  2522. }
  2523. }
  2524. va_end(ap);
  2525. return res;
  2526. }
  2527. int ast_update2_realtime(const char *family, ...)
  2528. {
  2529. struct ast_config_engine *eng;
  2530. int res = -1, i;
  2531. char db[256];
  2532. char table[256];
  2533. va_list ap;
  2534. va_start(ap, family);
  2535. for (i = 1; ; i++) {
  2536. if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
  2537. if (eng->update2_func && !(res = eng->update2_func(db, table, ap))) {
  2538. break;
  2539. }
  2540. } else {
  2541. break;
  2542. }
  2543. }
  2544. va_end(ap);
  2545. return res;
  2546. }
  2547. int ast_store_realtime(const char *family, ...)
  2548. {
  2549. struct ast_config_engine *eng;
  2550. int res = -1, i;
  2551. char db[256];
  2552. char table[256];
  2553. va_list ap;
  2554. va_start(ap, family);
  2555. for (i = 1; ; i++) {
  2556. if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
  2557. /* If the store succeeds, it returns 0. */
  2558. if (eng->store_func && !(res = eng->store_func(db, table, ap))) {
  2559. break;
  2560. }
  2561. } else {
  2562. break;
  2563. }
  2564. }
  2565. va_end(ap);
  2566. return res;
  2567. }
  2568. int ast_destroy_realtime(const char *family, const char *keyfield, const char *lookup, ...)
  2569. {
  2570. struct ast_config_engine *eng;
  2571. int res = -1, i;
  2572. char db[256];
  2573. char table[256];
  2574. va_list ap;
  2575. va_start(ap, lookup);
  2576. for (i = 1; ; i++) {
  2577. if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
  2578. if (eng->destroy_func && !(res = eng->destroy_func(db, table, keyfield, lookup, ap))) {
  2579. break;
  2580. }
  2581. } else {
  2582. break;
  2583. }
  2584. }
  2585. va_end(ap);
  2586. return res;
  2587. }
  2588. char *ast_realtime_decode_chunk(char *chunk)
  2589. {
  2590. char *orig = chunk;
  2591. for (; *chunk; chunk++) {
  2592. if (*chunk == '^' && strchr("0123456789ABCDEFabcdef", chunk[1]) && strchr("0123456789ABCDEFabcdef", chunk[2])) {
  2593. sscanf(chunk + 1, "%02hhX", (unsigned char *)chunk);
  2594. memmove(chunk + 1, chunk + 3, strlen(chunk + 3) + 1);
  2595. }
  2596. }
  2597. return orig;
  2598. }
  2599. char *ast_realtime_encode_chunk(struct ast_str **dest, ssize_t maxlen, const char *chunk)
  2600. {
  2601. if (!strchr(chunk, ';') && !strchr(chunk, '^')) {
  2602. ast_str_set(dest, maxlen, "%s", chunk);
  2603. } else {
  2604. ast_str_reset(*dest);
  2605. for (; *chunk; chunk++) {
  2606. if (strchr(";^", *chunk)) {
  2607. ast_str_append(dest, maxlen, "^%02hhX", *chunk);
  2608. } else {
  2609. ast_str_append(dest, maxlen, "%c", *chunk);
  2610. }
  2611. }
  2612. }
  2613. return ast_str_buffer(*dest);
  2614. }
  2615. /*! \brief Helper function to parse arguments
  2616. * See documentation in config.h
  2617. */
  2618. int ast_parse_arg(const char *arg, enum ast_parse_flags flags,
  2619. void *p_result, ...)
  2620. {
  2621. va_list ap;
  2622. int error = 0;
  2623. va_start(ap, p_result);
  2624. switch (flags & PARSE_TYPE) {
  2625. case PARSE_INT32:
  2626. {
  2627. long int x = 0;
  2628. int32_t *result = p_result;
  2629. int32_t def = result ? *result : 0, high = INT32_MAX, low = INT32_MIN;
  2630. char *endptr = NULL;
  2631. /* optional arguments: default value and/or (low, high) */
  2632. if (flags & PARSE_DEFAULT) {
  2633. def = va_arg(ap, int32_t);
  2634. }
  2635. if (flags & (PARSE_IN_RANGE | PARSE_OUT_RANGE)) {
  2636. low = va_arg(ap, int32_t);
  2637. high = va_arg(ap, int32_t);
  2638. }
  2639. if (ast_strlen_zero(arg)) {
  2640. error = 1;
  2641. goto int32_done;
  2642. }
  2643. errno = 0;
  2644. x = strtol(arg, &endptr, 0);
  2645. if (*endptr || errno || x < INT32_MIN || x > INT32_MAX) {
  2646. /* Parse error, or type out of int32_t bounds */
  2647. error = 1;
  2648. goto int32_done;
  2649. }
  2650. error = (x < low) || (x > high);
  2651. if (flags & PARSE_RANGE_DEFAULTS) {
  2652. if (x < low) {
  2653. def = low;
  2654. } else if (x > high) {
  2655. def = high;
  2656. }
  2657. }
  2658. if (flags & PARSE_OUT_RANGE) {
  2659. error = !error;
  2660. }
  2661. int32_done:
  2662. if (result) {
  2663. *result = error ? def : x;
  2664. }
  2665. ast_debug(3, "extract int from [%s] in [%d, %d] gives [%ld](%d)\n",
  2666. arg, low, high, result ? *result : x, error);
  2667. break;
  2668. }
  2669. case PARSE_UINT32:
  2670. {
  2671. unsigned long int x = 0;
  2672. uint32_t *result = p_result;
  2673. uint32_t def = result ? *result : 0, low = 0, high = UINT32_MAX;
  2674. char *endptr = NULL;
  2675. /* optional argument: first default value, then range */
  2676. if (flags & PARSE_DEFAULT) {
  2677. def = va_arg(ap, uint32_t);
  2678. }
  2679. if (flags & (PARSE_IN_RANGE|PARSE_OUT_RANGE)) {
  2680. /* range requested, update bounds */
  2681. low = va_arg(ap, uint32_t);
  2682. high = va_arg(ap, uint32_t);
  2683. }
  2684. if (ast_strlen_zero(arg)) {
  2685. error = 1;
  2686. goto uint32_done;
  2687. }
  2688. /* strtoul will happilly and silently negate negative numbers */
  2689. arg = ast_skip_blanks(arg);
  2690. if (*arg == '-') {
  2691. error = 1;
  2692. goto uint32_done;
  2693. }
  2694. errno = 0;
  2695. x = strtoul(arg, &endptr, 0);
  2696. if (*endptr || errno || x > UINT32_MAX) {
  2697. error = 1;
  2698. goto uint32_done;
  2699. }
  2700. error = (x < low) || (x > high);
  2701. if (flags & PARSE_RANGE_DEFAULTS) {
  2702. if (x < low) {
  2703. def = low;
  2704. } else if (x > high) {
  2705. def = high;
  2706. }
  2707. }
  2708. if (flags & PARSE_OUT_RANGE) {
  2709. error = !error;
  2710. }
  2711. uint32_done:
  2712. if (result) {
  2713. *result = error ? def : x;
  2714. }
  2715. ast_debug(3, "extract uint from [%s] in [%u, %u] gives [%lu](%d)\n",
  2716. arg, low, high, result ? *result : x, error);
  2717. break;
  2718. }
  2719. case PARSE_DOUBLE:
  2720. {
  2721. double *result = p_result;
  2722. double x = 0, def = result ? *result : 0, low = -HUGE_VAL, high = HUGE_VAL;
  2723. char *endptr = NULL;
  2724. /* optional argument: first default value, then range */
  2725. if (flags & PARSE_DEFAULT) {
  2726. def = va_arg(ap, double);
  2727. }
  2728. if (flags & (PARSE_IN_RANGE | PARSE_OUT_RANGE)) {
  2729. /* range requested, update bounds */
  2730. low = va_arg(ap, double);
  2731. high = va_arg(ap, double);
  2732. }
  2733. if (ast_strlen_zero(arg)) {
  2734. error = 1;
  2735. goto double_done;
  2736. }
  2737. errno = 0;
  2738. x = strtod(arg, &endptr);
  2739. if (*endptr || errno == ERANGE) {
  2740. error = 1;
  2741. goto double_done;
  2742. }
  2743. error = (x < low) || (x > high);
  2744. if (flags & PARSE_OUT_RANGE) {
  2745. error = !error;
  2746. }
  2747. double_done:
  2748. if (result) {
  2749. *result = error ? def : x;
  2750. }
  2751. ast_debug(3, "extract double from [%s] in [%f, %f] gives [%f](%d)\n",
  2752. arg, low, high, result ? *result : x, error);
  2753. break;
  2754. }
  2755. case PARSE_ADDR:
  2756. {
  2757. struct ast_sockaddr *addr = (struct ast_sockaddr *)p_result;
  2758. if (!ast_sockaddr_parse(addr, arg, flags & PARSE_PORT_MASK)) {
  2759. error = 1;
  2760. }
  2761. ast_debug(3, "extract addr from %s gives %s(%d)\n",
  2762. arg, ast_sockaddr_stringify(addr), error);
  2763. break;
  2764. }
  2765. case PARSE_INADDR: /* TODO Remove this (use PARSE_ADDR instead). */
  2766. {
  2767. char *port, *buf;
  2768. struct sockaddr_in _sa_buf; /* buffer for the result */
  2769. struct sockaddr_in *sa = p_result ?
  2770. (struct sockaddr_in *)p_result : &_sa_buf;
  2771. /* default is either the supplied value or the result itself */
  2772. struct sockaddr_in *def = (flags & PARSE_DEFAULT) ?
  2773. va_arg(ap, struct sockaddr_in *) : sa;
  2774. struct hostent *hp;
  2775. struct ast_hostent ahp;
  2776. memset(&_sa_buf, '\0', sizeof(_sa_buf)); /* clear buffer */
  2777. /* duplicate the string to strip away the :port */
  2778. port = ast_strdupa(arg);
  2779. buf = strsep(&port, ":");
  2780. sa->sin_family = AF_INET; /* assign family */
  2781. /*
  2782. * honor the ports flag setting, assign default value
  2783. * in case of errors or field unset.
  2784. */
  2785. flags &= PARSE_PORT_MASK; /* the only flags left to process */
  2786. if (port) {
  2787. if (flags == PARSE_PORT_FORBID) {
  2788. error = 1; /* port was forbidden */
  2789. sa->sin_port = def->sin_port;
  2790. } else if (flags == PARSE_PORT_IGNORE)
  2791. sa->sin_port = def->sin_port;
  2792. else /* accept or require */
  2793. sa->sin_port = htons(strtol(port, NULL, 0));
  2794. } else {
  2795. sa->sin_port = def->sin_port;
  2796. if (flags == PARSE_PORT_REQUIRE)
  2797. error = 1;
  2798. }
  2799. /* Now deal with host part, even if we have errors before. */
  2800. hp = ast_gethostbyname(buf, &ahp);
  2801. if (hp) /* resolved successfully */
  2802. memcpy(&sa->sin_addr, hp->h_addr, sizeof(sa->sin_addr));
  2803. else {
  2804. error = 1;
  2805. sa->sin_addr = def->sin_addr;
  2806. }
  2807. ast_debug(3,
  2808. "extract inaddr from [%s] gives [%s:%d](%d)\n",
  2809. arg, ast_inet_ntoa(sa->sin_addr),
  2810. ntohs(sa->sin_port), error);
  2811. break;
  2812. }
  2813. }
  2814. va_end(ap);
  2815. return error;
  2816. }
  2817. static char *handle_cli_core_show_config_mappings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2818. {
  2819. struct ast_config_engine *eng;
  2820. struct ast_config_map *map;
  2821. switch (cmd) {
  2822. case CLI_INIT:
  2823. e->command = "core show config mappings";
  2824. e->usage =
  2825. "Usage: core show config mappings\n"
  2826. " Shows the filenames to config engines.\n";
  2827. return NULL;
  2828. case CLI_GENERATE:
  2829. return NULL;
  2830. }
  2831. ast_mutex_lock(&config_lock);
  2832. if (!config_engine_list) {
  2833. ast_cli(a->fd, "No config mappings found.\n");
  2834. } else {
  2835. for (eng = config_engine_list; eng; eng = eng->next) {
  2836. ast_cli(a->fd, "Config Engine: %s\n", eng->name);
  2837. for (map = config_maps; map; map = map->next) {
  2838. if (!strcasecmp(map->driver, eng->name)) {
  2839. ast_cli(a->fd, "===> %s (db=%s, table=%s)\n", map->name, map->database,
  2840. map->table ? map->table : map->name);
  2841. }
  2842. }
  2843. }
  2844. }
  2845. ast_mutex_unlock(&config_lock);
  2846. return CLI_SUCCESS;
  2847. }
  2848. static char *handle_cli_config_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2849. {
  2850. struct cache_file_mtime *cfmtime;
  2851. char *prev = "", *completion_value = NULL;
  2852. int wordlen, which = 0;
  2853. switch (cmd) {
  2854. case CLI_INIT:
  2855. e->command = "config reload";
  2856. e->usage =
  2857. "Usage: config reload <filename.conf>\n"
  2858. " Reloads all modules that reference <filename.conf>\n";
  2859. return NULL;
  2860. case CLI_GENERATE:
  2861. if (a->pos > 2) {
  2862. return NULL;
  2863. }
  2864. wordlen = strlen(a->word);
  2865. AST_LIST_LOCK(&cfmtime_head);
  2866. AST_LIST_TRAVERSE(&cfmtime_head, cfmtime, list) {
  2867. /* Skip duplicates - this only works because the list is sorted by filename */
  2868. if (strcmp(cfmtime->filename, prev) == 0) {
  2869. continue;
  2870. }
  2871. /* Core configs cannot be reloaded */
  2872. if (ast_strlen_zero(cfmtime->who_asked)) {
  2873. continue;
  2874. }
  2875. if (++which > a->n && strncmp(cfmtime->filename, a->word, wordlen) == 0) {
  2876. completion_value = ast_strdup(cfmtime->filename);
  2877. break;
  2878. }
  2879. /* Otherwise save that we've seen this filename */
  2880. prev = cfmtime->filename;
  2881. }
  2882. AST_LIST_UNLOCK(&cfmtime_head);
  2883. return completion_value;
  2884. }
  2885. if (a->argc != 3) {
  2886. return CLI_SHOWUSAGE;
  2887. }
  2888. AST_LIST_LOCK(&cfmtime_head);
  2889. AST_LIST_TRAVERSE(&cfmtime_head, cfmtime, list) {
  2890. if (!strcmp(cfmtime->filename, a->argv[2])) {
  2891. char *buf = ast_alloca(strlen("module reload ") + strlen(cfmtime->who_asked) + 1);
  2892. sprintf(buf, "module reload %s", cfmtime->who_asked);
  2893. ast_cli_command(a->fd, buf);
  2894. }
  2895. }
  2896. AST_LIST_UNLOCK(&cfmtime_head);
  2897. return CLI_SUCCESS;
  2898. }
  2899. static char *handle_cli_config_list(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2900. {
  2901. struct cache_file_mtime *cfmtime;
  2902. switch (cmd) {
  2903. case CLI_INIT:
  2904. e->command = "config list";
  2905. e->usage =
  2906. "Usage: config list\n"
  2907. " Show all modules that have loaded a configuration file\n";
  2908. return NULL;
  2909. case CLI_GENERATE:
  2910. return NULL;
  2911. }
  2912. AST_LIST_LOCK(&cfmtime_head);
  2913. AST_LIST_TRAVERSE(&cfmtime_head, cfmtime, list) {
  2914. ast_cli(a->fd, "%-20.20s %-50s\n", S_OR(cfmtime->who_asked, "core"), cfmtime->filename);
  2915. }
  2916. AST_LIST_UNLOCK(&cfmtime_head);
  2917. return CLI_SUCCESS;
  2918. }
  2919. static struct ast_cli_entry cli_config[] = {
  2920. AST_CLI_DEFINE(handle_cli_core_show_config_mappings, "Display config mappings (file names to config engines)"),
  2921. AST_CLI_DEFINE(handle_cli_config_reload, "Force a reload on modules using a particular configuration file"),
  2922. AST_CLI_DEFINE(handle_cli_config_list, "Show all files that have loaded a configuration file"),
  2923. };
  2924. static void config_shutdown(void)
  2925. {
  2926. struct cache_file_mtime *cfmtime;
  2927. AST_LIST_LOCK(&cfmtime_head);
  2928. while ((cfmtime = AST_LIST_REMOVE_HEAD(&cfmtime_head, list))) {
  2929. config_cache_destroy_entry(cfmtime);
  2930. }
  2931. AST_LIST_UNLOCK(&cfmtime_head);
  2932. ast_cli_unregister_multiple(cli_config, ARRAY_LEN(cli_config));
  2933. ao2_cleanup(cfg_hooks);
  2934. cfg_hooks = NULL;
  2935. }
  2936. int register_config_cli(void)
  2937. {
  2938. ast_cli_register_multiple(cli_config, ARRAY_LEN(cli_config));
  2939. ast_register_cleanup(config_shutdown);
  2940. return 0;
  2941. }
  2942. struct cfg_hook {
  2943. const char *name;
  2944. const char *filename;
  2945. const char *module;
  2946. config_hook_cb hook_cb;
  2947. };
  2948. static void hook_destroy(void *obj)
  2949. {
  2950. struct cfg_hook *hook = obj;
  2951. ast_free((void *) hook->name);
  2952. ast_free((void *) hook->filename);
  2953. ast_free((void *) hook->module);
  2954. }
  2955. static int hook_cmp(void *obj, void *arg, int flags)
  2956. {
  2957. struct cfg_hook *hook1 = obj;
  2958. struct cfg_hook *hook2 = arg;
  2959. return !(strcasecmp(hook1->name, hook2->name)) ? CMP_MATCH | CMP_STOP : 0;
  2960. }
  2961. static int hook_hash(const void *obj, const int flags)
  2962. {
  2963. const struct cfg_hook *hook = obj;
  2964. return ast_str_hash(hook->name);
  2965. }
  2966. void ast_config_hook_unregister(const char *name)
  2967. {
  2968. struct cfg_hook tmp;
  2969. tmp.name = ast_strdupa(name);
  2970. ao2_find(cfg_hooks, &tmp, OBJ_POINTER | OBJ_UNLINK | OBJ_NODATA);
  2971. }
  2972. static void config_hook_exec(const char *filename, const char *module, const struct ast_config *cfg)
  2973. {
  2974. struct ao2_iterator it;
  2975. struct cfg_hook *hook;
  2976. if (!(cfg_hooks)) {
  2977. return;
  2978. }
  2979. it = ao2_iterator_init(cfg_hooks, 0);
  2980. while ((hook = ao2_iterator_next(&it))) {
  2981. if (!strcasecmp(hook->filename, filename) &&
  2982. !strcasecmp(hook->module, module)) {
  2983. struct ast_config *copy = ast_config_copy(cfg);
  2984. hook->hook_cb(copy);
  2985. }
  2986. ao2_ref(hook, -1);
  2987. }
  2988. ao2_iterator_destroy(&it);
  2989. }
  2990. int ast_config_hook_register(const char *name,
  2991. const char *filename,
  2992. const char *module,
  2993. enum config_hook_flags flags,
  2994. config_hook_cb hook_cb)
  2995. {
  2996. struct cfg_hook *hook;
  2997. if (!cfg_hooks && !(cfg_hooks = ao2_container_alloc(17, hook_hash, hook_cmp))) {
  2998. return -1;
  2999. }
  3000. if (!(hook = ao2_alloc(sizeof(*hook), hook_destroy))) {
  3001. return -1;
  3002. }
  3003. hook->hook_cb = hook_cb;
  3004. hook->filename = ast_strdup(filename);
  3005. hook->name = ast_strdup(name);
  3006. hook->module = ast_strdup(module);
  3007. ao2_link(cfg_hooks, hook);
  3008. ao2_ref(hook, -1);
  3009. return 0;
  3010. }