config.c 106 KB

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