logger.c 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief Asterisk Logger
  21. *
  22. * Logging routines
  23. *
  24. * \author Mark Spencer <markster@digium.com>
  25. */
  26. /*! \li \ref logger.c uses the configuration file \ref logger.conf
  27. * \addtogroup configuration_file Configuration Files
  28. */
  29. /*!
  30. * \page logger.conf logger.conf
  31. * \verbinclude logger.conf.sample
  32. */
  33. /*** MODULEINFO
  34. <support_level>core</support_level>
  35. ***/
  36. #include "asterisk.h"
  37. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  38. /* When we include logger.h again it will trample on some stuff in syslog.h, but
  39. * nothing we care about in here. */
  40. #include <syslog.h>
  41. #include <signal.h>
  42. #include <time.h>
  43. #include <sys/stat.h>
  44. #include <fcntl.h>
  45. #include "asterisk/_private.h"
  46. #include "asterisk/paths.h" /* use ast_config_AST_LOG_DIR */
  47. #include "asterisk/logger.h"
  48. #include "asterisk/lock.h"
  49. #include "asterisk/channel.h"
  50. #include "asterisk/config.h"
  51. #include "asterisk/term.h"
  52. #include "asterisk/cli.h"
  53. #include "asterisk/utils.h"
  54. #include "asterisk/manager.h"
  55. #include "asterisk/astobj2.h"
  56. #include "asterisk/threadstorage.h"
  57. #include "asterisk/strings.h"
  58. #include "asterisk/pbx.h"
  59. #include "asterisk/app.h"
  60. #include "asterisk/syslog.h"
  61. #include "asterisk/buildinfo.h"
  62. #include "asterisk/ast_version.h"
  63. #include "asterisk/backtrace.h"
  64. /*** DOCUMENTATION
  65. ***/
  66. static char dateformat[256] = "%b %e %T"; /* Original Asterisk Format */
  67. static char queue_log_name[256] = QUEUELOG;
  68. static char exec_after_rotate[256] = "";
  69. static int filesize_reload_needed;
  70. static unsigned int global_logmask = 0xFFFF;
  71. static int queuelog_init;
  72. static int logger_initialized;
  73. static volatile int next_unique_callid; /* Used to assign unique call_ids to calls */
  74. static int display_callids;
  75. static void unique_callid_cleanup(void *data);
  76. static int logger_queue_size;
  77. static int logger_queue_limit = 1000;
  78. static int logger_messages_discarded;
  79. static unsigned int high_water_alert;
  80. struct ast_callid {
  81. int call_identifier; /* Numerical value of the call displayed in the logs */
  82. };
  83. AST_THREADSTORAGE_CUSTOM(unique_callid, NULL, unique_callid_cleanup);
  84. static enum rotatestrategy {
  85. NONE = 0, /* Do not rotate log files at all, instead rely on external mechanisms */
  86. SEQUENTIAL = 1 << 0, /* Original method - create a new file, in order */
  87. ROTATE = 1 << 1, /* Rotate all files, such that the oldest file has the highest suffix */
  88. TIMESTAMP = 1 << 2, /* Append the epoch timestamp onto the end of the archived file */
  89. } rotatestrategy = SEQUENTIAL;
  90. static struct {
  91. unsigned int queue_log:1;
  92. unsigned int queue_log_to_file:1;
  93. unsigned int queue_adaptive_realtime:1;
  94. unsigned int queue_log_realtime_use_gmt:1;
  95. } logfiles = { 1 };
  96. static char hostname[MAXHOSTNAMELEN];
  97. AST_THREADSTORAGE_RAW(in_safe_log);
  98. enum logtypes {
  99. LOGTYPE_SYSLOG,
  100. LOGTYPE_FILE,
  101. LOGTYPE_CONSOLE,
  102. };
  103. struct logchannel {
  104. /*! What to log to this channel */
  105. unsigned int logmask;
  106. /*! If this channel is disabled or not */
  107. int disabled;
  108. /*! syslog facility */
  109. int facility;
  110. /*! Verbosity level. (-1 if use option_verbose for the level.) */
  111. int verbosity;
  112. /*! Type of log channel */
  113. enum logtypes type;
  114. /*! logfile logging file pointer */
  115. FILE *fileptr;
  116. /*! Filename */
  117. char filename[PATH_MAX];
  118. /*! field for linking to list */
  119. AST_LIST_ENTRY(logchannel) list;
  120. /*! Line number from configuration file */
  121. int lineno;
  122. /*! Whether this log channel was created dynamically */
  123. int dynamic;
  124. /*! Components (levels) from last config load */
  125. char components[0];
  126. };
  127. static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
  128. enum logmsgtypes {
  129. LOGMSG_NORMAL = 0,
  130. LOGMSG_VERBOSE,
  131. };
  132. struct logmsg {
  133. enum logmsgtypes type;
  134. int level;
  135. int line;
  136. int lwp;
  137. struct ast_callid *callid;
  138. AST_DECLARE_STRING_FIELDS(
  139. AST_STRING_FIELD(date);
  140. AST_STRING_FIELD(file);
  141. AST_STRING_FIELD(function);
  142. AST_STRING_FIELD(message);
  143. AST_STRING_FIELD(level_name);
  144. );
  145. AST_LIST_ENTRY(logmsg) list;
  146. };
  147. static void logmsg_free(struct logmsg *msg)
  148. {
  149. if (msg->callid) {
  150. ast_callid_unref(msg->callid);
  151. }
  152. ast_string_field_free_memory(msg);
  153. ast_free(msg);
  154. }
  155. static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
  156. static pthread_t logthread = AST_PTHREADT_NULL;
  157. static ast_cond_t logcond;
  158. static int close_logger_thread = 0;
  159. static FILE *qlog;
  160. /*! \brief Logging channels used in the Asterisk logging system
  161. *
  162. * The first 16 levels are reserved for system usage, and the remaining
  163. * levels are reserved for usage by dynamic levels registered via
  164. * ast_logger_register_level.
  165. */
  166. /* Modifications to this array are protected by the rwlock in the
  167. * logchannels list.
  168. */
  169. static char *levels[NUMLOGLEVELS] = {
  170. "DEBUG",
  171. "---EVENT---", /* no longer used */
  172. "NOTICE",
  173. "WARNING",
  174. "ERROR",
  175. "VERBOSE",
  176. "DTMF",
  177. };
  178. /*! \brief Colors used in the console for logging */
  179. static const int colors[NUMLOGLEVELS] = {
  180. COLOR_BRGREEN,
  181. COLOR_BRBLUE, /* no longer used */
  182. COLOR_YELLOW,
  183. COLOR_BRRED,
  184. COLOR_RED,
  185. COLOR_GREEN,
  186. COLOR_BRGREEN,
  187. 0,
  188. 0,
  189. 0,
  190. 0,
  191. 0,
  192. 0,
  193. 0,
  194. 0,
  195. 0,
  196. COLOR_BRBLUE,
  197. COLOR_BRBLUE,
  198. COLOR_BRBLUE,
  199. COLOR_BRBLUE,
  200. COLOR_BRBLUE,
  201. COLOR_BRBLUE,
  202. COLOR_BRBLUE,
  203. COLOR_BRBLUE,
  204. COLOR_BRBLUE,
  205. COLOR_BRBLUE,
  206. COLOR_BRBLUE,
  207. COLOR_BRBLUE,
  208. COLOR_BRBLUE,
  209. COLOR_BRBLUE,
  210. COLOR_BRBLUE,
  211. COLOR_BRBLUE,
  212. };
  213. AST_THREADSTORAGE(verbose_buf);
  214. AST_THREADSTORAGE(verbose_build_buf);
  215. #define VERBOSE_BUF_INIT_SIZE 256
  216. AST_THREADSTORAGE(log_buf);
  217. #define LOG_BUF_INIT_SIZE 256
  218. static void make_components(struct logchannel *chan)
  219. {
  220. char *w;
  221. unsigned int logmask = 0;
  222. char *stringp = ast_strdupa(chan->components);
  223. unsigned int x;
  224. unsigned int verb_level;
  225. /* Default to using option_verbose as the verbosity level of the logging channel. */
  226. verb_level = -1;
  227. while ((w = strsep(&stringp, ","))) {
  228. w = ast_strip(w);
  229. if (ast_strlen_zero(w)) {
  230. continue;
  231. }
  232. if (!strcmp(w, "*")) {
  233. logmask = 0xFFFFFFFF;
  234. } else if (!strncasecmp(w, "verbose(", 8)) {
  235. if (levels[__LOG_VERBOSE] && sscanf(w + 8, "%30u)", &verb_level) == 1) {
  236. logmask |= (1 << __LOG_VERBOSE);
  237. }
  238. } else {
  239. for (x = 0; x < ARRAY_LEN(levels); ++x) {
  240. if (levels[x] && !strcasecmp(w, levels[x])) {
  241. logmask |= (1 << x);
  242. break;
  243. }
  244. }
  245. }
  246. }
  247. if (chan->type == LOGTYPE_CONSOLE) {
  248. /*
  249. * Force to use the root console verbose level so if the
  250. * user specified any verbose level then it does not interfere
  251. * with calculating the ast_verb_sys_level value.
  252. */
  253. chan->verbosity = -1;
  254. } else {
  255. chan->verbosity = verb_level;
  256. }
  257. chan->logmask = logmask;
  258. }
  259. /*!
  260. * \brief create the filename that will be used for a logger channel.
  261. *
  262. * \param channel The name of the logger channel
  263. * \param[out] filename The filename for the logger channel
  264. * \param size The size of the filename buffer
  265. */
  266. static void make_filename(const char *channel, char *filename, size_t size)
  267. {
  268. const char *log_dir_prefix = "";
  269. const char *log_dir_separator = "";
  270. *filename = '\0';
  271. if (!strcasecmp(channel, "console")) {
  272. return;
  273. }
  274. if (!strncasecmp(channel, "syslog", 6)) {
  275. ast_copy_string(filename, channel, size);
  276. return;
  277. }
  278. /* It's a filename */
  279. if (channel[0] != '/') {
  280. log_dir_prefix = ast_config_AST_LOG_DIR;
  281. log_dir_separator = "/";
  282. }
  283. if (!ast_strlen_zero(hostname)) {
  284. snprintf(filename, size, "%s%s%s.%s",
  285. log_dir_prefix, log_dir_separator, channel, hostname);
  286. } else {
  287. snprintf(filename, size, "%s%s%s",
  288. log_dir_prefix, log_dir_separator, channel);
  289. }
  290. }
  291. /*!
  292. * \brief Find a particular logger channel by name
  293. *
  294. * \pre logchannels list is locked
  295. *
  296. * \param channel The name of the logger channel to find
  297. * \retval non-NULL The corresponding logger channel
  298. * \retval NULL Unable to find a logger channel with that particular name
  299. */
  300. static struct logchannel *find_logchannel(const char *channel)
  301. {
  302. char filename[PATH_MAX];
  303. struct logchannel *chan;
  304. make_filename(channel, filename, sizeof(filename));
  305. AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
  306. if (!strcmp(chan->filename, filename)) {
  307. return chan;
  308. }
  309. }
  310. return NULL;
  311. }
  312. static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno, int dynamic)
  313. {
  314. struct logchannel *chan;
  315. char *facility;
  316. struct ast_tm tm;
  317. struct timeval now = ast_tvnow();
  318. char datestring[256];
  319. if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan) + strlen(components) + 1)))
  320. return NULL;
  321. strcpy(chan->components, components);
  322. chan->lineno = lineno;
  323. chan->dynamic = dynamic;
  324. make_filename(channel, chan->filename, sizeof(chan->filename));
  325. if (!strcasecmp(channel, "console")) {
  326. chan->type = LOGTYPE_CONSOLE;
  327. } else if (!strncasecmp(channel, "syslog", 6)) {
  328. /*
  329. * syntax is:
  330. * syslog.facility => level,level,level
  331. */
  332. facility = strchr(channel, '.');
  333. if (!facility++ || !facility) {
  334. facility = "local0";
  335. }
  336. chan->facility = ast_syslog_facility(facility);
  337. if (chan->facility < 0) {
  338. fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
  339. ast_free(chan);
  340. return NULL;
  341. }
  342. chan->type = LOGTYPE_SYSLOG;
  343. openlog("asterisk", LOG_PID, chan->facility);
  344. } else {
  345. if (!(chan->fileptr = fopen(chan->filename, "a"))) {
  346. /* Can't do real logging here since we're called with a lock
  347. * so log to any attached consoles */
  348. ast_console_puts_mutable("ERROR: Unable to open log file '", __LOG_ERROR);
  349. ast_console_puts_mutable(chan->filename, __LOG_ERROR);
  350. ast_console_puts_mutable("': ", __LOG_ERROR);
  351. ast_console_puts_mutable(strerror(errno), __LOG_ERROR);
  352. ast_console_puts_mutable("'\n", __LOG_ERROR);
  353. ast_free(chan);
  354. return NULL;
  355. } else {
  356. /* Create our date/time */
  357. ast_localtime(&now, &tm, NULL);
  358. ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
  359. fprintf(chan->fileptr, "[%s] Asterisk %s built by %s @ %s on a %s running %s on %s\n",
  360. datestring, ast_get_version(), ast_build_user, ast_build_hostname,
  361. ast_build_machine, ast_build_os, ast_build_date);
  362. fflush(chan->fileptr);
  363. }
  364. chan->type = LOGTYPE_FILE;
  365. }
  366. make_components(chan);
  367. return chan;
  368. }
  369. /*!
  370. * \brief Read config, setup channels.
  371. * \param locked The logchannels list is locked and this is a reload
  372. * \param altconf Alternate configuration file to read.
  373. *
  374. * \retval 0 Success
  375. * \retval -1 No config found or Failed
  376. */
  377. static int init_logger_chain(int locked, const char *altconf)
  378. {
  379. struct logchannel *chan;
  380. struct ast_config *cfg;
  381. struct ast_variable *var;
  382. const char *s;
  383. struct ast_flags config_flags = { 0 };
  384. if (!(cfg = ast_config_load2(S_OR(altconf, "logger.conf"), "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
  385. cfg = NULL;
  386. }
  387. if (!locked) {
  388. AST_RWLIST_WRLOCK(&logchannels);
  389. }
  390. /* Set defaults */
  391. hostname[0] = '\0';
  392. display_callids = 1;
  393. memset(&logfiles, 0, sizeof(logfiles));
  394. logfiles.queue_log = 1;
  395. ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
  396. ast_copy_string(queue_log_name, QUEUELOG, sizeof(queue_log_name));
  397. exec_after_rotate[0] = '\0';
  398. rotatestrategy = SEQUENTIAL;
  399. /* delete our list of log channels */
  400. while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list))) {
  401. ast_free(chan);
  402. }
  403. global_logmask = 0;
  404. if (!locked) {
  405. AST_RWLIST_UNLOCK(&logchannels);
  406. }
  407. errno = 0;
  408. /* close syslog */
  409. closelog();
  410. /* If no config file, we're fine, set default options. */
  411. if (!cfg) {
  412. chan = make_logchannel("console", "error,warning,notice,verbose", 0, 0);
  413. if (!chan) {
  414. fprintf(stderr, "ERROR: Failed to initialize default logging\n");
  415. return -1;
  416. }
  417. if (!locked) {
  418. AST_RWLIST_WRLOCK(&logchannels);
  419. }
  420. AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
  421. global_logmask |= chan->logmask;
  422. if (!locked) {
  423. AST_RWLIST_UNLOCK(&logchannels);
  424. }
  425. return -1;
  426. }
  427. if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
  428. if (ast_true(s)) {
  429. if (gethostname(hostname, sizeof(hostname) - 1)) {
  430. ast_copy_string(hostname, "unknown", sizeof(hostname));
  431. fprintf(stderr, "What box has no hostname???\n");
  432. }
  433. }
  434. }
  435. if ((s = ast_variable_retrieve(cfg, "general", "display_callids"))) {
  436. display_callids = ast_true(s);
  437. }
  438. if ((s = ast_variable_retrieve(cfg, "general", "dateformat"))) {
  439. ast_copy_string(dateformat, s, sizeof(dateformat));
  440. }
  441. if ((s = ast_variable_retrieve(cfg, "general", "queue_log"))) {
  442. logfiles.queue_log = ast_true(s);
  443. }
  444. if ((s = ast_variable_retrieve(cfg, "general", "queue_log_to_file"))) {
  445. logfiles.queue_log_to_file = ast_true(s);
  446. }
  447. if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name"))) {
  448. ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
  449. }
  450. if ((s = ast_variable_retrieve(cfg, "general", "queue_log_realtime_use_gmt"))) {
  451. logfiles.queue_log_realtime_use_gmt = ast_true(s);
  452. }
  453. if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate"))) {
  454. ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
  455. }
  456. if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
  457. if (strcasecmp(s, "timestamp") == 0) {
  458. rotatestrategy = TIMESTAMP;
  459. } else if (strcasecmp(s, "rotate") == 0) {
  460. rotatestrategy = ROTATE;
  461. } else if (strcasecmp(s, "sequential") == 0) {
  462. rotatestrategy = SEQUENTIAL;
  463. } else if (strcasecmp(s, "none") == 0) {
  464. rotatestrategy = NONE;
  465. } else {
  466. fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
  467. }
  468. } else {
  469. if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
  470. rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
  471. fprintf(stderr, "rotatetimestamp option has been deprecated. Please use rotatestrategy instead.\n");
  472. }
  473. }
  474. if ((s = ast_variable_retrieve(cfg, "general", "logger_queue_limit"))) {
  475. if (sscanf(s, "%30d", &logger_queue_limit) != 1) {
  476. fprintf(stderr, "logger_queue_limit has an invalid value. Leaving at default of %d.\n",
  477. logger_queue_limit);
  478. }
  479. if (logger_queue_limit < 10) {
  480. fprintf(stderr, "logger_queue_limit must be >= 10. Setting to 10.\n");
  481. logger_queue_limit = 10;
  482. }
  483. }
  484. if (!locked) {
  485. AST_RWLIST_WRLOCK(&logchannels);
  486. }
  487. var = ast_variable_browse(cfg, "logfiles");
  488. for (; var; var = var->next) {
  489. chan = make_logchannel(var->name, var->value, var->lineno, 0);
  490. if (!chan) {
  491. /* Print error message directly to the consoles since the lock is held
  492. * and we don't want to unlock with the list partially built */
  493. ast_console_puts_mutable("ERROR: Unable to create log channel '", __LOG_ERROR);
  494. ast_console_puts_mutable(var->name, __LOG_ERROR);
  495. ast_console_puts_mutable("'\n", __LOG_ERROR);
  496. continue;
  497. }
  498. AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
  499. global_logmask |= chan->logmask;
  500. }
  501. if (qlog) {
  502. fclose(qlog);
  503. qlog = NULL;
  504. }
  505. if (!locked) {
  506. AST_RWLIST_UNLOCK(&logchannels);
  507. }
  508. ast_config_destroy(cfg);
  509. return 0;
  510. }
  511. void ast_child_verbose(int level, const char *fmt, ...)
  512. {
  513. char *msg = NULL, *emsg = NULL, *sptr, *eptr;
  514. va_list ap, aq;
  515. int size;
  516. va_start(ap, fmt);
  517. va_copy(aq, ap);
  518. if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
  519. va_end(ap);
  520. va_end(aq);
  521. return;
  522. }
  523. va_end(ap);
  524. if (!(msg = ast_malloc(size + 1))) {
  525. va_end(aq);
  526. return;
  527. }
  528. vsnprintf(msg, size + 1, fmt, aq);
  529. va_end(aq);
  530. if (!(emsg = ast_malloc(size * 2 + 1))) {
  531. ast_free(msg);
  532. return;
  533. }
  534. for (sptr = msg, eptr = emsg; ; sptr++) {
  535. if (*sptr == '"') {
  536. *eptr++ = '\\';
  537. }
  538. *eptr++ = *sptr;
  539. if (*sptr == '\0') {
  540. break;
  541. }
  542. }
  543. ast_free(msg);
  544. fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
  545. fflush(stdout);
  546. ast_free(emsg);
  547. }
  548. void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
  549. {
  550. va_list ap;
  551. struct timeval tv;
  552. struct ast_tm tm;
  553. char qlog_msg[8192];
  554. int qlog_len;
  555. char time_str[30];
  556. if (!logger_initialized) {
  557. /* You are too early. We are not open yet! */
  558. return;
  559. }
  560. if (!queuelog_init) {
  561. /* We must initialize now since someone is trying to log something. */
  562. logger_queue_start();
  563. }
  564. if (ast_check_realtime("queue_log")) {
  565. tv = ast_tvnow();
  566. ast_localtime(&tv, &tm, logfiles.queue_log_realtime_use_gmt ? "GMT" : NULL);
  567. ast_strftime(time_str, sizeof(time_str), "%F %T.%6q", &tm);
  568. va_start(ap, fmt);
  569. vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
  570. va_end(ap);
  571. if (logfiles.queue_adaptive_realtime) {
  572. AST_DECLARE_APP_ARGS(args,
  573. AST_APP_ARG(data)[5];
  574. );
  575. AST_NONSTANDARD_APP_ARGS(args, qlog_msg, '|');
  576. /* Ensure fields are large enough to receive data */
  577. ast_realtime_require_field("queue_log",
  578. "data1", RQ_CHAR, strlen(S_OR(args.data[0], "")),
  579. "data2", RQ_CHAR, strlen(S_OR(args.data[1], "")),
  580. "data3", RQ_CHAR, strlen(S_OR(args.data[2], "")),
  581. "data4", RQ_CHAR, strlen(S_OR(args.data[3], "")),
  582. "data5", RQ_CHAR, strlen(S_OR(args.data[4], "")),
  583. SENTINEL);
  584. /* Store the log */
  585. ast_store_realtime("queue_log", "time", time_str,
  586. "callid", callid,
  587. "queuename", queuename,
  588. "agent", agent,
  589. "event", event,
  590. "data1", S_OR(args.data[0], ""),
  591. "data2", S_OR(args.data[1], ""),
  592. "data3", S_OR(args.data[2], ""),
  593. "data4", S_OR(args.data[3], ""),
  594. "data5", S_OR(args.data[4], ""),
  595. SENTINEL);
  596. } else {
  597. ast_store_realtime("queue_log", "time", time_str,
  598. "callid", callid,
  599. "queuename", queuename,
  600. "agent", agent,
  601. "event", event,
  602. "data", qlog_msg,
  603. SENTINEL);
  604. }
  605. if (!logfiles.queue_log_to_file) {
  606. return;
  607. }
  608. }
  609. if (qlog) {
  610. va_start(ap, fmt);
  611. qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
  612. vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
  613. va_end(ap);
  614. AST_RWLIST_RDLOCK(&logchannels);
  615. if (qlog) {
  616. fprintf(qlog, "%s\n", qlog_msg);
  617. fflush(qlog);
  618. }
  619. AST_RWLIST_UNLOCK(&logchannels);
  620. }
  621. }
  622. static int rotate_file(const char *filename)
  623. {
  624. char old[PATH_MAX];
  625. char new[PATH_MAX];
  626. int x, y, which, found, res = 0, fd;
  627. char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
  628. switch (rotatestrategy) {
  629. case NONE:
  630. /* No rotation */
  631. break;
  632. case SEQUENTIAL:
  633. for (x = 0; ; x++) {
  634. snprintf(new, sizeof(new), "%s.%d", filename, x);
  635. fd = open(new, O_RDONLY);
  636. if (fd > -1)
  637. close(fd);
  638. else
  639. break;
  640. }
  641. if (rename(filename, new)) {
  642. fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
  643. res = -1;
  644. } else {
  645. filename = new;
  646. }
  647. break;
  648. case TIMESTAMP:
  649. snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
  650. if (rename(filename, new)) {
  651. fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
  652. res = -1;
  653. } else {
  654. filename = new;
  655. }
  656. break;
  657. case ROTATE:
  658. /* Find the next empty slot, including a possible suffix */
  659. for (x = 0; ; x++) {
  660. found = 0;
  661. for (which = 0; which < ARRAY_LEN(suffixes); which++) {
  662. snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
  663. fd = open(new, O_RDONLY);
  664. if (fd > -1) {
  665. close(fd);
  666. found = 1;
  667. break;
  668. }
  669. }
  670. if (!found) {
  671. break;
  672. }
  673. }
  674. /* Found an empty slot */
  675. for (y = x; y > 0; y--) {
  676. for (which = 0; which < ARRAY_LEN(suffixes); which++) {
  677. snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
  678. fd = open(old, O_RDONLY);
  679. if (fd > -1) {
  680. /* Found the right suffix */
  681. close(fd);
  682. snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
  683. if (rename(old, new)) {
  684. fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
  685. res = -1;
  686. }
  687. break;
  688. }
  689. }
  690. }
  691. /* Finally, rename the current file */
  692. snprintf(new, sizeof(new), "%s.0", filename);
  693. if (rename(filename, new)) {
  694. fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
  695. res = -1;
  696. } else {
  697. filename = new;
  698. }
  699. }
  700. if (!ast_strlen_zero(exec_after_rotate)) {
  701. struct ast_channel *c = ast_dummy_channel_alloc();
  702. char buf[512];
  703. pbx_builtin_setvar_helper(c, "filename", filename);
  704. pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
  705. if (c) {
  706. c = ast_channel_unref(c);
  707. }
  708. if (ast_safe_system(buf) == -1) {
  709. ast_log(LOG_WARNING, "error executing '%s'\n", buf);
  710. }
  711. }
  712. return res;
  713. }
  714. /*!
  715. * \internal
  716. * \brief Start the realtime queue logging if configured.
  717. *
  718. * \retval TRUE if not to open queue log file.
  719. */
  720. static int logger_queue_rt_start(void)
  721. {
  722. if (ast_check_realtime("queue_log")) {
  723. if (!ast_realtime_require_field("queue_log",
  724. "time", RQ_DATETIME, 26,
  725. "data1", RQ_CHAR, 20,
  726. "data2", RQ_CHAR, 20,
  727. "data3", RQ_CHAR, 20,
  728. "data4", RQ_CHAR, 20,
  729. "data5", RQ_CHAR, 20,
  730. SENTINEL)) {
  731. logfiles.queue_adaptive_realtime = 1;
  732. } else {
  733. logfiles.queue_adaptive_realtime = 0;
  734. }
  735. if (!logfiles.queue_log_to_file) {
  736. /* Don't open the log file. */
  737. return 1;
  738. }
  739. }
  740. return 0;
  741. }
  742. /*!
  743. * \internal
  744. * \brief Rotate the queue log file and restart.
  745. *
  746. * \param queue_rotate Log queue rotation mode.
  747. *
  748. * \note Assumes logchannels is write locked on entry.
  749. *
  750. * \retval 0 on success.
  751. * \retval -1 on error.
  752. */
  753. static int logger_queue_restart(int queue_rotate)
  754. {
  755. int res = 0;
  756. char qfname[PATH_MAX];
  757. if (logger_queue_rt_start()) {
  758. return res;
  759. }
  760. snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
  761. if (qlog) {
  762. /* Just in case it was still open. */
  763. fclose(qlog);
  764. qlog = NULL;
  765. }
  766. if (queue_rotate) {
  767. rotate_file(qfname);
  768. }
  769. /* Open the log file. */
  770. qlog = fopen(qfname, "a");
  771. if (!qlog) {
  772. ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
  773. res = -1;
  774. }
  775. return res;
  776. }
  777. static int reload_logger(int rotate, const char *altconf)
  778. {
  779. int queue_rotate = rotate;
  780. struct logchannel *f;
  781. int res = 0;
  782. AST_RWLIST_WRLOCK(&logchannels);
  783. if (qlog) {
  784. if (rotate < 0) {
  785. /* Check filesize - this one typically doesn't need an auto-rotate */
  786. if (ftello(qlog) > 0x40000000) { /* Arbitrarily, 1 GB */
  787. fclose(qlog);
  788. qlog = NULL;
  789. } else {
  790. queue_rotate = 0;
  791. }
  792. } else {
  793. fclose(qlog);
  794. qlog = NULL;
  795. }
  796. } else {
  797. queue_rotate = 0;
  798. }
  799. ast_mkdir(ast_config_AST_LOG_DIR, 0777);
  800. AST_RWLIST_TRAVERSE(&logchannels, f, list) {
  801. if (f->disabled) {
  802. f->disabled = 0; /* Re-enable logging at reload */
  803. /*** DOCUMENTATION
  804. <managerEventInstance>
  805. <synopsis>Raised when a logging channel is re-enabled after a reload operation.</synopsis>
  806. <syntax>
  807. <parameter name="Channel">
  808. <para>The name of the logging channel.</para>
  809. </parameter>
  810. </syntax>
  811. </managerEventInstance>
  812. ***/
  813. manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
  814. }
  815. if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
  816. int rotate_this = 0;
  817. if (rotatestrategy != NONE && ftello(f->fileptr) > 0x40000000) { /* Arbitrarily, 1 GB */
  818. /* Be more proactive about rotating massive log files */
  819. rotate_this = 1;
  820. }
  821. fclose(f->fileptr); /* Close file */
  822. f->fileptr = NULL;
  823. if (rotate || rotate_this) {
  824. rotate_file(f->filename);
  825. }
  826. }
  827. }
  828. filesize_reload_needed = 0;
  829. init_logger_chain(1 /* locked */, altconf);
  830. ast_unload_realtime("queue_log");
  831. if (logfiles.queue_log) {
  832. res = logger_queue_restart(queue_rotate);
  833. AST_RWLIST_UNLOCK(&logchannels);
  834. ast_verb_update();
  835. ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
  836. ast_verb(1, "Asterisk Queue Logger restarted\n");
  837. } else {
  838. AST_RWLIST_UNLOCK(&logchannels);
  839. ast_verb_update();
  840. }
  841. return res;
  842. }
  843. /*! \brief Reload the logger module without rotating log files (also used from loader.c during
  844. a full Asterisk reload) */
  845. int logger_reload(void)
  846. {
  847. if (reload_logger(0, NULL)) {
  848. return RESULT_FAILURE;
  849. }
  850. return RESULT_SUCCESS;
  851. }
  852. static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  853. {
  854. switch (cmd) {
  855. case CLI_INIT:
  856. e->command = "logger reload";
  857. e->usage =
  858. "Usage: logger reload [<alt-conf>]\n"
  859. " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
  860. return NULL;
  861. case CLI_GENERATE:
  862. return NULL;
  863. }
  864. if (reload_logger(0, a->argc == 3 ? a->argv[2] : NULL)) {
  865. ast_cli(a->fd, "Failed to reload the logger\n");
  866. return CLI_FAILURE;
  867. }
  868. return CLI_SUCCESS;
  869. }
  870. static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  871. {
  872. switch (cmd) {
  873. case CLI_INIT:
  874. e->command = "logger rotate";
  875. e->usage =
  876. "Usage: logger rotate\n"
  877. " Rotates and Reopens the log files.\n";
  878. return NULL;
  879. case CLI_GENERATE:
  880. return NULL;
  881. }
  882. if (reload_logger(1, NULL)) {
  883. ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
  884. return CLI_FAILURE;
  885. }
  886. return CLI_SUCCESS;
  887. }
  888. int ast_logger_rotate()
  889. {
  890. return reload_logger(1, NULL);
  891. }
  892. int ast_logger_rotate_channel(const char *log_channel)
  893. {
  894. struct logchannel *f;
  895. int success = AST_LOGGER_FAILURE;
  896. char filename[PATH_MAX];
  897. make_filename(log_channel, filename, sizeof(filename));
  898. AST_RWLIST_WRLOCK(&logchannels);
  899. ast_mkdir(ast_config_AST_LOG_DIR, 0644);
  900. AST_RWLIST_TRAVERSE(&logchannels, f, list) {
  901. if (f->disabled) {
  902. f->disabled = 0; /* Re-enable logging at reload */
  903. manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n",
  904. f->filename);
  905. }
  906. if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
  907. fclose(f->fileptr); /* Close file */
  908. f->fileptr = NULL;
  909. if (strcmp(filename, f->filename) == 0) {
  910. rotate_file(f->filename);
  911. success = AST_LOGGER_SUCCESS;
  912. }
  913. }
  914. }
  915. init_logger_chain(1 /* locked */, NULL);
  916. AST_RWLIST_UNLOCK(&logchannels);
  917. return success;
  918. }
  919. static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  920. {
  921. int x;
  922. int state;
  923. int level = -1;
  924. switch (cmd) {
  925. case CLI_INIT:
  926. e->command = "logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}";
  927. e->usage =
  928. "Usage: logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}\n"
  929. " Set a specific log level to enabled/disabled for this console.\n";
  930. return NULL;
  931. case CLI_GENERATE:
  932. return NULL;
  933. }
  934. if (a->argc < 5)
  935. return CLI_SHOWUSAGE;
  936. AST_RWLIST_WRLOCK(&logchannels);
  937. for (x = 0; x < ARRAY_LEN(levels); x++) {
  938. if (levels[x] && !strcasecmp(a->argv[3], levels[x])) {
  939. level = x;
  940. break;
  941. }
  942. }
  943. AST_RWLIST_UNLOCK(&logchannels);
  944. state = ast_true(a->argv[4]) ? 1 : 0;
  945. if (level != -1) {
  946. ast_console_toggle_loglevel(a->fd, level, state);
  947. ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
  948. } else
  949. return CLI_SHOWUSAGE;
  950. return CLI_SUCCESS;
  951. }
  952. int ast_logger_get_channels(int (*logentry)(const char *channel, const char *type,
  953. const char *status, const char *configuration, void *data), void *data)
  954. {
  955. struct logchannel *chan;
  956. struct ast_str *configs = ast_str_create(64);
  957. int res = AST_LOGGER_SUCCESS;
  958. if (!configs) {
  959. return AST_LOGGER_ALLOC_ERROR;
  960. }
  961. AST_RWLIST_RDLOCK(&logchannels);
  962. AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
  963. unsigned int level;
  964. ast_str_reset(configs);
  965. for (level = 0; level < ARRAY_LEN(levels); level++) {
  966. if ((chan->logmask & (1 << level)) && levels[level]) {
  967. ast_str_append(&configs, 0, "%s ", levels[level]);
  968. }
  969. }
  970. res = logentry(chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" :
  971. (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"), chan->disabled ?
  972. "Disabled" : "Enabled", ast_str_buffer(configs), data);
  973. if (res) {
  974. AST_RWLIST_UNLOCK(&logchannels);
  975. ast_free(configs);
  976. configs = NULL;
  977. return AST_LOGGER_FAILURE;
  978. }
  979. }
  980. AST_RWLIST_UNLOCK(&logchannels);
  981. ast_free(configs);
  982. configs = NULL;
  983. return AST_LOGGER_SUCCESS;
  984. }
  985. /*! \brief CLI command to show logging system configuration */
  986. static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  987. {
  988. #define FORMATL "%-35.35s %-8.8s %-9.9s "
  989. struct logchannel *chan;
  990. switch (cmd) {
  991. case CLI_INIT:
  992. e->command = "logger show channels";
  993. e->usage =
  994. "Usage: logger show channels\n"
  995. " List configured logger channels.\n";
  996. return NULL;
  997. case CLI_GENERATE:
  998. return NULL;
  999. }
  1000. ast_cli(a->fd, "Logger queue limit: %d\n\n", logger_queue_limit);
  1001. ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
  1002. ast_cli(a->fd, "Configuration\n");
  1003. ast_cli(a->fd, FORMATL, "-------", "----", "------");
  1004. ast_cli(a->fd, "-------------\n");
  1005. AST_RWLIST_RDLOCK(&logchannels);
  1006. AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
  1007. unsigned int level;
  1008. ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
  1009. chan->disabled ? "Disabled" : "Enabled");
  1010. ast_cli(a->fd, " - ");
  1011. for (level = 0; level < ARRAY_LEN(levels); level++) {
  1012. if ((chan->logmask & (1 << level)) && levels[level]) {
  1013. ast_cli(a->fd, "%s ", levels[level]);
  1014. }
  1015. }
  1016. ast_cli(a->fd, "\n");
  1017. }
  1018. AST_RWLIST_UNLOCK(&logchannels);
  1019. ast_cli(a->fd, "\n");
  1020. return CLI_SUCCESS;
  1021. }
  1022. int ast_logger_create_channel(const char *log_channel, const char *components)
  1023. {
  1024. struct logchannel *chan;
  1025. if (ast_strlen_zero(components)) {
  1026. return AST_LOGGER_DECLINE;
  1027. }
  1028. AST_RWLIST_WRLOCK(&logchannels);
  1029. chan = find_logchannel(log_channel);
  1030. if (chan) {
  1031. AST_RWLIST_UNLOCK(&logchannels);
  1032. return AST_LOGGER_FAILURE;
  1033. }
  1034. chan = make_logchannel(log_channel, components, 0, 1);
  1035. if (!chan) {
  1036. AST_RWLIST_UNLOCK(&logchannels);
  1037. return AST_LOGGER_ALLOC_ERROR;
  1038. }
  1039. AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
  1040. global_logmask |= chan->logmask;
  1041. AST_RWLIST_UNLOCK(&logchannels);
  1042. return AST_LOGGER_SUCCESS;
  1043. }
  1044. static char *handle_logger_add_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1045. {
  1046. switch (cmd) {
  1047. case CLI_INIT:
  1048. e->command = "logger add channel";
  1049. e->usage =
  1050. "Usage: logger add channel <name> <levels>\n"
  1051. " Adds a temporary logger channel. This logger channel\n"
  1052. " will exist until removed or until Asterisk is restarted.\n"
  1053. " <levels> is a comma-separated list of desired logger\n"
  1054. " levels such as: verbose,warning,error\n";
  1055. return NULL;
  1056. case CLI_GENERATE:
  1057. return NULL;
  1058. }
  1059. if (a->argc < 5) {
  1060. return CLI_SHOWUSAGE;
  1061. }
  1062. switch (ast_logger_create_channel(a->argv[3], a->argv[4])) {
  1063. case AST_LOGGER_SUCCESS:
  1064. return CLI_SUCCESS;
  1065. case AST_LOGGER_FAILURE:
  1066. ast_cli(a->fd, "Logger channel '%s' already exists\n", a->argv[3]);
  1067. return CLI_SUCCESS;
  1068. case AST_LOGGER_DECLINE:
  1069. case AST_LOGGER_ALLOC_ERROR:
  1070. default:
  1071. ast_cli(a->fd, "ERROR: Unable to create log channel '%s'\n", a->argv[3]);
  1072. return CLI_FAILURE;
  1073. }
  1074. }
  1075. int ast_logger_remove_channel(const char *log_channel)
  1076. {
  1077. struct logchannel *chan;
  1078. AST_RWLIST_WRLOCK(&logchannels);
  1079. chan = find_logchannel(log_channel);
  1080. if (chan && chan->dynamic) {
  1081. AST_RWLIST_REMOVE(&logchannels, chan, list);
  1082. } else {
  1083. AST_RWLIST_UNLOCK(&logchannels);
  1084. return AST_LOGGER_FAILURE;
  1085. }
  1086. AST_RWLIST_UNLOCK(&logchannels);
  1087. if (chan->fileptr) {
  1088. fclose(chan->fileptr);
  1089. chan->fileptr = NULL;
  1090. }
  1091. ast_free(chan);
  1092. chan = NULL;
  1093. return AST_LOGGER_SUCCESS;
  1094. }
  1095. static char *handle_logger_remove_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1096. {
  1097. struct logchannel *chan;
  1098. int gen_count = 0;
  1099. char *gen_ret = NULL;
  1100. switch (cmd) {
  1101. case CLI_INIT:
  1102. e->command = "logger remove channel";
  1103. e->usage =
  1104. "Usage: logger remove channel <name>\n"
  1105. " Removes a temporary logger channel.\n";
  1106. return NULL;
  1107. case CLI_GENERATE:
  1108. if (a->argc > 4 || (a->argc == 4 && a->pos > 3)) {
  1109. return NULL;
  1110. }
  1111. AST_RWLIST_RDLOCK(&logchannels);
  1112. AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
  1113. if (chan->dynamic && (ast_strlen_zero(a->argv[3])
  1114. || !strncmp(a->argv[3], chan->filename, strlen(a->argv[3])))) {
  1115. if (gen_count == a->n) {
  1116. gen_ret = ast_strdup(chan->filename);
  1117. break;
  1118. }
  1119. gen_count++;
  1120. }
  1121. }
  1122. AST_RWLIST_UNLOCK(&logchannels);
  1123. return gen_ret;
  1124. }
  1125. if (a->argc < 4) {
  1126. return CLI_SHOWUSAGE;
  1127. }
  1128. switch (ast_logger_remove_channel(a->argv[3])) {
  1129. case AST_LOGGER_SUCCESS:
  1130. ast_cli(a->fd, "Removed dynamic logger channel '%s'\n", a->argv[3]);
  1131. return CLI_SUCCESS;
  1132. case AST_LOGGER_FAILURE:
  1133. ast_cli(a->fd, "Unable to find dynamic logger channel '%s'\n", a->argv[3]);
  1134. return CLI_SUCCESS;
  1135. default:
  1136. ast_cli(a->fd, "Internal failure attempting to delete dynamic logger channel '%s'\n", a->argv[3]);
  1137. return CLI_FAILURE;
  1138. }
  1139. }
  1140. struct verb {
  1141. void (*verboser)(const char *string);
  1142. AST_LIST_ENTRY(verb) list;
  1143. };
  1144. static AST_RWLIST_HEAD_STATIC(verbosers, verb);
  1145. static struct ast_cli_entry cli_logger[] = {
  1146. AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
  1147. AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
  1148. AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
  1149. AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console"),
  1150. AST_CLI_DEFINE(handle_logger_add_channel, "Adds a new logging channel"),
  1151. AST_CLI_DEFINE(handle_logger_remove_channel, "Removes a logging channel"),
  1152. };
  1153. static void _handle_SIGXFSZ(int sig)
  1154. {
  1155. /* Indicate need to reload */
  1156. filesize_reload_needed = 1;
  1157. }
  1158. static struct sigaction handle_SIGXFSZ = {
  1159. .sa_handler = _handle_SIGXFSZ,
  1160. .sa_flags = SA_RESTART,
  1161. };
  1162. static void ast_log_vsyslog(struct logmsg *msg, int facility)
  1163. {
  1164. char buf[BUFSIZ];
  1165. int syslog_level = ast_syslog_priority_from_loglevel(msg->level);
  1166. char call_identifier_str[13];
  1167. if (msg->callid) {
  1168. snprintf(call_identifier_str, sizeof(call_identifier_str), "[C-%08x]", (unsigned)msg->callid->call_identifier);
  1169. } else {
  1170. call_identifier_str[0] = '\0';
  1171. }
  1172. if (syslog_level < 0) {
  1173. /* we are locked here, so cannot ast_log() */
  1174. fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", msg->level);
  1175. return;
  1176. }
  1177. /* Don't use LOG_MAKEPRI because it's broken in glibc<2.17 */
  1178. syslog_level = facility | syslog_level; /* LOG_MAKEPRI(facility, syslog_level); */
  1179. snprintf(buf, sizeof(buf), "%s[%d]%s: %s:%d in %s: %s",
  1180. levels[msg->level], msg->lwp, call_identifier_str, msg->file, msg->line, msg->function, msg->message);
  1181. term_strip(buf, buf, strlen(buf) + 1);
  1182. syslog(syslog_level, "%s", buf);
  1183. }
  1184. static char *logger_strip_verbose_magic(const char *message, int level)
  1185. {
  1186. const char *begin, *end;
  1187. char *stripped_message, *dst;
  1188. char magic = -(level + 1);
  1189. if (!(stripped_message = ast_malloc(strlen(message) + 1))) {
  1190. return NULL;
  1191. }
  1192. begin = message;
  1193. dst = stripped_message;
  1194. do {
  1195. end = strchr(begin, magic);
  1196. if (end) {
  1197. size_t len = end - begin;
  1198. memcpy(dst, begin, len);
  1199. begin = end + 1;
  1200. dst += len;
  1201. } else {
  1202. strcpy(dst, begin); /* safe */
  1203. break;
  1204. }
  1205. } while (1);
  1206. return stripped_message;
  1207. }
  1208. /*! \brief Print a normal log message to the channels */
  1209. static void logger_print_normal(struct logmsg *logmsg)
  1210. {
  1211. struct logchannel *chan = NULL;
  1212. char buf[BUFSIZ];
  1213. struct verb *v = NULL;
  1214. char *tmpmsg;
  1215. int level = 0;
  1216. if (logmsg->level == __LOG_VERBOSE) {
  1217. /* Iterate through the list of verbosers and pass them the log message string */
  1218. AST_RWLIST_RDLOCK(&verbosers);
  1219. AST_RWLIST_TRAVERSE(&verbosers, v, list)
  1220. v->verboser(logmsg->message);
  1221. AST_RWLIST_UNLOCK(&verbosers);
  1222. level = VERBOSE_MAGIC2LEVEL(logmsg->message);
  1223. tmpmsg = logger_strip_verbose_magic(logmsg->message, level);
  1224. if (tmpmsg) {
  1225. ast_string_field_set(logmsg, message, tmpmsg);
  1226. ast_free(tmpmsg);
  1227. }
  1228. }
  1229. AST_RWLIST_RDLOCK(&logchannels);
  1230. if (!AST_RWLIST_EMPTY(&logchannels)) {
  1231. AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
  1232. char call_identifier_str[13];
  1233. if (logmsg->callid) {
  1234. snprintf(call_identifier_str, sizeof(call_identifier_str), "[C-%08x]", (unsigned)logmsg->callid->call_identifier);
  1235. } else {
  1236. call_identifier_str[0] = '\0';
  1237. }
  1238. /* If the channel is disabled, then move on to the next one */
  1239. if (chan->disabled) {
  1240. continue;
  1241. }
  1242. if (logmsg->level == __LOG_VERBOSE
  1243. && (((chan->verbosity < 0) ? option_verbose : chan->verbosity)) < level) {
  1244. continue;
  1245. }
  1246. /* Check syslog channels */
  1247. if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
  1248. ast_log_vsyslog(logmsg, chan->facility);
  1249. /* Console channels */
  1250. } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
  1251. char linestr[128];
  1252. int has_file = !ast_strlen_zero(logmsg->file);
  1253. int has_line = (logmsg->line > 0);
  1254. int has_func = !ast_strlen_zero(logmsg->function);
  1255. /* If the level is verbose, then skip it */
  1256. if (logmsg->level == __LOG_VERBOSE)
  1257. continue;
  1258. /* Turn the numerical line number into a string */
  1259. snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
  1260. /* Build string to print out */
  1261. snprintf(buf, sizeof(buf), "[%s] " COLORIZE_FMT "[%d]%s: " COLORIZE_FMT "%s" COLORIZE_FMT " " COLORIZE_FMT "%s %s",
  1262. logmsg->date,
  1263. COLORIZE(colors[logmsg->level], 0, logmsg->level_name),
  1264. logmsg->lwp,
  1265. call_identifier_str,
  1266. COLORIZE(COLOR_BRWHITE, 0, has_file ? logmsg->file : ""),
  1267. has_file ? ":" : "",
  1268. COLORIZE(COLOR_BRWHITE, 0, has_line ? linestr : ""),
  1269. COLORIZE(COLOR_BRWHITE, 0, has_func ? logmsg->function : ""),
  1270. has_func ? ":" : "",
  1271. logmsg->message);
  1272. /* Print out */
  1273. ast_console_puts_mutable(buf, logmsg->level);
  1274. /* File channels */
  1275. } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
  1276. int res = 0;
  1277. /* If no file pointer exists, skip it */
  1278. if (!chan->fileptr) {
  1279. continue;
  1280. }
  1281. /* Print out to the file */
  1282. res = fprintf(chan->fileptr, "[%s] %s[%d]%s %s: %s",
  1283. logmsg->date, logmsg->level_name, logmsg->lwp, call_identifier_str,
  1284. logmsg->file, term_strip(buf, logmsg->message, BUFSIZ));
  1285. if (res <= 0 && !ast_strlen_zero(logmsg->message)) {
  1286. fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
  1287. if (errno == ENOMEM || errno == ENOSPC)
  1288. fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
  1289. else
  1290. fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
  1291. /*** DOCUMENTATION
  1292. <managerEventInstance>
  1293. <synopsis>Raised when a logging channel is disabled.</synopsis>
  1294. <syntax>
  1295. <parameter name="Channel">
  1296. <para>The name of the logging channel.</para>
  1297. </parameter>
  1298. </syntax>
  1299. </managerEventInstance>
  1300. ***/
  1301. manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
  1302. chan->disabled = 1;
  1303. } else if (res > 0) {
  1304. fflush(chan->fileptr);
  1305. }
  1306. }
  1307. }
  1308. } else if (logmsg->level != __LOG_VERBOSE) {
  1309. fputs(logmsg->message, stdout);
  1310. }
  1311. AST_RWLIST_UNLOCK(&logchannels);
  1312. /* If we need to reload because of the file size, then do so */
  1313. if (filesize_reload_needed) {
  1314. reload_logger(-1, NULL);
  1315. ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
  1316. }
  1317. return;
  1318. }
  1319. static struct logmsg * __attribute__((format(printf, 6, 0))) format_log_message_ap(int level,
  1320. const char *file, int line, const char *function, struct ast_callid *callid,
  1321. const char *fmt, va_list ap)
  1322. {
  1323. struct logmsg *logmsg = NULL;
  1324. struct ast_str *buf = NULL;
  1325. struct ast_tm tm;
  1326. struct timeval now = ast_tvnow();
  1327. int res = 0;
  1328. char datestring[256];
  1329. if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE))) {
  1330. return NULL;
  1331. }
  1332. /* Build string */
  1333. res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
  1334. /* If the build failed, then abort and free this structure */
  1335. if (res == AST_DYNSTR_BUILD_FAILED) {
  1336. return NULL;
  1337. }
  1338. /* Create a new logging message */
  1339. if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128))) {
  1340. return NULL;
  1341. }
  1342. /* Copy string over */
  1343. ast_string_field_set(logmsg, message, ast_str_buffer(buf));
  1344. /* Set type */
  1345. if (level == __LOG_VERBOSE) {
  1346. logmsg->type = LOGMSG_VERBOSE;
  1347. } else {
  1348. logmsg->type = LOGMSG_NORMAL;
  1349. }
  1350. if (display_callids && callid) {
  1351. logmsg->callid = ast_callid_ref(callid);
  1352. /* callid will be unreffed at logmsg destruction */
  1353. }
  1354. /* Create our date/time */
  1355. ast_localtime(&now, &tm, NULL);
  1356. ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
  1357. ast_string_field_set(logmsg, date, datestring);
  1358. /* Copy over data */
  1359. logmsg->level = level;
  1360. logmsg->line = line;
  1361. ast_string_field_set(logmsg, level_name, levels[level]);
  1362. ast_string_field_set(logmsg, file, file);
  1363. ast_string_field_set(logmsg, function, function);
  1364. logmsg->lwp = ast_get_tid();
  1365. return logmsg;
  1366. }
  1367. static struct logmsg * __attribute__((format(printf, 6, 0))) format_log_message(int level,
  1368. const char *file, int line, const char *function, struct ast_callid *callid,
  1369. const char *fmt, ...)
  1370. {
  1371. struct logmsg *logmsg;
  1372. va_list ap;
  1373. va_start(ap, fmt);
  1374. logmsg = format_log_message_ap(level, file, line, function, callid, fmt, ap);
  1375. va_end(ap);
  1376. return logmsg;
  1377. }
  1378. /*! \brief Actual logging thread */
  1379. static void *logger_thread(void *data)
  1380. {
  1381. struct logmsg *next = NULL, *msg = NULL;
  1382. for (;;) {
  1383. /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
  1384. AST_LIST_LOCK(&logmsgs);
  1385. if (AST_LIST_EMPTY(&logmsgs)) {
  1386. if (close_logger_thread) {
  1387. AST_LIST_UNLOCK(&logmsgs);
  1388. break;
  1389. } else {
  1390. ast_cond_wait(&logcond, &logmsgs.lock);
  1391. }
  1392. }
  1393. if (high_water_alert) {
  1394. msg = format_log_message(__LOG_WARNING, "logger", 0, "***", NULL,
  1395. "Logging resumed. %d message%s discarded.\n",
  1396. logger_messages_discarded, logger_messages_discarded == 1 ? "" : "s");
  1397. if (msg) {
  1398. AST_LIST_INSERT_TAIL(&logmsgs, msg, list);
  1399. }
  1400. high_water_alert = 0;
  1401. logger_messages_discarded = 0;
  1402. }
  1403. next = AST_LIST_FIRST(&logmsgs);
  1404. AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
  1405. logger_queue_size = 0;
  1406. AST_LIST_UNLOCK(&logmsgs);
  1407. /* Otherwise go through and process each message in the order added */
  1408. while ((msg = next)) {
  1409. /* Get the next entry now so that we can free our current structure later */
  1410. next = AST_LIST_NEXT(msg, list);
  1411. /* Depending on the type, send it to the proper function */
  1412. logger_print_normal(msg);
  1413. /* Free the data since we are done */
  1414. logmsg_free(msg);
  1415. }
  1416. }
  1417. return NULL;
  1418. }
  1419. /*!
  1420. * \internal
  1421. * \brief Initialize the logger queue.
  1422. *
  1423. * \note Assumes logchannels is write locked on entry.
  1424. *
  1425. * \return Nothing
  1426. */
  1427. static void logger_queue_init(void)
  1428. {
  1429. ast_unload_realtime("queue_log");
  1430. if (logfiles.queue_log) {
  1431. char qfname[PATH_MAX];
  1432. if (logger_queue_rt_start()) {
  1433. return;
  1434. }
  1435. /* Open the log file. */
  1436. snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR,
  1437. queue_log_name);
  1438. if (qlog) {
  1439. /* Just in case it was already open. */
  1440. fclose(qlog);
  1441. }
  1442. qlog = fopen(qfname, "a");
  1443. if (!qlog) {
  1444. ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
  1445. }
  1446. }
  1447. }
  1448. int ast_is_logger_initialized(void)
  1449. {
  1450. return logger_initialized;
  1451. }
  1452. /*!
  1453. * \brief Start the ast_queue_log() logger.
  1454. *
  1455. * \note Called when the system is fully booted after startup
  1456. * so preloaded realtime modules can get up.
  1457. *
  1458. * \return Nothing
  1459. */
  1460. void logger_queue_start(void)
  1461. {
  1462. /* Must not be called before the logger is initialized. */
  1463. ast_assert(logger_initialized);
  1464. AST_RWLIST_WRLOCK(&logchannels);
  1465. if (!queuelog_init) {
  1466. logger_queue_init();
  1467. queuelog_init = 1;
  1468. AST_RWLIST_UNLOCK(&logchannels);
  1469. ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
  1470. } else {
  1471. AST_RWLIST_UNLOCK(&logchannels);
  1472. }
  1473. }
  1474. int init_logger(void)
  1475. {
  1476. int res;
  1477. /* auto rotate if sig SIGXFSZ comes a-knockin */
  1478. sigaction(SIGXFSZ, &handle_SIGXFSZ, NULL);
  1479. /* Re-initialize the logmsgs mutex. The recursive mutex can be accessed prior
  1480. * to Asterisk being forked into the background, which can cause the thread
  1481. * ID tracked by the underlying pthread mutex to be different than the ID of
  1482. * the thread that unlocks the mutex. Since init_logger is called after the
  1483. * fork, it is safe to initialize the mutex here for future accesses.
  1484. */
  1485. ast_mutex_destroy(&logmsgs.lock);
  1486. ast_mutex_init(&logmsgs.lock);
  1487. ast_cond_init(&logcond, NULL);
  1488. /* start logger thread */
  1489. if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
  1490. ast_cond_destroy(&logcond);
  1491. return -1;
  1492. }
  1493. /* register the logger cli commands */
  1494. ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
  1495. ast_mkdir(ast_config_AST_LOG_DIR, 0777);
  1496. /* create log channels */
  1497. res = init_logger_chain(0 /* locked */, NULL);
  1498. ast_verb_update();
  1499. logger_initialized = 1;
  1500. if (res) {
  1501. ast_log(LOG_ERROR, "Errors detected in logger.conf. Default console logging is being used.\n");
  1502. }
  1503. return 0;
  1504. }
  1505. void close_logger(void)
  1506. {
  1507. struct logchannel *f = NULL;
  1508. struct verb *cur = NULL;
  1509. ast_cli_unregister_multiple(cli_logger, ARRAY_LEN(cli_logger));
  1510. logger_initialized = 0;
  1511. /* Stop logger thread */
  1512. AST_LIST_LOCK(&logmsgs);
  1513. close_logger_thread = 1;
  1514. ast_cond_signal(&logcond);
  1515. AST_LIST_UNLOCK(&logmsgs);
  1516. if (logthread != AST_PTHREADT_NULL)
  1517. pthread_join(logthread, NULL);
  1518. AST_RWLIST_WRLOCK(&verbosers);
  1519. while ((cur = AST_LIST_REMOVE_HEAD(&verbosers, list))) {
  1520. ast_free(cur);
  1521. }
  1522. AST_RWLIST_UNLOCK(&verbosers);
  1523. AST_RWLIST_WRLOCK(&logchannels);
  1524. if (qlog) {
  1525. fclose(qlog);
  1526. qlog = NULL;
  1527. }
  1528. while ((f = AST_LIST_REMOVE_HEAD(&logchannels, list))) {
  1529. if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
  1530. fclose(f->fileptr);
  1531. f->fileptr = NULL;
  1532. }
  1533. ast_free(f);
  1534. }
  1535. closelog(); /* syslog */
  1536. AST_RWLIST_UNLOCK(&logchannels);
  1537. }
  1538. void ast_callid_strnprint(char *buffer, size_t buffer_size, struct ast_callid *callid)
  1539. {
  1540. snprintf(buffer, buffer_size, "[C-%08x]", (unsigned)callid->call_identifier);
  1541. }
  1542. struct ast_callid *ast_create_callid(void)
  1543. {
  1544. struct ast_callid *call;
  1545. call = ao2_alloc_options(sizeof(*call), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
  1546. if (!call) {
  1547. ast_log(LOG_ERROR, "Could not allocate callid struct.\n");
  1548. return NULL;
  1549. }
  1550. call->call_identifier = ast_atomic_fetchadd_int(&next_unique_callid, +1);
  1551. #ifdef TEST_FRAMEWORK
  1552. ast_debug(3, "CALL_ID [C-%08x] created by thread.\n", (unsigned)call->call_identifier);
  1553. #endif
  1554. return call;
  1555. }
  1556. struct ast_callid *ast_read_threadstorage_callid(void)
  1557. {
  1558. struct ast_callid **callid;
  1559. callid = ast_threadstorage_get(&unique_callid, sizeof(*callid));
  1560. if (callid && *callid) {
  1561. ast_callid_ref(*callid);
  1562. return *callid;
  1563. }
  1564. return NULL;
  1565. }
  1566. int ast_callid_threadassoc_change(struct ast_callid *callid)
  1567. {
  1568. struct ast_callid **id = ast_threadstorage_get(&unique_callid, sizeof(*id));
  1569. if (!id) {
  1570. ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
  1571. return -1;
  1572. }
  1573. if (*id && (*id != callid)) {
  1574. #ifdef TEST_FRAMEWORK
  1575. ast_debug(3, "CALL_ID [C-%08x] being removed from thread.\n", (unsigned)(*id)->call_identifier);
  1576. #endif
  1577. *id = ast_callid_unref(*id);
  1578. *id = NULL;
  1579. }
  1580. if (!(*id) && callid) {
  1581. /* callid will be unreffed at thread destruction */
  1582. ast_callid_ref(callid);
  1583. *id = callid;
  1584. #ifdef TEST_FRAMEWORK
  1585. ast_debug(3, "CALL_ID [C-%08x] bound to thread.\n", (unsigned)callid->call_identifier);
  1586. #endif
  1587. }
  1588. return 0;
  1589. }
  1590. int ast_callid_threadassoc_add(struct ast_callid *callid)
  1591. {
  1592. struct ast_callid **pointing;
  1593. pointing = ast_threadstorage_get(&unique_callid, sizeof(*pointing));
  1594. if (!(pointing)) {
  1595. ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
  1596. return -1;
  1597. }
  1598. if (!(*pointing)) {
  1599. /* callid will be unreffed at thread destruction */
  1600. ast_callid_ref(callid);
  1601. *pointing = callid;
  1602. #ifdef TEST_FRAMEWORK
  1603. ast_debug(3, "CALL_ID [C-%08x] bound to thread.\n", (unsigned)callid->call_identifier);
  1604. #endif
  1605. } else {
  1606. ast_log(LOG_WARNING, "Attempted to ast_callid_threadassoc_add on thread already associated with a callid.\n");
  1607. return 1;
  1608. }
  1609. return 0;
  1610. }
  1611. int ast_callid_threadassoc_remove(void)
  1612. {
  1613. struct ast_callid **pointing;
  1614. pointing = ast_threadstorage_get(&unique_callid, sizeof(*pointing));
  1615. if (!(pointing)) {
  1616. ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
  1617. return -1;
  1618. }
  1619. if (!(*pointing)) {
  1620. ast_log(LOG_ERROR, "Tried to clean callid thread storage with no callid in thread storage.\n");
  1621. return -1;
  1622. } else {
  1623. #ifdef TEST_FRAMEWORK
  1624. ast_debug(3, "CALL_ID [C-%08x] being removed from thread.\n", (unsigned)(*pointing)->call_identifier);
  1625. #endif
  1626. *pointing = ast_callid_unref(*pointing);
  1627. return 0;
  1628. }
  1629. }
  1630. int ast_callid_threadstorage_auto(struct ast_callid **callid)
  1631. {
  1632. struct ast_callid *tmp;
  1633. /* Start by trying to see if a callid is available from thread storage */
  1634. tmp = ast_read_threadstorage_callid();
  1635. if (tmp) {
  1636. *callid = tmp;
  1637. return 0;
  1638. }
  1639. /* If that failed, try to create a new one and bind it. */
  1640. tmp = ast_create_callid();
  1641. if (tmp) {
  1642. ast_callid_threadassoc_add(tmp);
  1643. *callid = tmp;
  1644. return 1;
  1645. }
  1646. /* If neither worked, then something must have gone wrong. */
  1647. return -1;
  1648. }
  1649. void ast_callid_threadstorage_auto_clean(struct ast_callid *callid, int callid_created)
  1650. {
  1651. if (callid) {
  1652. /* If the callid was created rather than simply grabbed from the thread storage, we need to unbind here. */
  1653. if (callid_created == 1) {
  1654. ast_callid_threadassoc_remove();
  1655. }
  1656. callid = ast_callid_unref(callid);
  1657. }
  1658. }
  1659. /*!
  1660. * \internal
  1661. * \brief thread storage cleanup function for unique_callid
  1662. */
  1663. static void unique_callid_cleanup(void *data)
  1664. {
  1665. struct ast_callid **callid = data;
  1666. if (*callid) {
  1667. ast_callid_unref(*callid);
  1668. }
  1669. ast_free(data);
  1670. }
  1671. /*!
  1672. * \brief send log messages to syslog and/or the console
  1673. */
  1674. static void __attribute__((format(printf, 6, 0))) ast_log_full(int level, const char *file,
  1675. int line, const char *function, struct ast_callid *callid, const char *fmt, va_list ap)
  1676. {
  1677. struct logmsg *logmsg = NULL;
  1678. /* Ignore anything that never gets logged anywhere */
  1679. if (level != __LOG_VERBOSE && !(global_logmask & (1 << level))) {
  1680. return;
  1681. }
  1682. AST_LIST_LOCK(&logmsgs);
  1683. if (logger_queue_size >= logger_queue_limit && !close_logger_thread) {
  1684. logger_messages_discarded++;
  1685. if (!high_water_alert && !close_logger_thread) {
  1686. logmsg = format_log_message(__LOG_WARNING, "logger", 0, "***", NULL,
  1687. "Log queue threshold (%d) exceeded. Discarding new messages.\n", logger_queue_limit);
  1688. AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
  1689. high_water_alert = 1;
  1690. ast_cond_signal(&logcond);
  1691. }
  1692. AST_LIST_UNLOCK(&logmsgs);
  1693. return;
  1694. }
  1695. AST_LIST_UNLOCK(&logmsgs);
  1696. logmsg = format_log_message_ap(level, file, line, function, callid, fmt, ap);
  1697. if (!logmsg) {
  1698. return;
  1699. }
  1700. /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
  1701. if (logthread != AST_PTHREADT_NULL) {
  1702. AST_LIST_LOCK(&logmsgs);
  1703. if (close_logger_thread) {
  1704. /* Logger is either closing or closed. We cannot log this message. */
  1705. logmsg_free(logmsg);
  1706. } else {
  1707. AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
  1708. logger_queue_size++;
  1709. ast_cond_signal(&logcond);
  1710. }
  1711. AST_LIST_UNLOCK(&logmsgs);
  1712. } else {
  1713. logger_print_normal(logmsg);
  1714. logmsg_free(logmsg);
  1715. }
  1716. }
  1717. void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
  1718. {
  1719. struct ast_callid *callid;
  1720. va_list ap;
  1721. callid = ast_read_threadstorage_callid();
  1722. va_start(ap, fmt);
  1723. if (level == __LOG_VERBOSE) {
  1724. __ast_verbose_ap(file, line, function, 0, callid, fmt, ap);
  1725. } else {
  1726. ast_log_full(level, file, line, function, callid, fmt, ap);
  1727. }
  1728. va_end(ap);
  1729. if (callid) {
  1730. ast_callid_unref(callid);
  1731. }
  1732. }
  1733. void ast_log_safe(int level, const char *file, int line, const char *function, const char *fmt, ...)
  1734. {
  1735. va_list ap;
  1736. void *recursed = ast_threadstorage_get_ptr(&in_safe_log);
  1737. struct ast_callid *callid;
  1738. if (recursed) {
  1739. return;
  1740. }
  1741. if (ast_threadstorage_set_ptr(&in_safe_log, (void*)1)) {
  1742. /* We've failed to set the flag that protects against
  1743. * recursion, so bail. */
  1744. return;
  1745. }
  1746. callid = ast_read_threadstorage_callid();
  1747. va_start(ap, fmt);
  1748. ast_log_full(level, file, line, function, callid, fmt, ap);
  1749. va_end(ap);
  1750. if (callid) {
  1751. ast_callid_unref(callid);
  1752. }
  1753. /* Clear flag so the next allocation failure can be logged. */
  1754. ast_threadstorage_set_ptr(&in_safe_log, NULL);
  1755. }
  1756. void ast_log_callid(int level, const char *file, int line, const char *function, struct ast_callid *callid, const char *fmt, ...)
  1757. {
  1758. va_list ap;
  1759. va_start(ap, fmt);
  1760. ast_log_full(level, file, line, function, callid, fmt, ap);
  1761. va_end(ap);
  1762. }
  1763. void ast_log_backtrace(void)
  1764. {
  1765. #ifdef HAVE_BKTR
  1766. struct ast_bt *bt;
  1767. int i = 0;
  1768. struct ast_vector_string *strings;
  1769. if (!(bt = ast_bt_create())) {
  1770. ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
  1771. return;
  1772. }
  1773. if ((strings = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
  1774. int count = AST_VECTOR_SIZE(strings);
  1775. struct ast_str *buf = ast_str_create(bt->num_frames * 64);
  1776. if (buf) {
  1777. ast_str_append(&buf, 0, "Got %d backtrace record%c\n", count - 3, count - 3 != 1 ? 's' : ' ');
  1778. for (i = 3; i < AST_VECTOR_SIZE(strings); i++) {
  1779. ast_str_append(&buf, 0, "#%2d: %s\n", i - 3, AST_VECTOR_GET(strings, i));
  1780. }
  1781. ast_log_safe(__LOG_ERROR, NULL, 0, NULL, "%s\n", ast_str_buffer(buf));
  1782. ast_free(buf);
  1783. }
  1784. ast_bt_free_symbols(strings);
  1785. } else {
  1786. ast_log(LOG_ERROR, "Could not allocate memory for backtrace\n");
  1787. }
  1788. ast_bt_destroy(bt);
  1789. #else
  1790. ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
  1791. #endif /* defined(HAVE_BKTR) */
  1792. }
  1793. void __ast_verbose_ap(const char *file, int line, const char *func, int level, struct ast_callid *callid, const char *fmt, va_list ap)
  1794. {
  1795. const char *p;
  1796. struct ast_str *prefixed, *buf;
  1797. int res = 0;
  1798. signed char magic = level > 9 ? -10 : -level - 1; /* 0 => -1, 1 => -2, etc. Can't pass NUL, as it is EOS-delimiter */
  1799. /* For compatibility with modules still calling ast_verbose() directly instead of using ast_verb() */
  1800. if (level < 0) {
  1801. if (!strncmp(fmt, VERBOSE_PREFIX_4, strlen(VERBOSE_PREFIX_4))) {
  1802. magic = -5;
  1803. } else if (!strncmp(fmt, VERBOSE_PREFIX_3, strlen(VERBOSE_PREFIX_3))) {
  1804. magic = -4;
  1805. } else if (!strncmp(fmt, VERBOSE_PREFIX_2, strlen(VERBOSE_PREFIX_2))) {
  1806. magic = -3;
  1807. } else if (!strncmp(fmt, VERBOSE_PREFIX_1, strlen(VERBOSE_PREFIX_1))) {
  1808. magic = -2;
  1809. } else {
  1810. magic = -1;
  1811. }
  1812. }
  1813. if (!(prefixed = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)) ||
  1814. !(buf = ast_str_thread_get(&verbose_build_buf, VERBOSE_BUF_INIT_SIZE))) {
  1815. return;
  1816. }
  1817. res = ast_str_set_va(&buf, 0, fmt, ap);
  1818. /* If the build failed then we can drop this allocated message */
  1819. if (res == AST_DYNSTR_BUILD_FAILED) {
  1820. return;
  1821. }
  1822. ast_str_reset(prefixed);
  1823. /* for every newline found in the buffer add verbose prefix data */
  1824. fmt = ast_str_buffer(buf);
  1825. do {
  1826. if (!(p = strchr(fmt, '\n'))) {
  1827. p = strchr(fmt, '\0') - 1;
  1828. }
  1829. ++p;
  1830. ast_str_append(&prefixed, 0, "%c", (char)magic);
  1831. ast_str_append_substr(&prefixed, 0, fmt, p - fmt);
  1832. fmt = p;
  1833. } while (p && *p);
  1834. ast_log_callid(__LOG_VERBOSE, file, line, func, callid, "%s", ast_str_buffer(prefixed));
  1835. }
  1836. void __ast_verbose(const char *file, int line, const char *func, int level, const char *fmt, ...)
  1837. {
  1838. struct ast_callid *callid;
  1839. va_list ap;
  1840. callid = ast_read_threadstorage_callid();
  1841. va_start(ap, fmt);
  1842. __ast_verbose_ap(file, line, func, level, callid, fmt, ap);
  1843. va_end(ap);
  1844. if (callid) {
  1845. ast_callid_unref(callid);
  1846. }
  1847. }
  1848. void __ast_verbose_callid(const char *file, int line, const char *func, int level, struct ast_callid *callid, const char *fmt, ...)
  1849. {
  1850. va_list ap;
  1851. va_start(ap, fmt);
  1852. __ast_verbose_ap(file, line, func, level, callid, fmt, ap);
  1853. va_end(ap);
  1854. }
  1855. /* No new code should use this directly, but we have the ABI for backwards compat */
  1856. #undef ast_verbose
  1857. void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
  1858. void ast_verbose(const char *fmt, ...)
  1859. {
  1860. struct ast_callid *callid;
  1861. va_list ap;
  1862. callid = ast_read_threadstorage_callid();
  1863. va_start(ap, fmt);
  1864. __ast_verbose_ap("", 0, "", 0, callid, fmt, ap);
  1865. va_end(ap);
  1866. if (callid) {
  1867. ast_callid_unref(callid);
  1868. }
  1869. }
  1870. /*! Console verbosity level node. */
  1871. struct verb_console {
  1872. /*! List node link */
  1873. AST_LIST_ENTRY(verb_console) node;
  1874. /*! Console verbosity level. */
  1875. int *level;
  1876. };
  1877. /*! Registered console verbosity levels */
  1878. static AST_RWLIST_HEAD_STATIC(verb_consoles, verb_console);
  1879. /*! ast_verb_update() reentrancy protection lock. */
  1880. AST_MUTEX_DEFINE_STATIC(verb_update_lock);
  1881. void ast_verb_update(void)
  1882. {
  1883. struct logchannel *log;
  1884. struct verb_console *console;
  1885. int verb_level;
  1886. ast_mutex_lock(&verb_update_lock);
  1887. AST_RWLIST_RDLOCK(&verb_consoles);
  1888. /* Default to the root console verbosity. */
  1889. verb_level = option_verbose;
  1890. /* Determine max remote console level. */
  1891. AST_LIST_TRAVERSE(&verb_consoles, console, node) {
  1892. if (verb_level < *console->level) {
  1893. verb_level = *console->level;
  1894. }
  1895. }
  1896. AST_RWLIST_UNLOCK(&verb_consoles);
  1897. /* Determine max logger channel level. */
  1898. AST_RWLIST_RDLOCK(&logchannels);
  1899. AST_RWLIST_TRAVERSE(&logchannels, log, list) {
  1900. if (verb_level < log->verbosity) {
  1901. verb_level = log->verbosity;
  1902. }
  1903. }
  1904. AST_RWLIST_UNLOCK(&logchannels);
  1905. ast_verb_sys_level = verb_level;
  1906. ast_mutex_unlock(&verb_update_lock);
  1907. }
  1908. /*!
  1909. * \internal
  1910. * \brief Unregister a console verbose level.
  1911. *
  1912. * \param console Which console to unregister.
  1913. *
  1914. * \return Nothing
  1915. */
  1916. static void verb_console_unregister(struct verb_console *console)
  1917. {
  1918. AST_RWLIST_WRLOCK(&verb_consoles);
  1919. console = AST_RWLIST_REMOVE(&verb_consoles, console, node);
  1920. AST_RWLIST_UNLOCK(&verb_consoles);
  1921. if (console) {
  1922. ast_verb_update();
  1923. }
  1924. }
  1925. static void verb_console_free(void *v_console)
  1926. {
  1927. struct verb_console *console = v_console;
  1928. verb_console_unregister(console);
  1929. ast_free(console);
  1930. }
  1931. /*! Thread specific console verbosity level node. */
  1932. AST_THREADSTORAGE_CUSTOM(my_verb_console, NULL, verb_console_free);
  1933. void ast_verb_console_register(int *level)
  1934. {
  1935. struct verb_console *console;
  1936. console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
  1937. if (!console || !level) {
  1938. return;
  1939. }
  1940. console->level = level;
  1941. AST_RWLIST_WRLOCK(&verb_consoles);
  1942. AST_RWLIST_INSERT_HEAD(&verb_consoles, console, node);
  1943. AST_RWLIST_UNLOCK(&verb_consoles);
  1944. ast_verb_update();
  1945. }
  1946. void ast_verb_console_unregister(void)
  1947. {
  1948. struct verb_console *console;
  1949. console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
  1950. if (!console) {
  1951. return;
  1952. }
  1953. verb_console_unregister(console);
  1954. }
  1955. int ast_verb_console_get(void)
  1956. {
  1957. struct verb_console *console;
  1958. int verb_level;
  1959. console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
  1960. AST_RWLIST_RDLOCK(&verb_consoles);
  1961. if (!console) {
  1962. verb_level = 0;
  1963. } else if (console->level) {
  1964. verb_level = *console->level;
  1965. } else {
  1966. verb_level = option_verbose;
  1967. }
  1968. AST_RWLIST_UNLOCK(&verb_consoles);
  1969. return verb_level;
  1970. }
  1971. void ast_verb_console_set(int verb_level)
  1972. {
  1973. struct verb_console *console;
  1974. console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
  1975. if (!console) {
  1976. return;
  1977. }
  1978. AST_RWLIST_WRLOCK(&verb_consoles);
  1979. if (console->level) {
  1980. *console->level = verb_level;
  1981. } else {
  1982. option_verbose = verb_level;
  1983. }
  1984. AST_RWLIST_UNLOCK(&verb_consoles);
  1985. ast_verb_update();
  1986. }
  1987. int ast_register_verbose(void (*v)(const char *string))
  1988. {
  1989. struct verb *verb;
  1990. if (!(verb = ast_malloc(sizeof(*verb))))
  1991. return -1;
  1992. verb->verboser = v;
  1993. AST_RWLIST_WRLOCK(&verbosers);
  1994. AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
  1995. AST_RWLIST_UNLOCK(&verbosers);
  1996. return 0;
  1997. }
  1998. int ast_unregister_verbose(void (*v)(const char *string))
  1999. {
  2000. struct verb *cur;
  2001. AST_RWLIST_WRLOCK(&verbosers);
  2002. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
  2003. if (cur->verboser == v) {
  2004. AST_RWLIST_REMOVE_CURRENT(list);
  2005. ast_free(cur);
  2006. break;
  2007. }
  2008. }
  2009. AST_RWLIST_TRAVERSE_SAFE_END;
  2010. AST_RWLIST_UNLOCK(&verbosers);
  2011. return cur ? 0 : -1;
  2012. }
  2013. static void update_logchannels(void)
  2014. {
  2015. struct logchannel *cur;
  2016. AST_RWLIST_WRLOCK(&logchannels);
  2017. global_logmask = 0;
  2018. AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
  2019. make_components(cur);
  2020. global_logmask |= cur->logmask;
  2021. }
  2022. AST_RWLIST_UNLOCK(&logchannels);
  2023. }
  2024. int ast_logger_register_level(const char *name)
  2025. {
  2026. unsigned int level;
  2027. unsigned int available = 0;
  2028. AST_RWLIST_WRLOCK(&logchannels);
  2029. for (level = 0; level < ARRAY_LEN(levels); level++) {
  2030. if ((level >= 16) && !available && !levels[level]) {
  2031. available = level;
  2032. continue;
  2033. }
  2034. if (levels[level] && !strcasecmp(levels[level], name)) {
  2035. ast_log(LOG_WARNING,
  2036. "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
  2037. name);
  2038. AST_RWLIST_UNLOCK(&logchannels);
  2039. return -1;
  2040. }
  2041. }
  2042. if (!available) {
  2043. ast_log(LOG_WARNING,
  2044. "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
  2045. name);
  2046. AST_RWLIST_UNLOCK(&logchannels);
  2047. return -1;
  2048. }
  2049. levels[available] = ast_strdup(name);
  2050. AST_RWLIST_UNLOCK(&logchannels);
  2051. ast_debug(1, "Registered dynamic logger level '%s' with index %u.\n", name, available);
  2052. update_logchannels();
  2053. return available;
  2054. }
  2055. void ast_logger_unregister_level(const char *name)
  2056. {
  2057. unsigned int found = 0;
  2058. unsigned int x;
  2059. AST_RWLIST_WRLOCK(&logchannels);
  2060. for (x = 16; x < ARRAY_LEN(levels); x++) {
  2061. if (!levels[x]) {
  2062. continue;
  2063. }
  2064. if (strcasecmp(levels[x], name)) {
  2065. continue;
  2066. }
  2067. found = 1;
  2068. break;
  2069. }
  2070. if (found) {
  2071. /* take this level out of the global_logmask, to ensure that no new log messages
  2072. * will be queued for it
  2073. */
  2074. global_logmask &= ~(1 << x);
  2075. ast_free(levels[x]);
  2076. levels[x] = NULL;
  2077. AST_RWLIST_UNLOCK(&logchannels);
  2078. ast_debug(1, "Unregistered dynamic logger level '%s' with index %u.\n", name, x);
  2079. update_logchannels();
  2080. } else {
  2081. AST_RWLIST_UNLOCK(&logchannels);
  2082. }
  2083. }
  2084. const char *ast_logger_get_dateformat(void)
  2085. {
  2086. return dateformat;
  2087. }
  2088. void ast_logger_set_queue_limit(int queue_limit)
  2089. {
  2090. logger_queue_limit = queue_limit;
  2091. }
  2092. int ast_logger_get_queue_limit(void)
  2093. {
  2094. return logger_queue_limit;
  2095. }