logger.c 54 KB

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