loader.c 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. * Kevin P. Fleming <kpfleming@digium.com>
  8. * Luigi Rizzo <rizzo@icir.org>
  9. *
  10. * See http://www.asterisk.org for more information about
  11. * the Asterisk project. Please do not directly contact
  12. * any of the maintainers of this project for assistance;
  13. * the project provides a web site, mailing lists and IRC
  14. * channels for your use.
  15. *
  16. * This program is free software, distributed under the terms of
  17. * the GNU General Public License Version 2. See the LICENSE file
  18. * at the top of the source tree.
  19. */
  20. /*! \file
  21. *
  22. * \brief Module Loader
  23. * \author Mark Spencer <markster@digium.com>
  24. * \author Kevin P. Fleming <kpfleming@digium.com>
  25. * \author Luigi Rizzo <rizzo@icir.org>
  26. * - See ModMngMnt
  27. */
  28. /*** MODULEINFO
  29. <support_level>core</support_level>
  30. ***/
  31. #include "asterisk.h"
  32. #include "asterisk/_private.h"
  33. #include "asterisk/paths.h" /* use ast_config_AST_MODULE_DIR */
  34. #include <dirent.h>
  35. #include "asterisk/dlinkedlists.h"
  36. #include "asterisk/module.h"
  37. #include "asterisk/config.h"
  38. #include "asterisk/channel.h"
  39. #include "asterisk/term.h"
  40. #include "asterisk/manager.h"
  41. #include "asterisk/io.h"
  42. #include "asterisk/lock.h"
  43. #include "asterisk/vector.h"
  44. #include "asterisk/app.h"
  45. #include "asterisk/test.h"
  46. #include "asterisk/cli.h"
  47. #include <dlfcn.h>
  48. #include "asterisk/md5.h"
  49. #include "asterisk/utils.h"
  50. /*** DOCUMENTATION
  51. <managerEvent language="en_US" name="Reload">
  52. <managerEventInstance class="EVENT_FLAG_SYSTEM">
  53. <synopsis>Raised when a module has been reloaded in Asterisk.</synopsis>
  54. <syntax>
  55. <parameter name="Module">
  56. <para>The name of the module that was reloaded, or
  57. <literal>All</literal> if all modules were reloaded</para>
  58. </parameter>
  59. <parameter name="Status">
  60. <para>The numeric status code denoting the success or failure
  61. of the reload request.</para>
  62. <enumlist>
  63. <enum name="0"><para>Success</para></enum>
  64. <enum name="1"><para>Request queued</para></enum>
  65. <enum name="2"><para>Module not found</para></enum>
  66. <enum name="3"><para>Error</para></enum>
  67. <enum name="4"><para>Reload already in progress</para></enum>
  68. <enum name="5"><para>Module uninitialized</para></enum>
  69. <enum name="6"><para>Reload not supported</para></enum>
  70. </enumlist>
  71. </parameter>
  72. </syntax>
  73. </managerEventInstance>
  74. </managerEvent>
  75. <managerEvent language="en_US" name="Load">
  76. <managerEventInstance class="EVENT_FLAG_SYSTEM">
  77. <synopsis>Raised when a module has been loaded in Asterisk.</synopsis>
  78. <syntax>
  79. <parameter name="Module">
  80. <para>The name of the module that was loaded</para>
  81. </parameter>
  82. <parameter name="Status">
  83. <para>The result of the load request.</para>
  84. <enumlist>
  85. <enum name="Failure"><para>Module could not be loaded properly</para></enum>
  86. <enum name="Success"><para>Module loaded and configured</para></enum>
  87. <enum name="Decline"><para>Module is not configured</para></enum>
  88. </enumlist>
  89. </parameter>
  90. </syntax>
  91. </managerEventInstance>
  92. </managerEvent>
  93. <managerEvent language="en_US" name="Unload">
  94. <managerEventInstance class="EVENT_FLAG_SYSTEM">
  95. <synopsis>Raised when a module has been unloaded in Asterisk.</synopsis>
  96. <syntax>
  97. <parameter name="Module">
  98. <para>The name of the module that was unloaded</para>
  99. </parameter>
  100. <parameter name="Status">
  101. <para>The result of the unload request.</para>
  102. <enumlist>
  103. <enum name="Success"><para>Module unloaded successfully</para></enum>
  104. </enumlist>
  105. </parameter>
  106. </syntax>
  107. </managerEventInstance>
  108. </managerEvent>
  109. ***/
  110. #ifndef RTLD_NOW
  111. #define RTLD_NOW 0
  112. #endif
  113. #ifndef RTLD_LOCAL
  114. #define RTLD_LOCAL 0
  115. #endif
  116. struct ast_module_user {
  117. struct ast_channel *chan;
  118. AST_LIST_ENTRY(ast_module_user) entry;
  119. };
  120. AST_DLLIST_HEAD(module_user_list, ast_module_user);
  121. static const unsigned char expected_key[] =
  122. { 0x87, 0x76, 0x79, 0x35, 0x23, 0xea, 0x3a, 0xd3,
  123. 0x25, 0x2a, 0xbb, 0x35, 0x87, 0xe4, 0x22, 0x24 };
  124. static char buildopt_sum[33] = AST_BUILDOPT_SUM;
  125. AST_VECTOR(module_vector, struct ast_module *);
  126. /*! Used with AST_VECTOR_CALLBACK_VOID to create a
  127. * comma separated list of module names for error messages. */
  128. #define STR_APPEND_TEXT(txt, str) \
  129. ast_str_append(str, 0, "%s%s", \
  130. ast_str_strlen(*(str)) > 0 ? ", " : "", \
  131. txt)
  132. /* Built-in module registrations need special handling at startup */
  133. static unsigned int loader_ready;
  134. /*! String container for deferring output of startup errors. */
  135. static struct ast_vector_string startup_errors;
  136. static struct ast_str *startup_error_builder;
  137. #if defined(HAVE_PERMANENT_DLOPEN) || defined(AST_XML_DOCS)
  138. static char *get_name_from_resource(const char *resource)
  139. {
  140. int len;
  141. const char *last_three;
  142. char *mod_name;
  143. if (!resource) {
  144. return NULL;
  145. }
  146. len = strlen(resource);
  147. if (len > 3) {
  148. last_three = &resource[len-3];
  149. if (!strcasecmp(last_three, ".so")) {
  150. mod_name = ast_calloc(1, len - 2);
  151. if (mod_name) {
  152. ast_copy_string(mod_name, resource, len - 2);
  153. return mod_name;
  154. } else {
  155. /* Unable to allocate memory. */
  156. return NULL;
  157. }
  158. }
  159. }
  160. /* Resource is the name - happens when manually unloading a module. */
  161. mod_name = ast_calloc(1, len + 1);
  162. if (mod_name) {
  163. ast_copy_string(mod_name, resource, len + 1);
  164. return mod_name;
  165. }
  166. /* Unable to allocate memory. */
  167. return NULL;
  168. }
  169. #endif
  170. #if defined(HAVE_PERMANENT_DLOPEN)
  171. #define FIRST_DLOPEN 999
  172. struct ao2_container *info_list = NULL;
  173. struct info_list_obj {
  174. const struct ast_module_info *info;
  175. int dlopened;
  176. char name[0];
  177. };
  178. static struct info_list_obj *info_list_obj_alloc(const char *name,
  179. const struct ast_module_info *info)
  180. {
  181. struct info_list_obj *new_entry;
  182. new_entry = ao2_alloc(sizeof(*new_entry) + strlen(name) + 1, NULL);
  183. if (!new_entry) {
  184. return NULL;
  185. }
  186. strcpy(new_entry->name, name); /* SAFE */
  187. new_entry->info = info;
  188. new_entry->dlopened = FIRST_DLOPEN;
  189. return new_entry;
  190. }
  191. AO2_STRING_FIELD_CMP_FN(info_list_obj, name)
  192. static void manual_mod_reg(const void *lib, const char *resource)
  193. {
  194. struct info_list_obj *obj_tmp;
  195. char *mod_name;
  196. if (lib) {
  197. mod_name = get_name_from_resource(resource);
  198. if (mod_name) {
  199. obj_tmp = ao2_find(info_list, mod_name, OBJ_SEARCH_KEY);
  200. if (obj_tmp) {
  201. if (obj_tmp->dlopened == FIRST_DLOPEN) {
  202. obj_tmp->dlopened = 1;
  203. } else {
  204. ast_module_register(obj_tmp->info);
  205. }
  206. ao2_ref(obj_tmp, -1);
  207. }
  208. ast_free(mod_name);
  209. }
  210. }
  211. }
  212. static void manual_mod_unreg(const char *resource)
  213. {
  214. struct info_list_obj *obj_tmp;
  215. char *mod_name;
  216. /* When Asterisk shuts down the destructor is called automatically. */
  217. if (ast_shutdown_final()) {
  218. return;
  219. }
  220. mod_name = get_name_from_resource(resource);
  221. if (mod_name) {
  222. obj_tmp = ao2_find(info_list, mod_name, OBJ_SEARCH_KEY);
  223. if (obj_tmp) {
  224. ast_module_unregister(obj_tmp->info);
  225. ao2_ref(obj_tmp, -1);
  226. }
  227. ast_free(mod_name);
  228. }
  229. }
  230. #endif
  231. static __attribute__((format(printf, 1, 2))) void module_load_error(const char *fmt, ...)
  232. {
  233. char *copy = NULL;
  234. va_list ap;
  235. va_start(ap, fmt);
  236. if (startup_error_builder) {
  237. ast_str_set_va(&startup_error_builder, 0, fmt, ap);
  238. copy = ast_strdup(ast_str_buffer(startup_error_builder));
  239. if (!copy || AST_VECTOR_APPEND(&startup_errors, copy)) {
  240. ast_log(LOG_ERROR, "%s", ast_str_buffer(startup_error_builder));
  241. ast_free(copy);
  242. }
  243. } else {
  244. ast_log_ap(LOG_ERROR, fmt, ap);
  245. }
  246. va_end(ap);
  247. }
  248. /*!
  249. * \brief Internal flag to indicate all modules have been initially loaded.
  250. */
  251. static int modules_loaded;
  252. struct ast_module {
  253. const struct ast_module_info *info;
  254. /*! Used to get module references into refs log */
  255. void *ref_debug;
  256. /*! The shared lib. */
  257. void *lib;
  258. /*! Number of 'users' and other references currently holding the module. */
  259. int usecount;
  260. /*! List of users holding the module. */
  261. struct module_user_list users;
  262. /*! List of required module names. */
  263. struct ast_vector_string requires;
  264. /*! List of optional api modules. */
  265. struct ast_vector_string optional_modules;
  266. /*! List of modules this enhances. */
  267. struct ast_vector_string enhances;
  268. /*!
  269. * \brief Vector holding pointers to modules we have a reference to.
  270. *
  271. * When one module requires another, the required module gets added
  272. * to this list with a reference.
  273. */
  274. struct module_vector reffed_deps;
  275. struct {
  276. /*! The module running and ready to accept requests. */
  277. unsigned int running:1;
  278. /*! The module has declined to start. */
  279. unsigned int declined:1;
  280. /*! This module is being held open until it's time to shutdown. */
  281. unsigned int keepuntilshutdown:1;
  282. /*! The module is built-in. */
  283. unsigned int builtin:1;
  284. /*! The admin has declared this module is required. */
  285. unsigned int required:1;
  286. /*! This module is marked for preload. */
  287. unsigned int preload:1;
  288. } flags;
  289. AST_DLLIST_ENTRY(ast_module) entry;
  290. char resource[0];
  291. };
  292. static AST_DLLIST_HEAD_STATIC(module_list, ast_module);
  293. struct load_results_map {
  294. int result;
  295. const char *name;
  296. };
  297. static const struct load_results_map load_results[] = {
  298. { AST_MODULE_LOAD_SUCCESS, "Success" },
  299. { AST_MODULE_LOAD_DECLINE, "Decline" },
  300. { AST_MODULE_LOAD_SKIP, "Skip" },
  301. { AST_MODULE_LOAD_PRIORITY, "Priority" },
  302. { AST_MODULE_LOAD_FAILURE, "Failure" },
  303. };
  304. #define AST_MODULE_LOAD_UNKNOWN_STRING "Unknown" /* Status string for unknown load status */
  305. static void publish_load_message_type(const char* type, const char *name, const char *status);
  306. static void publish_reload_message(const char *name, enum ast_module_reload_result result);
  307. static void publish_load_message(const char *name, enum ast_module_load_result result);
  308. static void publish_unload_message(const char *name, const char* status);
  309. /*
  310. * module_list is cleared by its constructor possibly after
  311. * we start accumulating built-in modules, so we need to
  312. * use another list (without the lock) to accumulate them.
  313. */
  314. static struct module_list builtin_module_list;
  315. static int module_vector_strcasecmp(struct ast_module *a, struct ast_module *b)
  316. {
  317. return strcasecmp(a->resource, b->resource);
  318. }
  319. static int module_vector_cmp(struct ast_module *a, struct ast_module *b)
  320. {
  321. int preload_diff = (int)b->flags.preload - (int)a->flags.preload;
  322. /* if load_pri is not set, default is 128. Lower is better */
  323. int a_pri = ast_test_flag(a->info, AST_MODFLAG_LOAD_ORDER)
  324. ? a->info->load_pri : AST_MODPRI_DEFAULT;
  325. int b_pri = ast_test_flag(b->info, AST_MODFLAG_LOAD_ORDER)
  326. ? b->info->load_pri : AST_MODPRI_DEFAULT;
  327. if (preload_diff) {
  328. /* -1 preload a but not b */
  329. /* 0 preload both or neither */
  330. /* 1 preload b but not a */
  331. return preload_diff;
  332. }
  333. /*
  334. * Returns comparison values for a vector sorted by priority.
  335. * <0 a_pri < b_pri
  336. * =0 a_pri == b_pri
  337. * >0 a_pri > b_pri
  338. */
  339. return a_pri - b_pri;
  340. }
  341. static struct ast_module *find_resource(const char *resource, int do_lock);
  342. /*!
  343. * \internal
  344. * \brief Add a reference from mod to dep.
  345. *
  346. * \param mod Owner of the new reference.
  347. * \param dep Module to reference
  348. * \param missing Vector to store name of \a dep if it is not running.
  349. *
  350. * This function returns failure if \a dep is not running and \a missing
  351. * is NULL. If \a missing is not NULL errors will only be returned for
  352. * allocation failures.
  353. *
  354. * \retval 0 Success
  355. * \retval -1 Failure
  356. *
  357. * \note Adding a second reference to the same dep will return success
  358. * without doing anything.
  359. */
  360. static int module_reffed_deps_add(struct ast_module *mod, struct ast_module *dep,
  361. struct ast_vector_const_string *missing)
  362. {
  363. if (!dep->flags.running) {
  364. return !missing ? -1 : AST_VECTOR_APPEND(missing, dep->info->name);
  365. }
  366. if (AST_VECTOR_GET_CMP(&mod->reffed_deps, dep, AST_VECTOR_ELEM_DEFAULT_CMP)) {
  367. /* Skip duplicate. */
  368. return 0;
  369. }
  370. if (AST_VECTOR_APPEND(&mod->reffed_deps, dep)) {
  371. return -1;
  372. }
  373. ast_module_ref(dep);
  374. return 0;
  375. }
  376. /*!
  377. * \internal
  378. * \brief Add references for modules that enhance a dependency.
  379. *
  380. * \param mod Owner of the new references.
  381. * \param dep Module to check for enhancers.
  382. * \param missing Vector to store name of any enhancer that is not running or declined.
  383. *
  384. * \retval 0 Success
  385. * \retval -1 Failure
  386. */
  387. static int module_reffed_deps_add_dep_enhancers(struct ast_module *mod,
  388. struct ast_module *dep, struct ast_vector_const_string *missing)
  389. {
  390. struct ast_module *cur;
  391. AST_DLLIST_TRAVERSE(&module_list, cur, entry) {
  392. if (cur->flags.declined) {
  393. continue;
  394. }
  395. if (!AST_VECTOR_GET_CMP(&cur->enhances, dep->info->name, !strcasecmp)) {
  396. /* dep is not enhanced by cur. */
  397. continue;
  398. }
  399. /* dep is enhanced by cur, therefore mod requires cur. */
  400. if (module_reffed_deps_add(mod, cur, missing)) {
  401. return -1;
  402. }
  403. }
  404. return 0;
  405. }
  406. /*!
  407. * \internal
  408. * \brief Add references to a list of dependencies.
  409. *
  410. * \param mod Owner of the new references.
  411. * \param vec List of required modules to process
  412. * \param missing Vector to store names of modules that are not running.
  413. * \param ref_enhancers Reference all enhancers of each required module.
  414. * \param isoptional Modules that are not loaded can be ignored.
  415. *
  416. * \retval 0 Success
  417. * \retval -1 Failure
  418. */
  419. static int module_deps_process_reqlist(struct ast_module *mod,
  420. struct ast_vector_string *vec, struct ast_vector_const_string *missing,
  421. int ref_enhancers, int isoptional)
  422. {
  423. int idx;
  424. for (idx = 0; idx < AST_VECTOR_SIZE(vec); idx++) {
  425. const char *depname = AST_VECTOR_GET(vec, idx);
  426. struct ast_module *dep = find_resource(depname, 0);
  427. if (!dep || !dep->flags.running) {
  428. if (isoptional && !dep) {
  429. continue;
  430. }
  431. if (missing && !AST_VECTOR_APPEND(missing, depname)) {
  432. continue;
  433. }
  434. return -1;
  435. }
  436. if (module_reffed_deps_add(mod, dep, missing)) {
  437. return -1;
  438. }
  439. if (ref_enhancers && module_reffed_deps_add_dep_enhancers(mod, dep, missing)) {
  440. return -1;
  441. }
  442. }
  443. return 0;
  444. }
  445. /*!
  446. * \internal
  447. * \brief Grab all references required to start the module.
  448. *
  449. * \param mod The module we're trying to start.
  450. * \param missing Vector to store a list of missing dependencies.
  451. *
  452. * \retval 0 Success
  453. * \retval -1 Failure
  454. *
  455. * \note module_list must be locked.
  456. *
  457. * \note Caller is responsible for initializing and freeing the vector.
  458. * Elements are safely read only while module_list remains locked.
  459. */
  460. static int module_deps_reference(struct ast_module *mod, struct ast_vector_const_string *missing)
  461. {
  462. int res = 0;
  463. /* Grab references to modules we enhance but not other enhancements. */
  464. res |= module_deps_process_reqlist(mod, &mod->enhances, missing, 0, 0);
  465. /* Grab references to modules we require plus enhancements. */
  466. res |= module_deps_process_reqlist(mod, &mod->requires, missing, 1, 0);
  467. /* Grab references to optional modules including enhancements. */
  468. res |= module_deps_process_reqlist(mod, &mod->optional_modules, missing, 1, 1);
  469. return res;
  470. }
  471. /*!
  472. * \brief Recursively find required dependencies that are not running.
  473. *
  474. * \param mod Module to scan for dependencies.
  475. * \param missingdeps Vector listing modules that must be started first.
  476. *
  477. * \retval 0 All dependencies resolved.
  478. * \retval -1 Failed to resolve some dependencies.
  479. *
  480. * An error from this function usually means a required module is not even
  481. * loaded. This function is safe from infinite recursion, but dependency
  482. * loops are not reported as an error from here. On success missingdeps
  483. * will contain a list of every module that needs to be running before this
  484. * module can start. missingdeps is sorted by load priority so any missing
  485. * dependencies can be started if needed.
  486. */
  487. static int module_deps_missing_recursive(struct ast_module *mod, struct module_vector *missingdeps)
  488. {
  489. int i = 0;
  490. int res = -1;
  491. struct ast_vector_const_string localdeps;
  492. struct ast_module *dep;
  493. /*
  494. * localdeps stores a copy of all dependencies that mod could not reference.
  495. * First we discard modules that we've already found. We add all newly found
  496. * modules to the missingdeps vector then scan them recursively. This will
  497. * ensure we quickly run out of stuff to do.
  498. */
  499. AST_VECTOR_INIT(&localdeps, 0);
  500. if (module_deps_reference(mod, &localdeps)) {
  501. goto clean_return;
  502. }
  503. while (i < AST_VECTOR_SIZE(&localdeps)) {
  504. dep = find_resource(AST_VECTOR_GET(&localdeps, i), 0);
  505. if (!dep) {
  506. goto clean_return;
  507. }
  508. if (AST_VECTOR_GET_CMP(missingdeps, dep, AST_VECTOR_ELEM_DEFAULT_CMP)) {
  509. /* Skip common dependency. We have already searched it. */
  510. AST_VECTOR_REMOVE(&localdeps, i, 0);
  511. } else {
  512. /* missingdeps is the real list so keep it sorted. */
  513. if (AST_VECTOR_ADD_SORTED(missingdeps, dep, module_vector_cmp)) {
  514. goto clean_return;
  515. }
  516. i++;
  517. }
  518. }
  519. res = 0;
  520. for (i = 0; !res && i < AST_VECTOR_SIZE(&localdeps); i++) {
  521. dep = find_resource(AST_VECTOR_GET(&localdeps, i), 0);
  522. /* We've already confirmed dep is loaded in the first loop. */
  523. res = module_deps_missing_recursive(dep, missingdeps);
  524. }
  525. clean_return:
  526. AST_VECTOR_FREE(&localdeps);
  527. return res;
  528. }
  529. const char *ast_module_name(const struct ast_module *mod)
  530. {
  531. if (!mod || !mod->info) {
  532. return NULL;
  533. }
  534. return mod->info->name;
  535. }
  536. struct loadupdate {
  537. int (*updater)(void);
  538. AST_LIST_ENTRY(loadupdate) entry;
  539. };
  540. static AST_DLLIST_HEAD_STATIC(updaters, loadupdate);
  541. AST_MUTEX_DEFINE_STATIC(reloadlock);
  542. struct reload_queue_item {
  543. AST_LIST_ENTRY(reload_queue_item) entry;
  544. char module[0];
  545. };
  546. static int do_full_reload = 0;
  547. static AST_DLLIST_HEAD_STATIC(reload_queue, reload_queue_item);
  548. /*!
  549. * \internal
  550. *
  551. * This variable is set by load_dynamic_module so ast_module_register
  552. * can know what pointer is being registered.
  553. *
  554. * This is protected by the module_list lock.
  555. */
  556. static struct ast_module * volatile resource_being_loaded;
  557. /*!
  558. * \internal
  559. * \brief Used by AST_MODULE_INFO to register with the module loader.
  560. *
  561. * This function is automatically called when each module is opened.
  562. * It must never be used from outside AST_MODULE_INFO.
  563. */
  564. void ast_module_register(const struct ast_module_info *info)
  565. {
  566. struct ast_module *mod;
  567. if (!loader_ready) {
  568. mod = ast_std_calloc(1, sizeof(*mod) + strlen(info->name) + 1);
  569. if (!mod) {
  570. /* We haven't even reached main() yet, if we can't
  571. * allocate memory at this point just give up. */
  572. fprintf(stderr, "Allocation failure during startup.\n");
  573. exit(2);
  574. }
  575. strcpy(mod->resource, info->name); /* safe */
  576. mod->info = info;
  577. mod->flags.builtin = 1;
  578. AST_DLLIST_INSERT_TAIL(&builtin_module_list, mod, entry);
  579. /* ast_module_register for built-in modules is run again during module preload. */
  580. return;
  581. }
  582. /*
  583. * This lock protects resource_being_loaded as well as the module
  584. * list. Normally we already have a lock on module_list when we
  585. * begin the load but locking again from here prevents corruption
  586. * if an asterisk module is dlopen'ed from outside the module loader.
  587. */
  588. AST_DLLIST_LOCK(&module_list);
  589. mod = resource_being_loaded;
  590. if (!mod) {
  591. AST_DLLIST_UNLOCK(&module_list);
  592. return;
  593. }
  594. ast_debug(5, "Registering module %s\n", info->name);
  595. /* This tells load_dynamic_module that we're registered. */
  596. resource_being_loaded = NULL;
  597. mod->info = info;
  598. if (ast_opt_ref_debug) {
  599. mod->ref_debug = ao2_t_alloc_options(0, NULL, AO2_ALLOC_OPT_LOCK_NOLOCK, info->name);
  600. }
  601. AST_LIST_HEAD_INIT(&mod->users);
  602. AST_VECTOR_INIT(&mod->requires, 0);
  603. AST_VECTOR_INIT(&mod->optional_modules, 0);
  604. AST_VECTOR_INIT(&mod->enhances, 0);
  605. AST_VECTOR_INIT(&mod->reffed_deps, 0);
  606. AST_DLLIST_INSERT_TAIL(&module_list, mod, entry);
  607. AST_DLLIST_UNLOCK(&module_list);
  608. /* give the module a copy of its own handle, for later use in registrations and the like */
  609. *((struct ast_module **) &(info->self)) = mod;
  610. #if defined(HAVE_PERMANENT_DLOPEN)
  611. if (mod->flags.builtin != 1) {
  612. struct info_list_obj *obj_tmp = ao2_find(info_list, info->name,
  613. OBJ_SEARCH_KEY);
  614. if (!obj_tmp) {
  615. obj_tmp = info_list_obj_alloc(info->name, info);
  616. if (obj_tmp) {
  617. ao2_link(info_list, obj_tmp);
  618. ao2_ref(obj_tmp, -1);
  619. }
  620. } else {
  621. ao2_ref(obj_tmp, -1);
  622. }
  623. }
  624. #endif
  625. }
  626. static int module_post_register(struct ast_module *mod)
  627. {
  628. int res;
  629. /* Split lists from mod->info. */
  630. res = ast_vector_string_split(&mod->requires, mod->info->requires, ",", 0, strcasecmp);
  631. res |= ast_vector_string_split(&mod->optional_modules, mod->info->optional_modules, ",", 0, strcasecmp);
  632. res |= ast_vector_string_split(&mod->enhances, mod->info->enhances, ",", 0, strcasecmp);
  633. return res;
  634. }
  635. static void module_destroy(struct ast_module *mod)
  636. {
  637. AST_VECTOR_CALLBACK_VOID(&mod->requires, ast_free);
  638. AST_VECTOR_FREE(&mod->requires);
  639. AST_VECTOR_CALLBACK_VOID(&mod->optional_modules, ast_free);
  640. AST_VECTOR_FREE(&mod->optional_modules);
  641. AST_VECTOR_CALLBACK_VOID(&mod->enhances, ast_free);
  642. AST_VECTOR_FREE(&mod->enhances);
  643. /* Release references to all dependencies. */
  644. AST_VECTOR_CALLBACK_VOID(&mod->reffed_deps, ast_module_unref);
  645. AST_VECTOR_FREE(&mod->reffed_deps);
  646. AST_LIST_HEAD_DESTROY(&mod->users);
  647. ao2_cleanup(mod->ref_debug);
  648. if (mod->flags.builtin) {
  649. ast_std_free(mod);
  650. } else {
  651. ast_free(mod);
  652. }
  653. }
  654. void ast_module_unregister(const struct ast_module_info *info)
  655. {
  656. struct ast_module *mod = NULL;
  657. /* it is assumed that the users list in the module structure
  658. will already be empty, or we cannot have gotten to this
  659. point
  660. */
  661. AST_DLLIST_LOCK(&module_list);
  662. AST_DLLIST_TRAVERSE_BACKWARDS_SAFE_BEGIN(&module_list, mod, entry) {
  663. if (mod->info == info) {
  664. AST_DLLIST_REMOVE_CURRENT(entry);
  665. break;
  666. }
  667. }
  668. AST_DLLIST_TRAVERSE_BACKWARDS_SAFE_END;
  669. AST_DLLIST_UNLOCK(&module_list);
  670. if (mod && !mod->usecount) {
  671. /*
  672. * We are intentionally leaking mod if usecount is not zero.
  673. * This is necessary if the module is being forcefully unloaded.
  674. * In addition module_destroy is not safe to run after exit()
  675. * is called. ast_module_unregister is run during cleanup of
  676. * the process when libc releases each module's shared object
  677. * library.
  678. */
  679. ast_debug(5, "Unregistering module %s\n", info->name);
  680. module_destroy(mod);
  681. }
  682. }
  683. struct ast_module_user *__ast_module_user_add(struct ast_module *mod, struct ast_channel *chan)
  684. {
  685. struct ast_module_user *u;
  686. u = ast_calloc(1, sizeof(*u));
  687. if (!u) {
  688. return NULL;
  689. }
  690. u->chan = chan;
  691. AST_LIST_LOCK(&mod->users);
  692. AST_LIST_INSERT_HEAD(&mod->users, u, entry);
  693. AST_LIST_UNLOCK(&mod->users);
  694. if (mod->ref_debug) {
  695. ao2_ref(mod->ref_debug, +1);
  696. }
  697. ast_atomic_fetchadd_int(&mod->usecount, +1);
  698. ast_update_use_count();
  699. return u;
  700. }
  701. void __ast_module_user_remove(struct ast_module *mod, struct ast_module_user *u)
  702. {
  703. if (!u) {
  704. return;
  705. }
  706. AST_LIST_LOCK(&mod->users);
  707. u = AST_LIST_REMOVE(&mod->users, u, entry);
  708. AST_LIST_UNLOCK(&mod->users);
  709. if (!u) {
  710. /*
  711. * Was not in the list. Either a bad pointer or
  712. * __ast_module_user_hangup_all() has been called.
  713. */
  714. return;
  715. }
  716. if (mod->ref_debug) {
  717. ao2_ref(mod->ref_debug, -1);
  718. }
  719. ast_atomic_fetchadd_int(&mod->usecount, -1);
  720. ast_free(u);
  721. ast_update_use_count();
  722. }
  723. void __ast_module_user_hangup_all(struct ast_module *mod)
  724. {
  725. struct ast_module_user *u;
  726. AST_LIST_LOCK(&mod->users);
  727. while ((u = AST_LIST_REMOVE_HEAD(&mod->users, entry))) {
  728. if (u->chan) {
  729. ast_softhangup(u->chan, AST_SOFTHANGUP_APPUNLOAD);
  730. }
  731. if (mod->ref_debug) {
  732. ao2_ref(mod->ref_debug, -1);
  733. }
  734. ast_atomic_fetchadd_int(&mod->usecount, -1);
  735. ast_free(u);
  736. }
  737. AST_LIST_UNLOCK(&mod->users);
  738. ast_update_use_count();
  739. }
  740. static int printdigest(const unsigned char *d)
  741. {
  742. int x, pos;
  743. char buf[256]; /* large enough so we don't have to worry */
  744. for (pos = 0, x = 0; x < 16; x++)
  745. pos += sprintf(buf + pos, " %02hhx", *d++);
  746. ast_debug(1, "Unexpected signature:%s\n", buf);
  747. return 0;
  748. }
  749. #define key_matches(a, b) (memcmp((a), (b), 16) == 0)
  750. static int verify_key(const unsigned char *key)
  751. {
  752. struct MD5Context c;
  753. unsigned char digest[16];
  754. MD5Init(&c);
  755. MD5Update(&c, key, strlen((char *)key));
  756. MD5Final(digest, &c);
  757. if (key_matches(expected_key, digest))
  758. return 0;
  759. printdigest(digest);
  760. return -1;
  761. }
  762. static size_t resource_name_baselen(const char *name)
  763. {
  764. size_t len = strlen(name);
  765. if (len > 3 && !strcasecmp(name + len - 3, ".so")) {
  766. return len - 3;
  767. }
  768. return len;
  769. }
  770. static int resource_name_match(const char *name1, size_t baselen1, const char *name2)
  771. {
  772. if (baselen1 != resource_name_baselen(name2)) {
  773. return -1;
  774. }
  775. return strncasecmp(name1, name2, baselen1);
  776. }
  777. static struct ast_module *find_resource(const char *resource, int do_lock)
  778. {
  779. struct ast_module *cur;
  780. size_t resource_baselen = resource_name_baselen(resource);
  781. if (do_lock) {
  782. AST_DLLIST_LOCK(&module_list);
  783. }
  784. AST_DLLIST_TRAVERSE(&module_list, cur, entry) {
  785. if (!resource_name_match(resource, resource_baselen, cur->resource)) {
  786. break;
  787. }
  788. }
  789. if (do_lock) {
  790. AST_DLLIST_UNLOCK(&module_list);
  791. }
  792. return cur;
  793. }
  794. /*!
  795. * \brief dlclose(), with failure logging.
  796. */
  797. static void logged_dlclose(const char *name, void *lib)
  798. {
  799. char *error;
  800. if (!lib) {
  801. return;
  802. }
  803. /* Clear any existing error */
  804. dlerror();
  805. if (dlclose(lib)) {
  806. error = dlerror();
  807. ast_log(AST_LOG_ERROR, "Failure in dlclose for module '%s': %s\n",
  808. S_OR(name, "unknown"), S_OR(error, "Unknown error"));
  809. #if defined(HAVE_PERMANENT_DLOPEN)
  810. } else {
  811. manual_mod_unreg(name);
  812. #endif
  813. }
  814. }
  815. #if defined(HAVE_RTLD_NOLOAD)
  816. /*!
  817. * \brief Check to see if the given resource is loaded.
  818. *
  819. * \param resource_name Name of the resource, including .so suffix.
  820. * \return False (0) if module is not loaded.
  821. * \return True (non-zero) if module is loaded.
  822. */
  823. static int is_module_loaded(const char *resource_name)
  824. {
  825. char fn[PATH_MAX] = "";
  826. void *lib;
  827. snprintf(fn, sizeof(fn), "%s/%s", ast_config_AST_MODULE_DIR,
  828. resource_name);
  829. lib = dlopen(fn, RTLD_LAZY | RTLD_NOLOAD);
  830. if (lib) {
  831. logged_dlclose(resource_name, lib);
  832. return 1;
  833. }
  834. return 0;
  835. }
  836. #endif
  837. static void unload_dynamic_module(struct ast_module *mod)
  838. {
  839. #if defined(HAVE_RTLD_NOLOAD)
  840. char *name = ast_strdupa(ast_module_name(mod));
  841. #endif
  842. void *lib = mod->lib;
  843. /* WARNING: the structure pointed to by mod is going to
  844. disappear when this operation succeeds, so we can't
  845. dereference it */
  846. logged_dlclose(ast_module_name(mod), lib);
  847. /* There are several situations where the module might still be resident
  848. * in memory.
  849. *
  850. * If somehow there was another dlopen() on the same module (unlikely,
  851. * since that all is supposed to happen in loader.c).
  852. *
  853. * Avoid the temptation of repeating the dlclose(). The other code that
  854. * dlopened the module still has its module reference, and should close
  855. * it itself. In other situations, dlclose() will happily return success
  856. * for as many times as you wish to call it.
  857. */
  858. #if defined(HAVE_RTLD_NOLOAD)
  859. if (is_module_loaded(name)) {
  860. ast_log(LOG_WARNING, "Module '%s' could not be completely unloaded\n", name);
  861. }
  862. #endif
  863. }
  864. static int load_dlopen_missing(struct ast_str **list, struct ast_vector_string *deps)
  865. {
  866. int i;
  867. int c = 0;
  868. for (i = 0; i < AST_VECTOR_SIZE(deps); i++) {
  869. const char *dep = AST_VECTOR_GET(deps, i);
  870. if (!find_resource(dep, 0)) {
  871. STR_APPEND_TEXT(dep, list);
  872. c++;
  873. }
  874. }
  875. return c;
  876. }
  877. /*!
  878. * \internal
  879. * \brief Attempt to dlopen a module.
  880. *
  881. * \param resource_in The module name to load.
  882. * \param so_ext ".so" or blank if ".so" is already part of resource_in.
  883. * \param filename Passed directly to dlopen.
  884. * \param flags Passed directly to dlopen.
  885. * \param suppress_logging Do not log any error from dlopen.
  886. *
  887. * \return Pointer to opened module, NULL on error.
  888. *
  889. * \warning module_list must be locked before calling this function.
  890. */
  891. static struct ast_module *load_dlopen(const char *resource_in, const char *so_ext,
  892. const char *filename, int flags, unsigned int suppress_logging)
  893. {
  894. struct ast_module *mod;
  895. ast_assert(!resource_being_loaded);
  896. mod = ast_calloc(1, sizeof(*mod) + strlen(resource_in) + strlen(so_ext) + 1);
  897. if (!mod) {
  898. return NULL;
  899. }
  900. sprintf(mod->resource, "%s%s", resource_in, so_ext); /* safe */
  901. resource_being_loaded = mod;
  902. mod->lib = dlopen(filename, flags);
  903. #if defined(HAVE_PERMANENT_DLOPEN)
  904. manual_mod_reg(mod->lib, mod->resource);
  905. #endif
  906. if (resource_being_loaded) {
  907. struct ast_str *list;
  908. int c = 0;
  909. const char *dlerror_msg = ast_strdupa(S_OR(dlerror(), ""));
  910. resource_being_loaded = NULL;
  911. if (mod->lib) {
  912. module_load_error("Module '%s' did not register itself during load\n", resource_in);
  913. logged_dlclose(resource_in, mod->lib);
  914. goto error_return;
  915. }
  916. if (suppress_logging) {
  917. goto error_return;
  918. }
  919. resource_being_loaded = mod;
  920. mod->lib = dlopen(filename, RTLD_LAZY | RTLD_LOCAL);
  921. #if defined(HAVE_PERMANENT_DLOPEN)
  922. manual_mod_reg(mod->lib, mod->resource);
  923. #endif
  924. if (resource_being_loaded) {
  925. resource_being_loaded = NULL;
  926. module_load_error("Error loading module '%s': %s\n", resource_in, dlerror_msg);
  927. logged_dlclose(resource_in, mod->lib);
  928. goto error_return;
  929. }
  930. list = ast_str_create(64);
  931. if (list) {
  932. if (module_post_register(mod)) {
  933. goto loaded_error;
  934. }
  935. c = load_dlopen_missing(&list, &mod->requires);
  936. c += load_dlopen_missing(&list, &mod->enhances);
  937. #ifndef OPTIONAL_API
  938. c += load_dlopen_missing(&list, &mod->optional_modules);
  939. #endif
  940. }
  941. if (list && ast_str_strlen(list)) {
  942. module_load_error("Error loading module '%s', missing %s: %s\n",
  943. resource_in, c == 1 ? "dependency" : "dependencies", ast_str_buffer(list));
  944. } else {
  945. module_load_error("Error loading module '%s': %s\n", resource_in, dlerror_msg);
  946. }
  947. loaded_error:
  948. ast_free(list);
  949. unload_dynamic_module(mod);
  950. return NULL;
  951. error_return:
  952. ast_free(mod);
  953. return NULL;
  954. }
  955. return mod;
  956. }
  957. static struct ast_module *load_dynamic_module(const char *resource_in, unsigned int suppress_logging)
  958. {
  959. char fn[PATH_MAX];
  960. struct ast_module *mod;
  961. size_t resource_in_len = strlen(resource_in);
  962. const char *so_ext = "";
  963. if (resource_in_len < 4 || strcasecmp(resource_in + resource_in_len - 3, ".so")) {
  964. so_ext = ".so";
  965. }
  966. snprintf(fn, sizeof(fn), "%s/%s%s", ast_config_AST_MODULE_DIR, resource_in, so_ext);
  967. /* Try loading in quiet mode first with RTLD_LOCAL. The majority of modules do not
  968. * export symbols so this allows the least number of calls to dlopen. */
  969. mod = load_dlopen(resource_in, so_ext, fn, RTLD_NOW | RTLD_LOCAL, suppress_logging);
  970. if (!mod || !ast_test_flag(mod->info, AST_MODFLAG_GLOBAL_SYMBOLS)) {
  971. return mod;
  972. }
  973. /* Close the module so we can reopen with correct flags. */
  974. logged_dlclose(resource_in, mod->lib);
  975. return load_dlopen(resource_in, so_ext, fn, RTLD_NOW | RTLD_GLOBAL, 0);
  976. }
  977. int modules_shutdown(void)
  978. {
  979. struct ast_module *mod;
  980. int somethingchanged;
  981. int res;
  982. AST_DLLIST_LOCK(&module_list);
  983. /*!\note Some resources, like timers, are started up dynamically, and thus
  984. * may be still in use, even if all channels are dead. We must therefore
  985. * check the usecount before asking modules to unload. */
  986. do {
  987. /* Reset flag before traversing the list */
  988. somethingchanged = 0;
  989. AST_DLLIST_TRAVERSE_BACKWARDS_SAFE_BEGIN(&module_list, mod, entry) {
  990. if (mod->usecount) {
  991. ast_debug(1, "Passing on %s: its use count is %d\n",
  992. mod->resource, mod->usecount);
  993. continue;
  994. }
  995. AST_DLLIST_REMOVE_CURRENT(entry);
  996. if (mod->flags.running && !mod->flags.declined && mod->info->unload) {
  997. ast_verb(4, "Unloading %s\n", mod->resource);
  998. mod->info->unload();
  999. }
  1000. module_destroy(mod);
  1001. somethingchanged = 1;
  1002. }
  1003. AST_DLLIST_TRAVERSE_BACKWARDS_SAFE_END;
  1004. if (!somethingchanged) {
  1005. AST_DLLIST_TRAVERSE(&module_list, mod, entry) {
  1006. if (mod->flags.keepuntilshutdown) {
  1007. ast_module_unref(mod);
  1008. mod->flags.keepuntilshutdown = 0;
  1009. somethingchanged = 1;
  1010. }
  1011. }
  1012. }
  1013. } while (somethingchanged);
  1014. res = AST_DLLIST_EMPTY(&module_list);
  1015. AST_DLLIST_UNLOCK(&module_list);
  1016. return !res;
  1017. }
  1018. /*!
  1019. * \brief Whether or not this module should be able to be unloaded successfully,
  1020. * if we recursively unload any modules that are dependent on it.
  1021. * \note module_list should be locked when calling this
  1022. * \retval 0 if not, 1 if likely possible
  1023. */
  1024. static int graceful_unload_possible(struct ast_module *target, struct ast_vector_const_string *dependents)
  1025. {
  1026. struct ast_module *mod;
  1027. int usecount = target->usecount;
  1028. /* Check the reffed_deps of each module to see if we're one of them. */
  1029. AST_DLLIST_TRAVERSE(&module_list, mod, entry) {
  1030. if (AST_VECTOR_GET_CMP(&mod->reffed_deps, target, AST_VECTOR_ELEM_DEFAULT_CMP)) {
  1031. const char *name;
  1032. /* This module is dependent on the target.
  1033. * If we can unload this module gracefully,
  1034. * then that would decrement our use count.
  1035. * If any single module could not be unloaded gracefully,
  1036. * then we don't proceed. */
  1037. int unloadable;
  1038. if (AST_VECTOR_GET_CMP(dependents, ast_module_name(mod), !strcasecmp)) {
  1039. /* Already in our list, we already checked this module,
  1040. * and we gave it the green light. */
  1041. ast_debug(3, "Skipping duplicate dependent %s\n", ast_module_name(mod));
  1042. if (!--usecount) {
  1043. break;
  1044. }
  1045. continue;
  1046. }
  1047. unloadable = graceful_unload_possible(mod, dependents);
  1048. if (!unloadable) {
  1049. ast_log(LOG_NOTICE, "Can't unload %s right now because %s is dependent on it\n", ast_module_name(target), ast_module_name(mod));
  1050. return 0;
  1051. }
  1052. /* Insert at beginning, so later if we're loading modules again automatically, we can do so in the same order. */
  1053. name = ast_strdup(ast_module_name(mod));
  1054. if (!name) {
  1055. return 0;
  1056. }
  1057. ast_debug(3, "Found new dependent %s\n", ast_module_name(mod));
  1058. if (AST_VECTOR_INSERT_AT(dependents, 0, name)) {
  1059. ast_log(LOG_ERROR, "Failed to add module '%s' to vector\n", ast_module_name(mod));
  1060. return 0;
  1061. }
  1062. if (!--usecount) {
  1063. break;
  1064. }
  1065. }
  1066. }
  1067. if (usecount) {
  1068. ast_log(LOG_NOTICE, "Module %s cannot be unloaded (would still have use count %d/%d after unloading dependents)\n", ast_module_name(target), usecount, target->usecount);
  1069. return 0;
  1070. }
  1071. return 1;
  1072. }
  1073. /*!
  1074. * \brief Unload a resource
  1075. * \param resource_name Module name
  1076. * \param force
  1077. * \param recursive Whether to attempt to recursively unload dependents of this module and load them again afterwards
  1078. * \param dependents. Can be NULL if autounload is 0.
  1079. * \retval 0 on success, -1 on failure
  1080. */
  1081. static int auto_unload_resource(const char *resource_name, enum ast_module_unload_mode force, int recursive, struct ast_vector_const_string *dependents)
  1082. {
  1083. struct ast_module *mod;
  1084. int res = -1;
  1085. int error = 0;
  1086. AST_DLLIST_LOCK(&module_list);
  1087. if (!(mod = find_resource(resource_name, 0))) {
  1088. AST_DLLIST_UNLOCK(&module_list);
  1089. ast_log(LOG_WARNING, "Unload failed, '%s' could not be found\n", resource_name);
  1090. return -1;
  1091. }
  1092. if (!mod->flags.running || mod->flags.declined) {
  1093. /* If the user asks to unload a module that didn't load, obey.
  1094. * Otherwise, we never dlclose() modules that fail to load,
  1095. * which means if the module (shared object) is updated,
  1096. * we can't load the updated module since we never dlclose()'d it.
  1097. * Accordingly, obey the unload request so we can load the module
  1098. * from scratch next time.
  1099. */
  1100. ast_log(LOG_NOTICE, "Unloading module '%s' that previously declined to load\n", resource_name);
  1101. error = 0;
  1102. res = 0;
  1103. goto exit; /* Skip all the intervening !error checks, only the last one is relevant. */
  1104. }
  1105. if (!error && mod->usecount > 0 && recursive) {
  1106. /* Try automatically unloading all modules dependent on the module we're trying to unload,
  1107. * and then, optionally, load them back again if we end up loading this module again.
  1108. * If any modules that have us as a dependency can't be unloaded, for whatever reason,
  1109. * then the entire unload operation will fail, so to try to make this an atomic operation
  1110. * and avoid leaving modules in a partial unload state, first check if we think we're going
  1111. * to be able to pull this off, and if not, abort.
  1112. *
  1113. * A race condition is technically still possible, if some depending module suddenly goes in use
  1114. * between this check and trying to unload it, but this takes care of the majority of
  1115. * easy-to-avoid cases that would fail eventually anyways.
  1116. *
  1117. * Note that we can encounter false negatives (e.g. unloading all the dependents would allow
  1118. * a module to unload, but graceful_unload_possible returns 0). This is because it's only
  1119. * checking direct module dependencies; other dependencies caused by a module registering
  1120. * a resource that cause its ref count to get bumped aren't accounted for here.
  1121. */
  1122. if (graceful_unload_possible(mod, dependents)) {
  1123. int i, res = 0;
  1124. size_t num_deps = AST_VECTOR_SIZE(dependents);
  1125. ast_debug(1, "%lu module%s will need to be unloaded\n", AST_VECTOR_SIZE(dependents), ESS(AST_VECTOR_SIZE(dependents)));
  1126. /* Unload from the end, since the last module was the first one added, which means it isn't a dependency of anything else. */
  1127. for (i = AST_VECTOR_SIZE(dependents) - 1; i >= 0; i--) {
  1128. const char *depname = AST_VECTOR_GET(dependents, i);
  1129. res = ast_unload_resource(depname, force);
  1130. if (res) {
  1131. ast_log(LOG_WARNING, "Failed to unload %lu module%s automatically (%s could not be unloaded)\n", num_deps, ESS(num_deps), depname);
  1132. /* To be polite, load modules that we already unloaded,
  1133. * to try to leave things the way they were when we started. */
  1134. for (i++; i < num_deps; i++) {
  1135. const char *depname = AST_VECTOR_GET(dependents, i);
  1136. res = ast_load_resource(depname);
  1137. if (res) {
  1138. ast_log(LOG_WARNING, "Could not load module '%s' again automatically\n", depname);
  1139. }
  1140. }
  1141. break;
  1142. }
  1143. }
  1144. /* Either we failed, or we successfully unloaded everything.
  1145. * If we succeeded, we can now proceed and unload ourselves. */
  1146. }
  1147. }
  1148. if (!error && (mod->usecount > 0)) {
  1149. if (force) {
  1150. ast_log(LOG_WARNING, "Warning: Forcing removal of module '%s' with use count %d\n", resource_name, mod->usecount);
  1151. } else {
  1152. ast_log(LOG_WARNING, "%s unload failed, '%s' has use count %d\n", recursive ? "Recursive soft" : "Soft", resource_name, mod->usecount);
  1153. error = 1;
  1154. }
  1155. }
  1156. if (!error) {
  1157. /* Request any channels attached to the module to hangup. */
  1158. __ast_module_user_hangup_all(mod);
  1159. ast_verb(4, "Unloading %s\n", mod->resource);
  1160. res = mod->info->unload();
  1161. if (res) {
  1162. ast_log(LOG_WARNING, "Firm unload failed for %s\n", resource_name);
  1163. if (force <= AST_FORCE_FIRM) {
  1164. error = 1;
  1165. } else {
  1166. ast_log(LOG_WARNING, "** Dangerous **: Unloading resource anyway, at user request\n");
  1167. }
  1168. }
  1169. if (!error) {
  1170. /*
  1171. * Request hangup on any channels that managed to get attached
  1172. * while we called the module unload function.
  1173. */
  1174. __ast_module_user_hangup_all(mod);
  1175. sched_yield();
  1176. }
  1177. }
  1178. if (!error)
  1179. mod->flags.running = mod->flags.declined = 0;
  1180. exit:
  1181. AST_DLLIST_UNLOCK(&module_list);
  1182. if (!error) {
  1183. unload_dynamic_module(mod);
  1184. ast_test_suite_event_notify("MODULE_UNLOAD", "Message: %s", resource_name);
  1185. ast_update_use_count();
  1186. publish_unload_message(resource_name, "Success");
  1187. }
  1188. return res;
  1189. }
  1190. int ast_refresh_resource(const char *resource_name, enum ast_module_unload_mode force, int recursive)
  1191. {
  1192. if (recursive) {
  1193. /* Recursively unload dependents of this module and then load them back again */
  1194. int res, i;
  1195. struct ast_vector_const_string dependents;
  1196. AST_VECTOR_INIT(&dependents, 0);
  1197. res = auto_unload_resource(resource_name, force, recursive, &dependents);
  1198. if (res) {
  1199. AST_VECTOR_FREE(&dependents);
  1200. return 1;
  1201. }
  1202. /* Start by loading the target again. */
  1203. if (ast_load_resource(resource_name)) {
  1204. ast_log(LOG_WARNING, "Failed to load module '%s' again automatically\n", resource_name);
  1205. AST_VECTOR_FREE(&dependents);
  1206. return -1;
  1207. }
  1208. res = 0;
  1209. /* Finally, load again any modules we had to unload in order to refresh the target.
  1210. * We must load modules in the reverse order that we unloaded them,
  1211. * to preserve dependency requirements. */
  1212. for (i = 0; i < AST_VECTOR_SIZE(&dependents); i++) {
  1213. const char *depname = AST_VECTOR_GET(&dependents, i);
  1214. int mres = ast_load_resource(depname);
  1215. if (mres) {
  1216. ast_log(LOG_WARNING, "Could not load module '%s' again automatically\n", depname);
  1217. }
  1218. res |= mres;
  1219. }
  1220. AST_VECTOR_FREE(&dependents);
  1221. return res ? -1 : 0;
  1222. }
  1223. /* Simple case: just unload and load the module again */
  1224. if (ast_unload_resource(resource_name, force)) {
  1225. return 1;
  1226. }
  1227. return ast_load_resource(resource_name);
  1228. }
  1229. int ast_unload_resource(const char *resource_name, enum ast_module_unload_mode force)
  1230. {
  1231. return auto_unload_resource(resource_name, force, 0, NULL);
  1232. }
  1233. static int module_matches_helper_type(struct ast_module *mod, enum ast_module_helper_type type)
  1234. {
  1235. switch (type) {
  1236. case AST_MODULE_HELPER_UNLOAD:
  1237. return !mod->usecount && mod->flags.running && !mod->flags.declined;
  1238. case AST_MODULE_HELPER_RELOAD:
  1239. return mod->flags.running && mod->info->reload;
  1240. case AST_MODULE_HELPER_RUNNING:
  1241. return mod->flags.running;
  1242. case AST_MODULE_HELPER_LOADED:
  1243. /* if we have a 'struct ast_module' then we're loaded. */
  1244. return 1;
  1245. default:
  1246. /* This function is not called for AST_MODULE_HELPER_LOAD. */
  1247. /* Unknown ast_module_helper_type. Assume it doesn't match. */
  1248. ast_assert(0);
  1249. return 0;
  1250. }
  1251. }
  1252. struct module_load_word {
  1253. const char *word;
  1254. size_t len;
  1255. size_t moddir_len;
  1256. };
  1257. static int module_load_helper_on_file(const char *dir_name, const char *filename, void *obj)
  1258. {
  1259. struct module_load_word *word = obj;
  1260. struct ast_module *mod;
  1261. char *filename_merged = NULL;
  1262. /* dir_name will never be shorter than word->moddir_len. */
  1263. dir_name += word->moddir_len;
  1264. if (!ast_strlen_zero(dir_name)) {
  1265. ast_assert(dir_name[0] == '/');
  1266. dir_name += 1;
  1267. if (ast_asprintf(&filename_merged, "%s/%s", dir_name, filename) < 0) {
  1268. /* If we can't allocate the string just give up! */
  1269. return -1;
  1270. }
  1271. filename = filename_merged;
  1272. }
  1273. if (!strncasecmp(filename, word->word, word->len)) {
  1274. /* Don't list files that are already loaded! */
  1275. mod = find_resource(filename, 0);
  1276. if (!mod || !mod->flags.running) {
  1277. ast_cli_completion_add(ast_strdup(filename));
  1278. }
  1279. }
  1280. ast_free(filename_merged);
  1281. return 0;
  1282. }
  1283. static void module_load_helper(const char *word)
  1284. {
  1285. struct module_load_word word_l = {
  1286. .word = word,
  1287. .len = strlen(word),
  1288. .moddir_len = strlen(ast_config_AST_MODULE_DIR),
  1289. };
  1290. AST_DLLIST_LOCK(&module_list);
  1291. ast_file_read_dirs(ast_config_AST_MODULE_DIR, module_load_helper_on_file, &word_l, -1);
  1292. AST_DLLIST_UNLOCK(&module_list);
  1293. }
  1294. char *ast_module_helper(const char *line, const char *word, int pos, int state, int rpos, enum ast_module_helper_type type)
  1295. {
  1296. struct ast_module *mod;
  1297. int which = 0;
  1298. int wordlen = strlen(word);
  1299. char *ret = NULL;
  1300. if (pos != rpos) {
  1301. return NULL;
  1302. }
  1303. /* Tab completion can't be used during startup, or CLI and loader will deadlock. */
  1304. if (!ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
  1305. return NULL;
  1306. }
  1307. if (type == AST_MODULE_HELPER_LOAD) {
  1308. module_load_helper(word);
  1309. return NULL;
  1310. }
  1311. AST_DLLIST_LOCK(&module_list);
  1312. AST_DLLIST_TRAVERSE(&module_list, mod, entry) {
  1313. if (!module_matches_helper_type(mod, type)) {
  1314. continue;
  1315. }
  1316. if (!strncasecmp(word, mod->resource, wordlen) && ++which > state) {
  1317. ret = ast_strdup(mod->resource);
  1318. break;
  1319. }
  1320. }
  1321. AST_DLLIST_UNLOCK(&module_list);
  1322. return ret;
  1323. }
  1324. void ast_process_pending_reloads(void)
  1325. {
  1326. struct reload_queue_item *item;
  1327. modules_loaded = 1;
  1328. AST_LIST_LOCK(&reload_queue);
  1329. if (do_full_reload) {
  1330. do_full_reload = 0;
  1331. AST_LIST_UNLOCK(&reload_queue);
  1332. ast_log(LOG_NOTICE, "Executing deferred reload request.\n");
  1333. ast_module_reload(NULL);
  1334. return;
  1335. }
  1336. while ((item = AST_LIST_REMOVE_HEAD(&reload_queue, entry))) {
  1337. ast_log(LOG_NOTICE, "Executing deferred reload request for module '%s'.\n", item->module);
  1338. ast_module_reload(item->module);
  1339. ast_free(item);
  1340. }
  1341. AST_LIST_UNLOCK(&reload_queue);
  1342. }
  1343. static void queue_reload_request(const char *module)
  1344. {
  1345. struct reload_queue_item *item;
  1346. AST_LIST_LOCK(&reload_queue);
  1347. if (do_full_reload) {
  1348. AST_LIST_UNLOCK(&reload_queue);
  1349. return;
  1350. }
  1351. if (ast_strlen_zero(module)) {
  1352. /* A full reload request (when module is NULL) wipes out any previous
  1353. reload requests and causes the queue to ignore future ones */
  1354. while ((item = AST_LIST_REMOVE_HEAD(&reload_queue, entry))) {
  1355. ast_free(item);
  1356. }
  1357. do_full_reload = 1;
  1358. } else {
  1359. /* No reason to add the same module twice */
  1360. AST_LIST_TRAVERSE(&reload_queue, item, entry) {
  1361. if (!strcasecmp(item->module, module)) {
  1362. AST_LIST_UNLOCK(&reload_queue);
  1363. return;
  1364. }
  1365. }
  1366. item = ast_calloc(1, sizeof(*item) + strlen(module) + 1);
  1367. if (!item) {
  1368. ast_log(LOG_ERROR, "Failed to allocate reload queue item.\n");
  1369. AST_LIST_UNLOCK(&reload_queue);
  1370. return;
  1371. }
  1372. strcpy(item->module, module);
  1373. AST_LIST_INSERT_TAIL(&reload_queue, item, entry);
  1374. }
  1375. AST_LIST_UNLOCK(&reload_queue);
  1376. }
  1377. /*!
  1378. * \since 12
  1379. * \internal
  1380. * \brief Publish a \ref stasis message regarding the type.
  1381. */
  1382. static void publish_load_message_type(const char* type, const char *name, const char *status)
  1383. {
  1384. RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
  1385. RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
  1386. RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
  1387. RAII_VAR(struct ast_json *, event_object, NULL, ast_json_unref);
  1388. ast_assert(type != NULL);
  1389. ast_assert(!ast_strlen_zero(name));
  1390. ast_assert(!ast_strlen_zero(status));
  1391. if (!ast_manager_get_generic_type()) {
  1392. return;
  1393. }
  1394. event_object = ast_json_pack("{s:s, s:s}",
  1395. "Module", name,
  1396. "Status", status);
  1397. json_object = ast_json_pack("{s:s, s:i, s:o}",
  1398. "type", type,
  1399. "class_type", EVENT_FLAG_SYSTEM,
  1400. "event", ast_json_ref(event_object));
  1401. if (!json_object) {
  1402. return;
  1403. }
  1404. payload = ast_json_payload_create(json_object);
  1405. if (!payload) {
  1406. return;
  1407. }
  1408. message = stasis_message_create(ast_manager_get_generic_type(), payload);
  1409. if (!message) {
  1410. return;
  1411. }
  1412. stasis_publish(ast_manager_get_topic(), message);
  1413. }
  1414. static const char* loadresult2str(enum ast_module_load_result result)
  1415. {
  1416. int i;
  1417. for (i = 0; i < ARRAY_LEN(load_results); i++) {
  1418. if (load_results[i].result == result) {
  1419. return load_results[i].name;
  1420. }
  1421. }
  1422. ast_log(LOG_WARNING, "Failed to find correct load result status. result %d\n", result);
  1423. return AST_MODULE_LOAD_UNKNOWN_STRING;
  1424. }
  1425. /*!
  1426. * \internal
  1427. * \brief Publish a \ref stasis message regarding the load result
  1428. */
  1429. static void publish_load_message(const char *name, enum ast_module_load_result result)
  1430. {
  1431. const char *status;
  1432. status = loadresult2str(result);
  1433. publish_load_message_type("Load", name, status);
  1434. }
  1435. /*!
  1436. * \internal
  1437. * \brief Publish a \ref stasis message regarding the unload result
  1438. */
  1439. static void publish_unload_message(const char *name, const char* status)
  1440. {
  1441. publish_load_message_type("Unload", name, status);
  1442. }
  1443. /*!
  1444. * \since 12
  1445. * \internal
  1446. * \brief Publish a \ref stasis message regarding the reload result
  1447. */
  1448. static void publish_reload_message(const char *name, enum ast_module_reload_result result)
  1449. {
  1450. char res_buffer[8];
  1451. snprintf(res_buffer, sizeof(res_buffer), "%u", result);
  1452. publish_load_message_type("Reload", S_OR(name, "All"), res_buffer);
  1453. }
  1454. enum ast_module_reload_result ast_module_reload(const char *name)
  1455. {
  1456. struct ast_module *cur;
  1457. enum ast_module_reload_result res = AST_MODULE_RELOAD_NOT_FOUND;
  1458. size_t name_baselen = name ? resource_name_baselen(name) : 0;
  1459. /* If we aren't fully booted, we just pretend we reloaded but we queue this
  1460. up to run once we are booted up. */
  1461. if (!modules_loaded) {
  1462. queue_reload_request(name);
  1463. res = AST_MODULE_RELOAD_QUEUED;
  1464. goto module_reload_exit;
  1465. }
  1466. if (ast_mutex_trylock(&reloadlock)) {
  1467. ast_verb(3, "The previous reload command didn't finish yet\n");
  1468. res = AST_MODULE_RELOAD_IN_PROGRESS;
  1469. goto module_reload_exit;
  1470. }
  1471. ast_sd_notify("RELOADING=1");
  1472. ast_lastreloadtime = ast_tvnow();
  1473. if (ast_opt_lock_confdir) {
  1474. int try;
  1475. int lockres;
  1476. for (try = 1, lockres = AST_LOCK_TIMEOUT; try < 6 && (lockres == AST_LOCK_TIMEOUT); try++) {
  1477. lockres = ast_lock_path(ast_config_AST_CONFIG_DIR);
  1478. if (lockres == AST_LOCK_TIMEOUT) {
  1479. ast_log(LOG_WARNING, "Failed to grab lock on %s, try %d\n", ast_config_AST_CONFIG_DIR, try);
  1480. }
  1481. }
  1482. if (lockres != AST_LOCK_SUCCESS) {
  1483. ast_log(AST_LOG_WARNING, "Cannot grab lock on %s\n", ast_config_AST_CONFIG_DIR);
  1484. res = AST_MODULE_RELOAD_ERROR;
  1485. goto module_reload_done;
  1486. }
  1487. }
  1488. AST_DLLIST_LOCK(&module_list);
  1489. AST_DLLIST_TRAVERSE(&module_list, cur, entry) {
  1490. const struct ast_module_info *info = cur->info;
  1491. if (name && resource_name_match(name, name_baselen, cur->resource)) {
  1492. continue;
  1493. }
  1494. if (!cur->flags.running || cur->flags.declined) {
  1495. if (res == AST_MODULE_RELOAD_NOT_FOUND) {
  1496. res = AST_MODULE_RELOAD_UNINITIALIZED;
  1497. }
  1498. if (!name) {
  1499. continue;
  1500. }
  1501. break;
  1502. }
  1503. if (!info->reload) { /* cannot be reloaded */
  1504. if (res == AST_MODULE_RELOAD_NOT_FOUND) {
  1505. res = AST_MODULE_RELOAD_NOT_IMPLEMENTED;
  1506. }
  1507. if (!name) {
  1508. continue;
  1509. }
  1510. break;
  1511. }
  1512. ast_verb(3, "Reloading module '%s' (%s)\n", cur->resource, info->description);
  1513. if (info->reload() == AST_MODULE_LOAD_SUCCESS) {
  1514. res = AST_MODULE_RELOAD_SUCCESS;
  1515. } else if (res == AST_MODULE_RELOAD_NOT_FOUND) {
  1516. res = AST_MODULE_RELOAD_ERROR;
  1517. }
  1518. if (name) {
  1519. break;
  1520. }
  1521. }
  1522. AST_DLLIST_UNLOCK(&module_list);
  1523. if (ast_opt_lock_confdir) {
  1524. ast_unlock_path(ast_config_AST_CONFIG_DIR);
  1525. }
  1526. module_reload_done:
  1527. ast_mutex_unlock(&reloadlock);
  1528. ast_sd_notify("READY=1");
  1529. module_reload_exit:
  1530. publish_reload_message(name, res);
  1531. return res;
  1532. }
  1533. static unsigned int inspect_module(const struct ast_module *mod)
  1534. {
  1535. if (!mod->info->description) {
  1536. module_load_error("Module '%s' does not provide a description.\n", mod->resource);
  1537. return 1;
  1538. }
  1539. if (!mod->info->key) {
  1540. module_load_error("Module '%s' does not provide a license key.\n", mod->resource);
  1541. return 1;
  1542. }
  1543. if (verify_key((unsigned char *) mod->info->key)) {
  1544. module_load_error("Module '%s' did not provide a valid license key.\n", mod->resource);
  1545. return 1;
  1546. }
  1547. if (!ast_strlen_zero(mod->info->buildopt_sum) &&
  1548. strcmp(buildopt_sum, mod->info->buildopt_sum)) {
  1549. module_load_error("Module '%s' was not compiled with the same compile-time options as this version of Asterisk.\n", mod->resource);
  1550. module_load_error("Module '%s' will not be initialized as it may cause instability.\n", mod->resource);
  1551. return 1;
  1552. }
  1553. return 0;
  1554. }
  1555. static enum ast_module_load_result start_resource(struct ast_module *mod)
  1556. {
  1557. char tmp[256];
  1558. enum ast_module_load_result res;
  1559. if (mod->flags.running) {
  1560. return AST_MODULE_LOAD_SUCCESS;
  1561. }
  1562. if (!mod->info->load) {
  1563. mod->flags.declined = 1;
  1564. return mod->flags.required ? AST_MODULE_LOAD_FAILURE : AST_MODULE_LOAD_DECLINE;
  1565. }
  1566. if (module_deps_reference(mod, NULL)) {
  1567. struct module_vector missing;
  1568. int i;
  1569. AST_VECTOR_INIT(&missing, 0);
  1570. if (module_deps_missing_recursive(mod, &missing)) {
  1571. module_load_error("%s has one or more unknown dependencies.\n", mod->info->name);
  1572. }
  1573. for (i = 0; i < AST_VECTOR_SIZE(&missing); i++) {
  1574. module_load_error("%s loaded before dependency %s!\n", mod->info->name,
  1575. AST_VECTOR_GET(&missing, i)->info->name);
  1576. }
  1577. AST_VECTOR_FREE(&missing);
  1578. return AST_MODULE_LOAD_DECLINE;
  1579. }
  1580. if (!ast_fully_booted) {
  1581. ast_verb(4, "Loading %s.\n", mod->resource);
  1582. }
  1583. res = mod->info->load();
  1584. switch (res) {
  1585. case AST_MODULE_LOAD_SUCCESS:
  1586. if (!ast_fully_booted) {
  1587. ast_verb(5, "%s => (%s)\n", mod->resource, term_color(tmp, mod->info->description, COLOR_BROWN, COLOR_BLACK, sizeof(tmp)));
  1588. } else {
  1589. ast_verb(4, "Loaded %s => (%s)\n", mod->resource, mod->info->description);
  1590. }
  1591. mod->flags.running = 1;
  1592. if (mod->flags.builtin) {
  1593. /* Built-in modules cannot be unloaded. */
  1594. ast_module_shutdown_ref(mod);
  1595. }
  1596. ast_update_use_count();
  1597. break;
  1598. case AST_MODULE_LOAD_DECLINE:
  1599. mod->flags.declined = 1;
  1600. if (mod->flags.required) {
  1601. res = AST_MODULE_LOAD_FAILURE;
  1602. }
  1603. break;
  1604. case AST_MODULE_LOAD_FAILURE:
  1605. mod->flags.declined = 1;
  1606. break;
  1607. case AST_MODULE_LOAD_SKIP: /* modules should never return this value */
  1608. case AST_MODULE_LOAD_PRIORITY:
  1609. break;
  1610. }
  1611. /* Make sure the newly started module is at the end of the list */
  1612. AST_DLLIST_LOCK(&module_list);
  1613. AST_DLLIST_REMOVE(&module_list, mod, entry);
  1614. AST_DLLIST_INSERT_TAIL(&module_list, mod, entry);
  1615. AST_DLLIST_UNLOCK(&module_list);
  1616. return res;
  1617. }
  1618. /*! loads a resource based upon resource_name. If global_symbols_only is set
  1619. * only modules with global symbols will be loaded.
  1620. *
  1621. * If the module_vector is provided (not NULL) the module is found and added to the
  1622. * vector without running the module's load() function. By doing this, modules
  1623. * can be initialized later in order by priority and dependencies.
  1624. *
  1625. * If the module_vector is not provided, the module's load function will be executed
  1626. * immediately */
  1627. static enum ast_module_load_result load_resource(const char *resource_name, unsigned int suppress_logging,
  1628. struct module_vector *module_priorities, int required, int preload)
  1629. {
  1630. struct ast_module *mod;
  1631. enum ast_module_load_result res = AST_MODULE_LOAD_SUCCESS;
  1632. if ((mod = find_resource(resource_name, 0))) {
  1633. if (mod->flags.running) {
  1634. ast_log(LOG_WARNING, "Module '%s' already loaded and running.\n", resource_name);
  1635. return AST_MODULE_LOAD_DECLINE;
  1636. }
  1637. } else {
  1638. mod = load_dynamic_module(resource_name, suppress_logging);
  1639. if (!mod) {
  1640. return required ? AST_MODULE_LOAD_FAILURE : AST_MODULE_LOAD_DECLINE;
  1641. }
  1642. if (module_post_register(mod)) {
  1643. goto prestart_error;
  1644. }
  1645. }
  1646. mod->flags.required |= required;
  1647. mod->flags.preload |= preload;
  1648. if (inspect_module(mod)) {
  1649. goto prestart_error;
  1650. }
  1651. mod->flags.declined = 0;
  1652. if (module_priorities) {
  1653. if (AST_VECTOR_ADD_SORTED(module_priorities, mod, module_vector_cmp)) {
  1654. goto prestart_error;
  1655. }
  1656. res = AST_MODULE_LOAD_PRIORITY;
  1657. } else {
  1658. res = start_resource(mod);
  1659. }
  1660. if (ast_fully_booted && !ast_shutdown_final()) {
  1661. publish_load_message(resource_name, res);
  1662. }
  1663. return res;
  1664. prestart_error:
  1665. module_load_error("Module '%s' could not be loaded.\n", resource_name);
  1666. unload_dynamic_module(mod);
  1667. res = required ? AST_MODULE_LOAD_FAILURE : AST_MODULE_LOAD_DECLINE;
  1668. if (ast_fully_booted && !ast_shutdown_final()) {
  1669. publish_load_message(resource_name, res);
  1670. }
  1671. return res;
  1672. }
  1673. enum ast_module_load_result ast_load_resource(const char *resource_name)
  1674. {
  1675. struct ast_module *mod;
  1676. enum ast_module_load_result res;
  1677. /* If we're trying to load a module that previously declined to load,
  1678. * transparently unload it first so we dlclose, then dlopen it afresh.
  1679. * Otherwise, we won't actually load a (potentially) updated module. */
  1680. mod = find_resource(resource_name, 0);
  1681. if (mod && mod->flags.declined) {
  1682. ast_debug(1, "Module %s previously declined to load, unloading it first before loading again\n", resource_name);
  1683. ast_unload_resource(resource_name, 0);
  1684. }
  1685. AST_DLLIST_LOCK(&module_list);
  1686. res = load_resource(resource_name, 0, NULL, 0, 0);
  1687. if (!res) {
  1688. ast_test_suite_event_notify("MODULE_LOAD", "Message: %s", resource_name);
  1689. }
  1690. AST_DLLIST_UNLOCK(&module_list);
  1691. return res;
  1692. }
  1693. struct load_order_entry {
  1694. char *resource;
  1695. int required;
  1696. int preload;
  1697. int builtin;
  1698. AST_LIST_ENTRY(load_order_entry) entry;
  1699. };
  1700. AST_LIST_HEAD_NOLOCK(load_order, load_order_entry);
  1701. static struct load_order_entry *add_to_load_order(const char *resource, struct load_order *load_order, int required, int preload, int builtin)
  1702. {
  1703. struct load_order_entry *order;
  1704. size_t resource_baselen = resource_name_baselen(resource);
  1705. AST_LIST_TRAVERSE(load_order, order, entry) {
  1706. if (!resource_name_match(resource, resource_baselen, order->resource)) {
  1707. /* Make sure we have the proper setting for the required field
  1708. (we might have both load= and required= lines in modules.conf) */
  1709. order->required |= required;
  1710. order->preload |= preload;
  1711. return order;
  1712. }
  1713. }
  1714. order = ast_calloc(1, sizeof(*order));
  1715. if (!order) {
  1716. return NULL;
  1717. }
  1718. order->resource = ast_strdup(resource);
  1719. if (!order->resource) {
  1720. ast_free(order);
  1721. return NULL;
  1722. }
  1723. order->required = required;
  1724. order->preload = preload;
  1725. order->builtin = builtin;
  1726. AST_LIST_INSERT_TAIL(load_order, order, entry);
  1727. return order;
  1728. }
  1729. AST_LIST_HEAD_NOLOCK(load_retries, load_order_entry);
  1730. static enum ast_module_load_result start_resource_attempt(struct ast_module *mod, int *count)
  1731. {
  1732. enum ast_module_load_result lres;
  1733. /* Try to grab required references. */
  1734. if (module_deps_reference(mod, NULL)) {
  1735. /* We're likely to retry so not an error. */
  1736. ast_debug(1, "Module %s is missing dependencies\n", mod->resource);
  1737. return AST_MODULE_LOAD_SKIP;
  1738. }
  1739. lres = start_resource(mod);
  1740. ast_debug(3, "START: %-46s[%d] %d\n",
  1741. mod->resource,
  1742. ast_test_flag(mod->info, AST_MODFLAG_LOAD_ORDER) ? mod->info->load_pri : AST_MODPRI_DEFAULT,
  1743. lres);
  1744. if (lres == AST_MODULE_LOAD_SUCCESS) {
  1745. (*count)++;
  1746. } else if (lres == AST_MODULE_LOAD_FAILURE) {
  1747. module_load_error("*** Failed to load %smodule %s\n",
  1748. mod->flags.required ? "required " : "",
  1749. mod->resource);
  1750. }
  1751. return lres;
  1752. }
  1753. static int resource_list_recursive_decline(struct module_vector *resources, struct ast_module *mod,
  1754. struct ast_str **printmissing)
  1755. {
  1756. struct module_vector missingdeps;
  1757. struct ast_vector_const_string localdeps;
  1758. int i = 0;
  1759. int res = -1;
  1760. mod->flags.declined = 1;
  1761. if (mod->flags.required) {
  1762. module_load_error("Required module %s declined to load.\n", ast_module_name(mod));
  1763. return -2;
  1764. }
  1765. module_load_error("%s declined to load.\n", ast_module_name(mod));
  1766. if (!*printmissing) {
  1767. *printmissing = ast_str_create(64);
  1768. if (!*printmissing) {
  1769. return -1;
  1770. }
  1771. } else {
  1772. ast_str_reset(*printmissing);
  1773. }
  1774. AST_VECTOR_INIT(&missingdeps, 0);
  1775. AST_VECTOR_INIT(&localdeps, 0);
  1776. /* Decline everything that depends on 'mod' from resources so we can
  1777. * print a concise list. */
  1778. while (res != -2 && i < AST_VECTOR_SIZE(resources)) {
  1779. struct ast_module *dep = AST_VECTOR_GET(resources, i);
  1780. i++;
  1781. AST_VECTOR_RESET(&missingdeps, AST_VECTOR_ELEM_CLEANUP_NOOP);
  1782. if (dep->flags.declined || module_deps_missing_recursive(dep, &missingdeps)) {
  1783. continue;
  1784. }
  1785. if (AST_VECTOR_GET_CMP(&missingdeps, mod, AST_VECTOR_ELEM_DEFAULT_CMP)) {
  1786. dep->flags.declined = 1;
  1787. if (dep->flags.required) {
  1788. module_load_error("Cannot load required module %s that depends on %s\n",
  1789. ast_module_name(dep), ast_module_name(mod));
  1790. res = -2;
  1791. } else {
  1792. AST_VECTOR_APPEND(&localdeps, ast_module_name(dep));
  1793. }
  1794. }
  1795. }
  1796. AST_VECTOR_FREE(&missingdeps);
  1797. if (res != -2 && AST_VECTOR_SIZE(&localdeps)) {
  1798. AST_VECTOR_CALLBACK_VOID(&localdeps, STR_APPEND_TEXT, printmissing);
  1799. module_load_error("Declined modules which depend on %s: %s\n",
  1800. ast_module_name(mod), ast_str_buffer(*printmissing));
  1801. }
  1802. AST_VECTOR_FREE(&localdeps);
  1803. return res;
  1804. }
  1805. static int start_resource_list(struct module_vector *resources, int *mod_count)
  1806. {
  1807. struct module_vector missingdeps;
  1808. int res = 0;
  1809. struct ast_str *printmissing = NULL;
  1810. AST_VECTOR_INIT(&missingdeps, 0);
  1811. while (res != -2 && AST_VECTOR_SIZE(resources)) {
  1812. struct ast_module *mod = AST_VECTOR_REMOVE(resources, 0, 1);
  1813. enum ast_module_load_result lres;
  1814. if (mod->flags.declined) {
  1815. ast_debug(1, "%s is already declined, skipping\n", ast_module_name(mod));
  1816. continue;
  1817. }
  1818. retry_load:
  1819. lres = start_resource_attempt(mod, mod_count);
  1820. if (lres == AST_MODULE_LOAD_SUCCESS) {
  1821. /* No missing dependencies, successful. */
  1822. continue;
  1823. }
  1824. if (lres == AST_MODULE_LOAD_FAILURE) {
  1825. res = -2;
  1826. break;
  1827. }
  1828. if (lres == AST_MODULE_LOAD_DECLINE) {
  1829. res = resource_list_recursive_decline(resources, mod, &printmissing);
  1830. continue;
  1831. }
  1832. if (module_deps_missing_recursive(mod, &missingdeps)) {
  1833. AST_VECTOR_RESET(&missingdeps, AST_VECTOR_ELEM_CLEANUP_NOOP);
  1834. module_load_error("Failed to resolve dependencies for %s\n", ast_module_name(mod));
  1835. res = resource_list_recursive_decline(resources, mod, &printmissing);
  1836. continue;
  1837. }
  1838. if (!AST_VECTOR_SIZE(&missingdeps)) {
  1839. module_load_error("%s load function returned an invalid result. "
  1840. "This is a bug in the module.\n", ast_module_name(mod));
  1841. /* Dependencies were met but the module failed to start and the result
  1842. * code was not AST_MODULE_LOAD_FAILURE or AST_MODULE_LOAD_DECLINE. */
  1843. res = resource_list_recursive_decline(resources, mod, &printmissing);
  1844. continue;
  1845. }
  1846. ast_debug(1, "%s has %d dependencies\n",
  1847. ast_module_name(mod), (int)AST_VECTOR_SIZE(&missingdeps));
  1848. while (AST_VECTOR_SIZE(&missingdeps)) {
  1849. int didwork = 0;
  1850. int i = 0;
  1851. while (i < AST_VECTOR_SIZE(&missingdeps)) {
  1852. struct ast_module *dep = AST_VECTOR_GET(&missingdeps, i);
  1853. if (dep->flags.declined) {
  1854. ast_debug(1, "%s tried to start %s but it's already declined\n",
  1855. ast_module_name(mod), ast_module_name(dep));
  1856. i++;
  1857. continue;
  1858. }
  1859. ast_debug(1, "%s trying to start %s\n", ast_module_name(mod), ast_module_name(dep));
  1860. lres = start_resource_attempt(dep, mod_count);
  1861. if (lres == AST_MODULE_LOAD_SUCCESS) {
  1862. ast_debug(1, "%s started %s\n", ast_module_name(mod), ast_module_name(dep));
  1863. AST_VECTOR_REMOVE(&missingdeps, i, 1);
  1864. AST_VECTOR_REMOVE_CMP_ORDERED(resources, dep,
  1865. AST_VECTOR_ELEM_DEFAULT_CMP, AST_VECTOR_ELEM_CLEANUP_NOOP);
  1866. didwork++;
  1867. continue;
  1868. }
  1869. if (lres == AST_MODULE_LOAD_FAILURE) {
  1870. module_load_error("Failed to load %s.\n", ast_module_name(dep));
  1871. res = -2;
  1872. goto exitpoint;
  1873. }
  1874. ast_debug(1, "%s failed to start %s\n", ast_module_name(mod), ast_module_name(dep));
  1875. i++;
  1876. }
  1877. if (!didwork) {
  1878. break;
  1879. }
  1880. }
  1881. if (AST_VECTOR_SIZE(&missingdeps)) {
  1882. if (!printmissing) {
  1883. printmissing = ast_str_create(64);
  1884. } else {
  1885. ast_str_reset(printmissing);
  1886. }
  1887. if (printmissing) {
  1888. struct ast_vector_const_string localdeps;
  1889. AST_VECTOR_INIT(&localdeps, 0);
  1890. module_deps_reference(mod, &localdeps);
  1891. AST_VECTOR_CALLBACK_VOID(&localdeps, STR_APPEND_TEXT, &printmissing);
  1892. AST_VECTOR_FREE(&localdeps);
  1893. }
  1894. module_load_error("Failed to load %s due to dependencies: %s.\n",
  1895. ast_module_name(mod),
  1896. printmissing ? ast_str_buffer(printmissing) : "allocation failure creating list");
  1897. res = resource_list_recursive_decline(resources, mod, &printmissing);
  1898. AST_VECTOR_RESET(&missingdeps, AST_VECTOR_ELEM_CLEANUP_NOOP);
  1899. continue;
  1900. }
  1901. /* If we're here it means that we started with missingdeps and they're all loaded
  1902. * now. It's impossible to reach this point a second time for the same module. */
  1903. goto retry_load;
  1904. }
  1905. exitpoint:
  1906. ast_free(printmissing);
  1907. AST_VECTOR_FREE(&missingdeps);
  1908. return res;
  1909. }
  1910. /*! loads modules in order by load_pri, updates mod_count
  1911. \return -1 on failure to load module, -2 on failure to load required module, otherwise 0
  1912. */
  1913. static int load_resource_list(struct load_order *load_order, int *mod_count)
  1914. {
  1915. struct module_vector module_priorities;
  1916. struct load_order_entry *order;
  1917. int attempt = 0;
  1918. int count = 0;
  1919. int res = 0;
  1920. int didwork;
  1921. int lasttry = 0;
  1922. if (AST_VECTOR_INIT(&module_priorities, 500)) {
  1923. ast_log(LOG_ERROR, "Failed to initialize module loader.\n");
  1924. return -1;
  1925. }
  1926. while (res != -2) {
  1927. didwork = 0;
  1928. AST_LIST_TRAVERSE_SAFE_BEGIN(load_order, order, entry) {
  1929. enum ast_module_load_result lres;
  1930. /* Suppress log messages unless this is the last pass */
  1931. lres = load_resource(order->resource, !lasttry, &module_priorities, order->required, order->preload);
  1932. ast_debug(3, "PASS %d: %-46s %d\n", attempt, order->resource, lres);
  1933. switch (lres) {
  1934. case AST_MODULE_LOAD_SUCCESS:
  1935. case AST_MODULE_LOAD_SKIP:
  1936. /* We're supplying module_priorities so SUCCESS isn't possible but we
  1937. * still have to test for it. SKIP is only used when we try to start a
  1938. * module that is missing dependencies. */
  1939. break;
  1940. case AST_MODULE_LOAD_DECLINE:
  1941. res = -1;
  1942. break;
  1943. case AST_MODULE_LOAD_FAILURE:
  1944. /* LOAD_FAILURE only happens for required modules */
  1945. if (lasttry) {
  1946. /* This run is just to print errors. */
  1947. module_load_error("*** Failed to load module %s - Required\n", order->resource);
  1948. fprintf(stderr, "*** Failed to load module %s - Required\n", order->resource);
  1949. res = -2;
  1950. }
  1951. break;
  1952. case AST_MODULE_LOAD_PRIORITY:
  1953. /* load_resource worked and the module was added to module_priorities */
  1954. AST_LIST_REMOVE_CURRENT(entry);
  1955. ast_free(order->resource);
  1956. ast_free(order);
  1957. didwork = 1;
  1958. break;
  1959. }
  1960. }
  1961. AST_LIST_TRAVERSE_SAFE_END;
  1962. if (!didwork) {
  1963. if (lasttry) {
  1964. break;
  1965. }
  1966. /* We know the next try is going to fail, it's only being performed
  1967. * so we can print errors. */
  1968. lasttry = 1;
  1969. }
  1970. attempt++;
  1971. }
  1972. if (res != -2) {
  1973. res = start_resource_list(&module_priorities, &count);
  1974. }
  1975. if (mod_count) {
  1976. *mod_count += count;
  1977. }
  1978. AST_VECTOR_FREE(&module_priorities);
  1979. return res;
  1980. }
  1981. static int loader_builtin_init(struct load_order *load_order)
  1982. {
  1983. struct ast_module *mod;
  1984. /*
  1985. * All built-in modules have registered the first time, now it's time to complete
  1986. * the registration and add them to the priority list.
  1987. */
  1988. loader_ready = 1;
  1989. while ((resource_being_loaded = AST_DLLIST_REMOVE_HEAD(&builtin_module_list, entry))) {
  1990. /* ast_module_register doesn't finish when first run by built-in modules. */
  1991. ast_module_register(resource_being_loaded->info);
  1992. }
  1993. /* Add all built-in modules to the load order. */
  1994. AST_DLLIST_TRAVERSE(&module_list, mod, entry) {
  1995. if (!mod->flags.builtin) {
  1996. continue;
  1997. }
  1998. /* Parse dependendencies from mod->info. */
  1999. if (module_post_register(mod)) {
  2000. return -1;
  2001. }
  2002. /* Built-in modules are not preloaded, most have an early load priority. */
  2003. if (!add_to_load_order(mod->resource, load_order, 0, 0, 1)) {
  2004. return -1;
  2005. }
  2006. }
  2007. return 0;
  2008. }
  2009. static int loader_config_init(struct load_order *load_order)
  2010. {
  2011. int res = -1;
  2012. struct load_order_entry *order;
  2013. struct ast_config *cfg;
  2014. struct ast_variable *v;
  2015. struct ast_flags config_flags = { 0 };
  2016. cfg = ast_config_load2(AST_MODULE_CONFIG, "" /* core, can't reload */, config_flags);
  2017. if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
  2018. ast_log(LOG_WARNING, "'%s' invalid or missing.\n", AST_MODULE_CONFIG);
  2019. return -1;
  2020. }
  2021. /* first, find all the modules we have been explicitly requested to load */
  2022. for (v = ast_variable_browse(cfg, "modules"); v; v = v->next) {
  2023. int required;
  2024. int preload = 0;
  2025. if (!strncasecmp(v->name, "preload", strlen("preload"))) {
  2026. preload = 1;
  2027. if (!strcasecmp(v->name, "preload")) {
  2028. required = 0;
  2029. } else if (!strcasecmp(v->name, "preload-require")) {
  2030. required = 1;
  2031. } else {
  2032. ast_log(LOG_ERROR, "Unknown configuration option '%s'", v->name);
  2033. goto done;
  2034. }
  2035. } else if (!strcasecmp(v->name, "load")) {
  2036. required = 0;
  2037. } else if (!strcasecmp(v->name, "require")) {
  2038. required = 1;
  2039. } else if (!strcasecmp(v->name, "noload") || !strcasecmp(v->name, "autoload")) {
  2040. continue;
  2041. } else {
  2042. ast_log(LOG_ERROR, "Unknown configuration option '%s'", v->name);
  2043. goto done;
  2044. }
  2045. if (required) {
  2046. ast_debug(2, "Adding module to required list: %s (%s)\n", v->value, v->name);
  2047. }
  2048. if (!add_to_load_order(v->value, load_order, required, preload, 0)) {
  2049. goto done;
  2050. }
  2051. }
  2052. /* check if 'autoload' is on */
  2053. if (ast_true(ast_variable_retrieve(cfg, "modules", "autoload"))) {
  2054. /* if we are allowed to load dynamic modules, scan the directory for
  2055. for all available modules and add them as well */
  2056. DIR *dir = opendir(ast_config_AST_MODULE_DIR);
  2057. struct dirent *dirent;
  2058. if (dir) {
  2059. while ((dirent = readdir(dir))) {
  2060. int ld = strlen(dirent->d_name);
  2061. /* Must end in .so to load it. */
  2062. if (ld < 4)
  2063. continue;
  2064. if (strcasecmp(dirent->d_name + ld - 3, ".so"))
  2065. continue;
  2066. /* if there is already a module by this name in the module_list,
  2067. skip this file */
  2068. if (find_resource(dirent->d_name, 0))
  2069. continue;
  2070. if (!add_to_load_order(dirent->d_name, load_order, 0, 0, 0)) {
  2071. closedir(dir);
  2072. goto done;
  2073. }
  2074. }
  2075. closedir(dir);
  2076. } else {
  2077. ast_log(LOG_ERROR, "Unable to open modules directory '%s'.\n", ast_config_AST_MODULE_DIR);
  2078. goto done;
  2079. }
  2080. }
  2081. /* now scan the config for any modules we are prohibited from loading and
  2082. remove them from the load order */
  2083. for (v = ast_variable_browse(cfg, "modules"); v; v = v->next) {
  2084. size_t baselen;
  2085. if (strcasecmp(v->name, "noload")) {
  2086. continue;
  2087. }
  2088. baselen = resource_name_baselen(v->value);
  2089. AST_LIST_TRAVERSE_SAFE_BEGIN(load_order, order, entry) {
  2090. if (!resource_name_match(v->value, baselen, order->resource)) {
  2091. if (order->builtin) {
  2092. ast_log(LOG_ERROR, "%s is a built-in module, you cannot specify 'noload'.\n", v->value);
  2093. goto done;
  2094. }
  2095. if (order->required) {
  2096. ast_log(LOG_ERROR, "%s is configured with '%s' and 'noload', this is impossible.\n",
  2097. v->value, order->preload ? "preload-require" : "require");
  2098. goto done;
  2099. }
  2100. AST_LIST_REMOVE_CURRENT(entry);
  2101. ast_free(order->resource);
  2102. ast_free(order);
  2103. }
  2104. }
  2105. AST_LIST_TRAVERSE_SAFE_END;
  2106. }
  2107. res = 0;
  2108. done:
  2109. ast_config_destroy(cfg);
  2110. return res;
  2111. }
  2112. int load_modules(void)
  2113. {
  2114. struct load_order_entry *order;
  2115. unsigned int load_count;
  2116. struct load_order load_order;
  2117. int res = 0;
  2118. int modulecount = 0;
  2119. int i;
  2120. struct ast_module *cur;
  2121. #ifdef AST_XML_DOCS
  2122. struct ast_str *warning_msg;
  2123. char deprecated_in[33];
  2124. char removed_in[33];
  2125. char replacement[129];
  2126. #endif
  2127. struct timeval start_time = ast_tvnow();
  2128. struct timeval end_time;
  2129. int64_t usElapsed;
  2130. ast_verb(1, "Asterisk Dynamic Loader Starting:\n");
  2131. #if defined(HAVE_PERMANENT_DLOPEN)
  2132. info_list = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0, NULL,
  2133. info_list_obj_cmp_fn); /* must not be cleaned at shutdown */
  2134. if (!info_list) {
  2135. fprintf(stderr, "Module info list allocation failure.\n");
  2136. return 1;
  2137. }
  2138. #endif
  2139. AST_LIST_HEAD_INIT_NOLOCK(&load_order);
  2140. AST_DLLIST_LOCK(&module_list);
  2141. AST_VECTOR_INIT(&startup_errors, 0);
  2142. startup_error_builder = ast_str_create(64);
  2143. res = loader_builtin_init(&load_order);
  2144. if (res) {
  2145. goto done;
  2146. }
  2147. res = loader_config_init(&load_order);
  2148. if (res) {
  2149. goto done;
  2150. }
  2151. load_count = 0;
  2152. AST_LIST_TRAVERSE(&load_order, order, entry)
  2153. load_count++;
  2154. if (load_count)
  2155. ast_log(LOG_NOTICE, "%u modules will be loaded.\n", load_count);
  2156. res = load_resource_list(&load_order, &modulecount);
  2157. if (res == -1) {
  2158. ast_log(LOG_WARNING, "Some non-required modules failed to load.\n");
  2159. res = 0;
  2160. }
  2161. done:
  2162. while ((order = AST_LIST_REMOVE_HEAD(&load_order, entry))) {
  2163. ast_free(order->resource);
  2164. ast_free(order);
  2165. }
  2166. #ifdef AST_XML_DOCS
  2167. warning_msg = ast_str_create(512);
  2168. #endif
  2169. AST_DLLIST_TRAVERSE(&module_list, cur, entry) {
  2170. #ifdef AST_XML_DOCS
  2171. char *mod_name = NULL;
  2172. struct ast_xml_xpath_results *results;
  2173. #endif
  2174. if (!cur->flags.running || cur->flags.declined) {
  2175. continue;
  2176. }
  2177. #ifdef AST_XML_DOCS
  2178. mod_name = get_name_from_resource(cur->resource);
  2179. if (!warning_msg || !mod_name) {
  2180. /* If we can't allocate memory, we have bigger issues */
  2181. ast_free(mod_name);
  2182. continue;
  2183. }
  2184. /* Clear out the previous values */
  2185. deprecated_in[0] = removed_in[0] = replacement[0] = 0;
  2186. results = ast_xmldoc_query("/docs/module[@name='%s']", mod_name);
  2187. if (results) {
  2188. struct ast_xml_node *deprecated_node, *removed_node, *replacement_node;
  2189. struct ast_xml_node *metadata_nodes = ast_xml_node_get_children(ast_xml_xpath_get_first_result(results));
  2190. deprecated_node = ast_xml_find_element(metadata_nodes, "deprecated_in", NULL, NULL);
  2191. if (deprecated_node) {
  2192. const char *result_tmp = ast_xml_get_text(deprecated_node);
  2193. if (!ast_strlen_zero(result_tmp)) {
  2194. ast_copy_string(deprecated_in, result_tmp, sizeof(deprecated_in));
  2195. }
  2196. }
  2197. removed_node = ast_xml_find_element(metadata_nodes, "removed_in", NULL, NULL);
  2198. if (removed_node) {
  2199. const char *result_tmp = ast_xml_get_text(removed_node);
  2200. if (!ast_strlen_zero(result_tmp)) {
  2201. ast_copy_string(removed_in, result_tmp, sizeof(removed_in));
  2202. }
  2203. }
  2204. replacement_node = ast_xml_find_element(metadata_nodes, "replacement", NULL, NULL);
  2205. if (replacement_node) {
  2206. const char *result_tmp = ast_xml_get_text(replacement_node);
  2207. if (!ast_strlen_zero(result_tmp)) {
  2208. ast_copy_string(replacement, result_tmp, sizeof(replacement));
  2209. }
  2210. }
  2211. ast_xml_xpath_results_free(results);
  2212. }
  2213. ast_str_reset(warning_msg);
  2214. if (cur->info->support_level == AST_MODULE_SUPPORT_DEPRECATED || !ast_strlen_zero(deprecated_in)
  2215. || !ast_strlen_zero(removed_in) || !ast_strlen_zero(replacement)) {
  2216. int already_butted = 0;
  2217. ast_str_append(&warning_msg, -1, "Module '%s' has been loaded", mod_name);
  2218. if (!ast_strlen_zero(deprecated_in)) {
  2219. ast_str_append(&warning_msg, -1, " but %s deprecated in Asterisk version %s",
  2220. cur->info->support_level == AST_MODULE_SUPPORT_DEPRECATED ? "was" : "will be", deprecated_in);
  2221. already_butted = 1;
  2222. }
  2223. if (!ast_strlen_zero(removed_in)) {
  2224. ast_str_append(&warning_msg, -1, " %s will be removed in Asterisk version %s", already_butted ? "and" : "but", removed_in);
  2225. } else {
  2226. ast_str_append(&warning_msg, -1, " %s may be removed in a future release", already_butted ? "and" : "but");
  2227. }
  2228. ast_str_append(&warning_msg, -1, ".");
  2229. if (!ast_strlen_zero(replacement)) {
  2230. ast_str_append(&warning_msg, -1, " Its replacement is '%s'.", replacement);
  2231. }
  2232. }
  2233. if (ast_str_strlen(warning_msg)) {
  2234. ast_log(LOG_WARNING, "%s\n", ast_str_buffer(warning_msg));
  2235. }
  2236. ast_free(mod_name);
  2237. #else
  2238. if (cur->info->support_level == AST_MODULE_SUPPORT_DEPRECATED) {
  2239. ast_log(LOG_WARNING, "The deprecated module '%s' has been loaded and is running, it may be removed in a future version\n", cur->resource);
  2240. }
  2241. #endif
  2242. }
  2243. #ifdef AST_XML_DOCS
  2244. ast_free(warning_msg);
  2245. #endif
  2246. AST_DLLIST_UNLOCK(&module_list);
  2247. for (i = 0; i < AST_VECTOR_SIZE(&startup_errors); i++) {
  2248. char *str = AST_VECTOR_GET(&startup_errors, i);
  2249. ast_log(LOG_ERROR, "%s", str);
  2250. ast_free(str);
  2251. }
  2252. AST_VECTOR_FREE(&startup_errors);
  2253. ast_free(startup_error_builder);
  2254. startup_error_builder = NULL;
  2255. end_time = ast_tvnow();
  2256. usElapsed = ast_tvdiff_us(end_time, start_time);
  2257. #ifdef AST_XML_DOCS
  2258. ast_debug(1, "Loader time with AST_XML_DOCS: %" PRId64 ".%06" PRId64 "\n", usElapsed / 1000000, usElapsed % 1000000);
  2259. #else
  2260. ast_debug(1, "Loader time without AST_XML_DOCS: %" PRId64 ".%06" PRId64 "\n", usElapsed / 1000000, usElapsed % 1000000);
  2261. #endif
  2262. return res;
  2263. }
  2264. void ast_update_use_count(void)
  2265. {
  2266. /* Notify any module monitors that the use count for a
  2267. resource has changed */
  2268. struct loadupdate *m;
  2269. AST_LIST_LOCK(&updaters);
  2270. AST_LIST_TRAVERSE(&updaters, m, entry)
  2271. m->updater();
  2272. AST_LIST_UNLOCK(&updaters);
  2273. }
  2274. /*!
  2275. * \internal
  2276. * \brief Build an alpha sorted list of modules.
  2277. *
  2278. * \param alpha_module_list Pointer to uninitialized module_vector.
  2279. *
  2280. * This function always initializes alpha_module_list.
  2281. *
  2282. * \pre module_list must be locked.
  2283. */
  2284. static int alpha_module_list_create(struct module_vector *alpha_module_list)
  2285. {
  2286. struct ast_module *cur;
  2287. if (AST_VECTOR_INIT(alpha_module_list, 32)) {
  2288. return -1;
  2289. }
  2290. AST_DLLIST_TRAVERSE(&module_list, cur, entry) {
  2291. if (AST_VECTOR_ADD_SORTED(alpha_module_list, cur, module_vector_strcasecmp)) {
  2292. return -1;
  2293. }
  2294. }
  2295. return 0;
  2296. }
  2297. int ast_update_module_list(int (*modentry)(const char *module, const char *description,
  2298. int usecnt, const char *status, const char *like,
  2299. enum ast_module_support_level support_level),
  2300. const char *like)
  2301. {
  2302. int total_mod_loaded = 0;
  2303. struct module_vector alpha_module_list;
  2304. AST_DLLIST_LOCK(&module_list);
  2305. if (!alpha_module_list_create(&alpha_module_list)) {
  2306. int idx;
  2307. for (idx = 0; idx < AST_VECTOR_SIZE(&alpha_module_list); idx++) {
  2308. struct ast_module *cur = AST_VECTOR_GET(&alpha_module_list, idx);
  2309. total_mod_loaded += modentry(cur->resource, cur->info->description, cur->usecount,
  2310. cur->flags.running ? "Running" : "Not Running", like, cur->info->support_level);
  2311. }
  2312. }
  2313. AST_DLLIST_UNLOCK(&module_list);
  2314. AST_VECTOR_FREE(&alpha_module_list);
  2315. return total_mod_loaded;
  2316. }
  2317. int ast_update_module_list_data(int (*modentry)(const char *module, const char *description,
  2318. int usecnt, const char *status, const char *like,
  2319. enum ast_module_support_level support_level,
  2320. void *data),
  2321. const char *like, void *data)
  2322. {
  2323. int total_mod_loaded = 0;
  2324. struct module_vector alpha_module_list;
  2325. AST_DLLIST_LOCK(&module_list);
  2326. if (!alpha_module_list_create(&alpha_module_list)) {
  2327. int idx;
  2328. for (idx = 0; idx < AST_VECTOR_SIZE(&alpha_module_list); idx++) {
  2329. struct ast_module *cur = AST_VECTOR_GET(&alpha_module_list, idx);
  2330. total_mod_loaded += modentry(cur->resource, cur->info->description, cur->usecount,
  2331. cur->flags.running? "Running" : "Not Running", like, cur->info->support_level, data);
  2332. }
  2333. }
  2334. AST_DLLIST_UNLOCK(&module_list);
  2335. AST_VECTOR_FREE(&alpha_module_list);
  2336. return total_mod_loaded;
  2337. }
  2338. int ast_update_module_list_condition(int (*modentry)(const char *module, const char *description,
  2339. int usecnt, const char *status,
  2340. const char *like,
  2341. enum ast_module_support_level support_level,
  2342. void *data, const char *condition),
  2343. const char *like, void *data, const char *condition)
  2344. {
  2345. int conditions_met = 0;
  2346. struct module_vector alpha_module_list;
  2347. AST_DLLIST_LOCK(&module_list);
  2348. if (!alpha_module_list_create(&alpha_module_list)) {
  2349. int idx;
  2350. for (idx = 0; idx < AST_VECTOR_SIZE(&alpha_module_list); idx++) {
  2351. struct ast_module *cur = AST_VECTOR_GET(&alpha_module_list, idx);
  2352. conditions_met += modentry(cur->resource, cur->info->description, cur->usecount,
  2353. cur->flags.running? "Running" : "Not Running", like, cur->info->support_level, data,
  2354. condition);
  2355. }
  2356. }
  2357. AST_DLLIST_UNLOCK(&module_list);
  2358. AST_VECTOR_FREE(&alpha_module_list);
  2359. return conditions_met;
  2360. }
  2361. /*! \brief Check if module exists */
  2362. int ast_module_check(const char *name)
  2363. {
  2364. struct ast_module *cur;
  2365. if (ast_strlen_zero(name))
  2366. return 0; /* FALSE */
  2367. cur = find_resource(name, 1);
  2368. return (cur != NULL);
  2369. }
  2370. int ast_loader_register(int (*v)(void))
  2371. {
  2372. struct loadupdate *tmp;
  2373. if (!(tmp = ast_malloc(sizeof(*tmp))))
  2374. return -1;
  2375. tmp->updater = v;
  2376. AST_LIST_LOCK(&updaters);
  2377. AST_LIST_INSERT_HEAD(&updaters, tmp, entry);
  2378. AST_LIST_UNLOCK(&updaters);
  2379. return 0;
  2380. }
  2381. int ast_loader_unregister(int (*v)(void))
  2382. {
  2383. struct loadupdate *cur;
  2384. AST_LIST_LOCK(&updaters);
  2385. AST_LIST_TRAVERSE_SAFE_BEGIN(&updaters, cur, entry) {
  2386. if (cur->updater == v) {
  2387. AST_LIST_REMOVE_CURRENT(entry);
  2388. break;
  2389. }
  2390. }
  2391. AST_LIST_TRAVERSE_SAFE_END;
  2392. AST_LIST_UNLOCK(&updaters);
  2393. return cur ? 0 : -1;
  2394. }
  2395. struct ast_module *__ast_module_ref(struct ast_module *mod, const char *file, int line, const char *func)
  2396. {
  2397. if (!mod) {
  2398. return NULL;
  2399. }
  2400. if (mod->ref_debug) {
  2401. __ao2_ref(mod->ref_debug, +1, "", file, line, func);
  2402. }
  2403. ast_atomic_fetchadd_int(&mod->usecount, +1);
  2404. ast_update_use_count();
  2405. return mod;
  2406. }
  2407. struct ast_module *__ast_module_running_ref(struct ast_module *mod,
  2408. const char *file, int line, const char *func)
  2409. {
  2410. if (!mod || !mod->flags.running) {
  2411. return NULL;
  2412. }
  2413. return __ast_module_ref(mod, file, line, func);
  2414. }
  2415. void __ast_module_shutdown_ref(struct ast_module *mod, const char *file, int line, const char *func)
  2416. {
  2417. if (!mod || mod->flags.keepuntilshutdown) {
  2418. return;
  2419. }
  2420. __ast_module_ref(mod, file, line, func);
  2421. mod->flags.keepuntilshutdown = 1;
  2422. }
  2423. void __ast_module_unref(struct ast_module *mod, const char *file, int line, const char *func)
  2424. {
  2425. if (!mod) {
  2426. return;
  2427. }
  2428. if (mod->ref_debug) {
  2429. __ao2_ref(mod->ref_debug, -1, "", file, line, func);
  2430. }
  2431. ast_atomic_fetchadd_int(&mod->usecount, -1);
  2432. ast_update_use_count();
  2433. }
  2434. const char *support_level_map [] = {
  2435. [AST_MODULE_SUPPORT_UNKNOWN] = "unknown",
  2436. [AST_MODULE_SUPPORT_CORE] = "core",
  2437. [AST_MODULE_SUPPORT_EXTENDED] = "extended",
  2438. [AST_MODULE_SUPPORT_DEPRECATED] = "deprecated",
  2439. };
  2440. const char *ast_module_support_level_to_string(enum ast_module_support_level support_level)
  2441. {
  2442. return support_level_map[support_level];
  2443. }