logger.c 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  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. /*** MODULEINFO
  27. <support_level>core</support_level>
  28. ***/
  29. #include "asterisk.h"
  30. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  31. /* When we include logger.h again it will trample on some stuff in syslog.h, but
  32. * nothing we care about in here. */
  33. #include <syslog.h>
  34. #include "asterisk/_private.h"
  35. #include "asterisk/paths.h" /* use ast_config_AST_LOG_DIR */
  36. #include "asterisk/logger.h"
  37. #include "asterisk/lock.h"
  38. #include "asterisk/channel.h"
  39. #include "asterisk/config.h"
  40. #include "asterisk/term.h"
  41. #include "asterisk/cli.h"
  42. #include "asterisk/utils.h"
  43. #include "asterisk/manager.h"
  44. #include "asterisk/threadstorage.h"
  45. #include "asterisk/strings.h"
  46. #include "asterisk/pbx.h"
  47. #include "asterisk/app.h"
  48. #include "asterisk/syslog.h"
  49. #include <signal.h>
  50. #include <time.h>
  51. #include <sys/stat.h>
  52. #include <fcntl.h>
  53. #ifdef HAVE_BKTR
  54. #include <execinfo.h>
  55. #define MAX_BACKTRACE_FRAMES 20
  56. # if defined(HAVE_DLADDR) && defined(HAVE_BFD) && defined(BETTER_BACKTRACES)
  57. # include <dlfcn.h>
  58. # include <bfd.h>
  59. # endif
  60. #endif
  61. static char dateformat[256] = "%b %e %T"; /* Original Asterisk Format */
  62. static char queue_log_name[256] = QUEUELOG;
  63. static char exec_after_rotate[256] = "";
  64. static int filesize_reload_needed;
  65. static unsigned int global_logmask = 0xFFFF;
  66. static int queuelog_init;
  67. static int logger_initialized;
  68. static enum rotatestrategy {
  69. SEQUENTIAL = 1 << 0, /* Original method - create a new file, in order */
  70. ROTATE = 1 << 1, /* Rotate all files, such that the oldest file has the highest suffix */
  71. TIMESTAMP = 1 << 2, /* Append the epoch timestamp onto the end of the archived file */
  72. } rotatestrategy = SEQUENTIAL;
  73. static struct {
  74. unsigned int queue_log:1;
  75. unsigned int queue_log_to_file:1;
  76. unsigned int queue_adaptive_realtime:1;
  77. } logfiles = { 1 };
  78. static char hostname[MAXHOSTNAMELEN];
  79. enum logtypes {
  80. LOGTYPE_SYSLOG,
  81. LOGTYPE_FILE,
  82. LOGTYPE_CONSOLE,
  83. };
  84. struct logchannel {
  85. /*! What to log to this channel */
  86. unsigned int logmask;
  87. /*! If this channel is disabled or not */
  88. int disabled;
  89. /*! syslog facility */
  90. int facility;
  91. /*! Type of log channel */
  92. enum logtypes type;
  93. /*! logfile logging file pointer */
  94. FILE *fileptr;
  95. /*! Filename */
  96. char filename[PATH_MAX];
  97. /*! field for linking to list */
  98. AST_LIST_ENTRY(logchannel) list;
  99. /*! Line number from configuration file */
  100. int lineno;
  101. /*! Components (levels) from last config load */
  102. char components[0];
  103. };
  104. static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
  105. enum logmsgtypes {
  106. LOGMSG_NORMAL = 0,
  107. LOGMSG_VERBOSE,
  108. };
  109. struct logmsg {
  110. enum logmsgtypes type;
  111. int level;
  112. int line;
  113. long process_id;
  114. AST_DECLARE_STRING_FIELDS(
  115. AST_STRING_FIELD(date);
  116. AST_STRING_FIELD(file);
  117. AST_STRING_FIELD(function);
  118. AST_STRING_FIELD(message);
  119. AST_STRING_FIELD(level_name);
  120. );
  121. AST_LIST_ENTRY(logmsg) list;
  122. };
  123. static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
  124. static pthread_t logthread = AST_PTHREADT_NULL;
  125. static ast_cond_t logcond;
  126. static int close_logger_thread = 0;
  127. static FILE *qlog;
  128. /*! \brief Logging channels used in the Asterisk logging system
  129. *
  130. * The first 16 levels are reserved for system usage, and the remaining
  131. * levels are reserved for usage by dynamic levels registered via
  132. * ast_logger_register_level.
  133. */
  134. /* Modifications to this array are protected by the rwlock in the
  135. * logchannels list.
  136. */
  137. static char *levels[NUMLOGLEVELS] = {
  138. "DEBUG",
  139. "---EVENT---", /* no longer used */
  140. "NOTICE",
  141. "WARNING",
  142. "ERROR",
  143. "VERBOSE",
  144. "DTMF",
  145. };
  146. /*! \brief Colors used in the console for logging */
  147. static const int colors[NUMLOGLEVELS] = {
  148. COLOR_BRGREEN,
  149. COLOR_BRBLUE, /* no longer used */
  150. COLOR_YELLOW,
  151. COLOR_BRRED,
  152. COLOR_RED,
  153. COLOR_GREEN,
  154. COLOR_BRGREEN,
  155. 0,
  156. 0,
  157. 0,
  158. 0,
  159. 0,
  160. 0,
  161. 0,
  162. 0,
  163. 0,
  164. COLOR_BRBLUE,
  165. COLOR_BRBLUE,
  166. COLOR_BRBLUE,
  167. COLOR_BRBLUE,
  168. COLOR_BRBLUE,
  169. COLOR_BRBLUE,
  170. COLOR_BRBLUE,
  171. COLOR_BRBLUE,
  172. COLOR_BRBLUE,
  173. COLOR_BRBLUE,
  174. COLOR_BRBLUE,
  175. COLOR_BRBLUE,
  176. COLOR_BRBLUE,
  177. COLOR_BRBLUE,
  178. COLOR_BRBLUE,
  179. COLOR_BRBLUE,
  180. };
  181. AST_THREADSTORAGE(verbose_buf);
  182. #define VERBOSE_BUF_INIT_SIZE 256
  183. AST_THREADSTORAGE(log_buf);
  184. #define LOG_BUF_INIT_SIZE 256
  185. static void logger_queue_init(void);
  186. static unsigned int make_components(const char *s, int lineno)
  187. {
  188. char *w;
  189. unsigned int res = 0;
  190. char *stringp = ast_strdupa(s);
  191. unsigned int x;
  192. while ((w = strsep(&stringp, ","))) {
  193. w = ast_skip_blanks(w);
  194. if (!strcmp(w, "*")) {
  195. res = 0xFFFFFFFF;
  196. break;
  197. } else for (x = 0; x < ARRAY_LEN(levels); x++) {
  198. if (levels[x] && !strcasecmp(w, levels[x])) {
  199. res |= (1 << x);
  200. break;
  201. }
  202. }
  203. }
  204. return res;
  205. }
  206. static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
  207. {
  208. struct logchannel *chan;
  209. char *facility;
  210. if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan) + strlen(components) + 1)))
  211. return NULL;
  212. strcpy(chan->components, components);
  213. chan->lineno = lineno;
  214. if (!strcasecmp(channel, "console")) {
  215. chan->type = LOGTYPE_CONSOLE;
  216. } else if (!strncasecmp(channel, "syslog", 6)) {
  217. /*
  218. * syntax is:
  219. * syslog.facility => level,level,level
  220. */
  221. facility = strchr(channel, '.');
  222. if (!facility++ || !facility) {
  223. facility = "local0";
  224. }
  225. chan->facility = ast_syslog_facility(facility);
  226. if (chan->facility < 0) {
  227. fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
  228. ast_free(chan);
  229. return NULL;
  230. }
  231. chan->type = LOGTYPE_SYSLOG;
  232. ast_copy_string(chan->filename, channel, sizeof(chan->filename));
  233. openlog("asterisk", LOG_PID, chan->facility);
  234. } else {
  235. const char *log_dir_prefix = "";
  236. const char *log_dir_separator = "";
  237. if (channel[0] != '/') {
  238. log_dir_prefix = ast_config_AST_LOG_DIR;
  239. log_dir_separator = "/";
  240. }
  241. if (!ast_strlen_zero(hostname)) {
  242. snprintf(chan->filename, sizeof(chan->filename), "%s%s%s.%s",
  243. log_dir_prefix, log_dir_separator, channel, hostname);
  244. } else {
  245. snprintf(chan->filename, sizeof(chan->filename), "%s%s%s",
  246. log_dir_prefix, log_dir_separator, channel);
  247. }
  248. if (!(chan->fileptr = fopen(chan->filename, "a"))) {
  249. /* Can't do real logging here since we're called with a lock
  250. * so log to any attached consoles */
  251. ast_console_puts_mutable("ERROR: Unable to open log file '", __LOG_ERROR);
  252. ast_console_puts_mutable(chan->filename, __LOG_ERROR);
  253. ast_console_puts_mutable("': ", __LOG_ERROR);
  254. ast_console_puts_mutable(strerror(errno), __LOG_ERROR);
  255. ast_console_puts_mutable("'\n", __LOG_ERROR);
  256. ast_free(chan);
  257. return NULL;
  258. }
  259. chan->type = LOGTYPE_FILE;
  260. }
  261. chan->logmask = make_components(chan->components, lineno);
  262. return chan;
  263. }
  264. static void init_logger_chain(int locked)
  265. {
  266. struct logchannel *chan;
  267. struct ast_config *cfg;
  268. struct ast_variable *var;
  269. const char *s;
  270. struct ast_flags config_flags = { 0 };
  271. if (!(cfg = ast_config_load2("logger.conf", "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
  272. return;
  273. }
  274. /* delete our list of log channels */
  275. if (!locked) {
  276. AST_RWLIST_WRLOCK(&logchannels);
  277. }
  278. while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list))) {
  279. ast_free(chan);
  280. }
  281. global_logmask = 0;
  282. if (!locked) {
  283. AST_RWLIST_UNLOCK(&logchannels);
  284. }
  285. errno = 0;
  286. /* close syslog */
  287. closelog();
  288. /* If no config file, we're fine, set default options. */
  289. if (!cfg) {
  290. if (errno) {
  291. fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
  292. } else {
  293. fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
  294. }
  295. if (!(chan = ast_calloc(1, sizeof(*chan)))) {
  296. return;
  297. }
  298. chan->type = LOGTYPE_CONSOLE;
  299. chan->logmask = __LOG_WARNING | __LOG_NOTICE | __LOG_ERROR;
  300. if (!locked) {
  301. AST_RWLIST_WRLOCK(&logchannels);
  302. }
  303. AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
  304. global_logmask |= chan->logmask;
  305. if (!locked) {
  306. AST_RWLIST_UNLOCK(&logchannels);
  307. }
  308. return;
  309. }
  310. if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
  311. if (ast_true(s)) {
  312. if (gethostname(hostname, sizeof(hostname) - 1)) {
  313. ast_copy_string(hostname, "unknown", sizeof(hostname));
  314. fprintf(stderr, "What box has no hostname???\n");
  315. }
  316. } else
  317. hostname[0] = '\0';
  318. } else
  319. hostname[0] = '\0';
  320. if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
  321. ast_copy_string(dateformat, s, sizeof(dateformat));
  322. else
  323. ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
  324. if ((s = ast_variable_retrieve(cfg, "general", "queue_log"))) {
  325. logfiles.queue_log = ast_true(s);
  326. }
  327. if ((s = ast_variable_retrieve(cfg, "general", "queue_log_to_file"))) {
  328. logfiles.queue_log_to_file = ast_true(s);
  329. }
  330. if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name"))) {
  331. ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
  332. }
  333. if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate"))) {
  334. ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
  335. }
  336. if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
  337. if (strcasecmp(s, "timestamp") == 0) {
  338. rotatestrategy = TIMESTAMP;
  339. } else if (strcasecmp(s, "rotate") == 0) {
  340. rotatestrategy = ROTATE;
  341. } else if (strcasecmp(s, "sequential") == 0) {
  342. rotatestrategy = SEQUENTIAL;
  343. } else {
  344. fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
  345. }
  346. } else {
  347. if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
  348. rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
  349. fprintf(stderr, "rotatetimestamp option has been deprecated. Please use rotatestrategy instead.\n");
  350. }
  351. }
  352. if (!locked) {
  353. AST_RWLIST_WRLOCK(&logchannels);
  354. }
  355. var = ast_variable_browse(cfg, "logfiles");
  356. for (; var; var = var->next) {
  357. if (!(chan = make_logchannel(var->name, var->value, var->lineno))) {
  358. /* Print error message directly to the consoles since the lock is held
  359. * and we don't want to unlock with the list partially built */
  360. ast_console_puts_mutable("ERROR: Unable to create log channel '", __LOG_ERROR);
  361. ast_console_puts_mutable(var->name, __LOG_ERROR);
  362. ast_console_puts_mutable("'\n", __LOG_ERROR);
  363. continue;
  364. }
  365. AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
  366. global_logmask |= chan->logmask;
  367. }
  368. if (qlog) {
  369. fclose(qlog);
  370. qlog = NULL;
  371. }
  372. if (!locked) {
  373. AST_RWLIST_UNLOCK(&logchannels);
  374. }
  375. ast_config_destroy(cfg);
  376. }
  377. void ast_child_verbose(int level, const char *fmt, ...)
  378. {
  379. char *msg = NULL, *emsg = NULL, *sptr, *eptr;
  380. va_list ap, aq;
  381. int size;
  382. /* Don't bother, if the level isn't that high */
  383. if (option_verbose < level) {
  384. return;
  385. }
  386. va_start(ap, fmt);
  387. va_copy(aq, ap);
  388. if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
  389. va_end(ap);
  390. va_end(aq);
  391. return;
  392. }
  393. va_end(ap);
  394. if (!(msg = ast_malloc(size + 1))) {
  395. va_end(aq);
  396. return;
  397. }
  398. vsnprintf(msg, size + 1, fmt, aq);
  399. va_end(aq);
  400. if (!(emsg = ast_malloc(size * 2 + 1))) {
  401. ast_free(msg);
  402. return;
  403. }
  404. for (sptr = msg, eptr = emsg; ; sptr++) {
  405. if (*sptr == '"') {
  406. *eptr++ = '\\';
  407. }
  408. *eptr++ = *sptr;
  409. if (*sptr == '\0') {
  410. break;
  411. }
  412. }
  413. ast_free(msg);
  414. fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
  415. fflush(stdout);
  416. ast_free(emsg);
  417. }
  418. void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
  419. {
  420. va_list ap;
  421. struct timeval tv;
  422. struct ast_tm tm;
  423. char qlog_msg[8192];
  424. int qlog_len;
  425. char time_str[30];
  426. if (!logger_initialized) {
  427. /* You are too early. We are not open yet! */
  428. return;
  429. }
  430. if (!queuelog_init) {
  431. AST_RWLIST_WRLOCK(&logchannels);
  432. if (!queuelog_init) {
  433. /*
  434. * We have delayed initializing the queue logging system so
  435. * preloaded realtime modules can get up. We must initialize
  436. * now since someone is trying to log something.
  437. */
  438. logger_queue_init();
  439. queuelog_init = 1;
  440. AST_RWLIST_UNLOCK(&logchannels);
  441. ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
  442. } else {
  443. AST_RWLIST_UNLOCK(&logchannels);
  444. }
  445. }
  446. if (ast_check_realtime("queue_log")) {
  447. tv = ast_tvnow();
  448. ast_localtime(&tv, &tm, NULL);
  449. ast_strftime(time_str, sizeof(time_str), "%F %T.%6q", &tm);
  450. va_start(ap, fmt);
  451. vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
  452. va_end(ap);
  453. if (logfiles.queue_adaptive_realtime) {
  454. AST_DECLARE_APP_ARGS(args,
  455. AST_APP_ARG(data)[5];
  456. );
  457. AST_NONSTANDARD_APP_ARGS(args, qlog_msg, '|');
  458. /* Ensure fields are large enough to receive data */
  459. ast_realtime_require_field("queue_log",
  460. "data1", RQ_CHAR, strlen(S_OR(args.data[0], "")),
  461. "data2", RQ_CHAR, strlen(S_OR(args.data[1], "")),
  462. "data3", RQ_CHAR, strlen(S_OR(args.data[2], "")),
  463. "data4", RQ_CHAR, strlen(S_OR(args.data[3], "")),
  464. "data5", RQ_CHAR, strlen(S_OR(args.data[4], "")),
  465. SENTINEL);
  466. /* Store the log */
  467. ast_store_realtime("queue_log", "time", time_str,
  468. "callid", callid,
  469. "queuename", queuename,
  470. "agent", agent,
  471. "event", event,
  472. "data1", S_OR(args.data[0], ""),
  473. "data2", S_OR(args.data[1], ""),
  474. "data3", S_OR(args.data[2], ""),
  475. "data4", S_OR(args.data[3], ""),
  476. "data5", S_OR(args.data[4], ""),
  477. SENTINEL);
  478. } else {
  479. ast_store_realtime("queue_log", "time", time_str,
  480. "callid", callid,
  481. "queuename", queuename,
  482. "agent", agent,
  483. "event", event,
  484. "data", qlog_msg,
  485. SENTINEL);
  486. }
  487. if (!logfiles.queue_log_to_file) {
  488. return;
  489. }
  490. }
  491. if (qlog) {
  492. va_start(ap, fmt);
  493. qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
  494. vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
  495. va_end(ap);
  496. AST_RWLIST_RDLOCK(&logchannels);
  497. if (qlog) {
  498. fprintf(qlog, "%s\n", qlog_msg);
  499. fflush(qlog);
  500. }
  501. AST_RWLIST_UNLOCK(&logchannels);
  502. }
  503. }
  504. static int rotate_file(const char *filename)
  505. {
  506. char old[PATH_MAX];
  507. char new[PATH_MAX];
  508. int x, y, which, found, res = 0, fd;
  509. char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
  510. switch (rotatestrategy) {
  511. case SEQUENTIAL:
  512. for (x = 0; ; x++) {
  513. snprintf(new, sizeof(new), "%s.%d", filename, x);
  514. fd = open(new, O_RDONLY);
  515. if (fd > -1)
  516. close(fd);
  517. else
  518. break;
  519. }
  520. if (rename(filename, new)) {
  521. fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
  522. res = -1;
  523. } else {
  524. filename = new;
  525. }
  526. break;
  527. case TIMESTAMP:
  528. snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
  529. if (rename(filename, new)) {
  530. fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
  531. res = -1;
  532. } else {
  533. filename = new;
  534. }
  535. break;
  536. case ROTATE:
  537. /* Find the next empty slot, including a possible suffix */
  538. for (x = 0; ; x++) {
  539. found = 0;
  540. for (which = 0; which < ARRAY_LEN(suffixes); which++) {
  541. snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
  542. fd = open(new, O_RDONLY);
  543. if (fd > -1) {
  544. close(fd);
  545. found = 1;
  546. break;
  547. }
  548. }
  549. if (!found) {
  550. break;
  551. }
  552. }
  553. /* Found an empty slot */
  554. for (y = x; y > 0; y--) {
  555. for (which = 0; which < ARRAY_LEN(suffixes); which++) {
  556. snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
  557. fd = open(old, O_RDONLY);
  558. if (fd > -1) {
  559. /* Found the right suffix */
  560. close(fd);
  561. snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
  562. if (rename(old, new)) {
  563. fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
  564. res = -1;
  565. }
  566. break;
  567. }
  568. }
  569. }
  570. /* Finally, rename the current file */
  571. snprintf(new, sizeof(new), "%s.0", filename);
  572. if (rename(filename, new)) {
  573. fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
  574. res = -1;
  575. } else {
  576. filename = new;
  577. }
  578. }
  579. if (!ast_strlen_zero(exec_after_rotate)) {
  580. struct ast_channel *c = ast_dummy_channel_alloc();
  581. char buf[512];
  582. pbx_builtin_setvar_helper(c, "filename", filename);
  583. pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
  584. if (c) {
  585. c = ast_channel_unref(c);
  586. }
  587. if (ast_safe_system(buf) == -1) {
  588. ast_log(LOG_WARNING, "error executing '%s'\n", buf);
  589. }
  590. }
  591. return res;
  592. }
  593. /*!
  594. * \internal
  595. * \brief Start the realtime queue logging if configured.
  596. *
  597. * \retval TRUE if not to open queue log file.
  598. */
  599. static int logger_queue_rt_start(void)
  600. {
  601. if (ast_check_realtime("queue_log")) {
  602. if (!ast_realtime_require_field("queue_log",
  603. "time", RQ_DATETIME, 26,
  604. "data1", RQ_CHAR, 20,
  605. "data2", RQ_CHAR, 20,
  606. "data3", RQ_CHAR, 20,
  607. "data4", RQ_CHAR, 20,
  608. "data5", RQ_CHAR, 20,
  609. SENTINEL)) {
  610. logfiles.queue_adaptive_realtime = 1;
  611. } else {
  612. logfiles.queue_adaptive_realtime = 0;
  613. }
  614. if (!logfiles.queue_log_to_file) {
  615. /* Don't open the log file. */
  616. return 1;
  617. }
  618. }
  619. return 0;
  620. }
  621. /*!
  622. * \internal
  623. * \brief Rotate the queue log file and restart.
  624. *
  625. * \param queue_rotate Log queue rotation mode.
  626. *
  627. * \note Assumes logchannels is write locked on entry.
  628. *
  629. * \retval 0 on success.
  630. * \retval -1 on error.
  631. */
  632. static int logger_queue_restart(int queue_rotate)
  633. {
  634. int res = 0;
  635. char qfname[PATH_MAX];
  636. if (logger_queue_rt_start()) {
  637. return res;
  638. }
  639. snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
  640. if (qlog) {
  641. /* Just in case it was still open. */
  642. fclose(qlog);
  643. qlog = NULL;
  644. }
  645. if (queue_rotate) {
  646. rotate_file(qfname);
  647. }
  648. /* Open the log file. */
  649. qlog = fopen(qfname, "a");
  650. if (!qlog) {
  651. ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
  652. res = -1;
  653. }
  654. return res;
  655. }
  656. static int reload_logger(int rotate)
  657. {
  658. int queue_rotate = rotate;
  659. struct logchannel *f;
  660. int res = 0;
  661. AST_RWLIST_WRLOCK(&logchannels);
  662. if (qlog) {
  663. if (rotate < 0) {
  664. /* Check filesize - this one typically doesn't need an auto-rotate */
  665. if (ftello(qlog) > 0x40000000) { /* Arbitrarily, 1 GB */
  666. fclose(qlog);
  667. qlog = NULL;
  668. } else {
  669. queue_rotate = 0;
  670. }
  671. } else {
  672. fclose(qlog);
  673. qlog = NULL;
  674. }
  675. } else {
  676. queue_rotate = 0;
  677. }
  678. ast_mkdir(ast_config_AST_LOG_DIR, 0777);
  679. AST_RWLIST_TRAVERSE(&logchannels, f, list) {
  680. if (f->disabled) {
  681. f->disabled = 0; /* Re-enable logging at reload */
  682. manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
  683. }
  684. if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
  685. int rotate_this = 0;
  686. if (ftello(f->fileptr) > 0x40000000) { /* Arbitrarily, 1 GB */
  687. /* Be more proactive about rotating massive log files */
  688. rotate_this = 1;
  689. }
  690. fclose(f->fileptr); /* Close file */
  691. f->fileptr = NULL;
  692. if (rotate || rotate_this) {
  693. rotate_file(f->filename);
  694. }
  695. }
  696. }
  697. filesize_reload_needed = 0;
  698. init_logger_chain(1 /* locked */);
  699. ast_unload_realtime("queue_log");
  700. if (logfiles.queue_log) {
  701. res = logger_queue_restart(queue_rotate);
  702. AST_RWLIST_UNLOCK(&logchannels);
  703. ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
  704. ast_verb(1, "Asterisk Queue Logger restarted\n");
  705. } else {
  706. AST_RWLIST_UNLOCK(&logchannels);
  707. }
  708. return res;
  709. }
  710. /*! \brief Reload the logger module without rotating log files (also used from loader.c during
  711. a full Asterisk reload) */
  712. int logger_reload(void)
  713. {
  714. if (reload_logger(0)) {
  715. return RESULT_FAILURE;
  716. }
  717. return RESULT_SUCCESS;
  718. }
  719. static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  720. {
  721. switch (cmd) {
  722. case CLI_INIT:
  723. e->command = "logger reload";
  724. e->usage =
  725. "Usage: logger reload\n"
  726. " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
  727. return NULL;
  728. case CLI_GENERATE:
  729. return NULL;
  730. }
  731. if (reload_logger(0)) {
  732. ast_cli(a->fd, "Failed to reload the logger\n");
  733. return CLI_FAILURE;
  734. }
  735. return CLI_SUCCESS;
  736. }
  737. static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  738. {
  739. switch (cmd) {
  740. case CLI_INIT:
  741. e->command = "logger rotate";
  742. e->usage =
  743. "Usage: logger rotate\n"
  744. " Rotates and Reopens the log files.\n";
  745. return NULL;
  746. case CLI_GENERATE:
  747. return NULL;
  748. }
  749. if (reload_logger(1)) {
  750. ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
  751. return CLI_FAILURE;
  752. }
  753. return CLI_SUCCESS;
  754. }
  755. static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  756. {
  757. int x;
  758. int state;
  759. int level = -1;
  760. switch (cmd) {
  761. case CLI_INIT:
  762. e->command = "logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}";
  763. e->usage =
  764. "Usage: logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}\n"
  765. " Set a specific log level to enabled/disabled for this console.\n";
  766. return NULL;
  767. case CLI_GENERATE:
  768. return NULL;
  769. }
  770. if (a->argc < 5)
  771. return CLI_SHOWUSAGE;
  772. AST_RWLIST_WRLOCK(&logchannels);
  773. for (x = 0; x < ARRAY_LEN(levels); x++) {
  774. if (levels[x] && !strcasecmp(a->argv[3], levels[x])) {
  775. level = x;
  776. break;
  777. }
  778. }
  779. AST_RWLIST_UNLOCK(&logchannels);
  780. state = ast_true(a->argv[4]) ? 1 : 0;
  781. if (level != -1) {
  782. ast_console_toggle_loglevel(a->fd, level, state);
  783. ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
  784. } else
  785. return CLI_SHOWUSAGE;
  786. return CLI_SUCCESS;
  787. }
  788. /*! \brief CLI command to show logging system configuration */
  789. static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  790. {
  791. #define FORMATL "%-35.35s %-8.8s %-9.9s "
  792. struct logchannel *chan;
  793. switch (cmd) {
  794. case CLI_INIT:
  795. e->command = "logger show channels";
  796. e->usage =
  797. "Usage: logger show channels\n"
  798. " List configured logger channels.\n";
  799. return NULL;
  800. case CLI_GENERATE:
  801. return NULL;
  802. }
  803. ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
  804. ast_cli(a->fd, "Configuration\n");
  805. ast_cli(a->fd, FORMATL, "-------", "----", "------");
  806. ast_cli(a->fd, "-------------\n");
  807. AST_RWLIST_RDLOCK(&logchannels);
  808. AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
  809. unsigned int level;
  810. ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
  811. chan->disabled ? "Disabled" : "Enabled");
  812. ast_cli(a->fd, " - ");
  813. for (level = 0; level < ARRAY_LEN(levels); level++) {
  814. if ((chan->logmask & (1 << level)) && levels[level]) {
  815. ast_cli(a->fd, "%s ", levels[level]);
  816. }
  817. }
  818. ast_cli(a->fd, "\n");
  819. }
  820. AST_RWLIST_UNLOCK(&logchannels);
  821. ast_cli(a->fd, "\n");
  822. return CLI_SUCCESS;
  823. }
  824. struct verb {
  825. void (*verboser)(const char *string);
  826. AST_LIST_ENTRY(verb) list;
  827. };
  828. static AST_RWLIST_HEAD_STATIC(verbosers, verb);
  829. static struct ast_cli_entry cli_logger[] = {
  830. AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
  831. AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
  832. AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
  833. AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console"),
  834. };
  835. static void _handle_SIGXFSZ(int sig)
  836. {
  837. /* Indicate need to reload */
  838. filesize_reload_needed = 1;
  839. }
  840. static struct sigaction handle_SIGXFSZ = {
  841. .sa_handler = _handle_SIGXFSZ,
  842. .sa_flags = SA_RESTART,
  843. };
  844. static void ast_log_vsyslog(struct logmsg *msg)
  845. {
  846. char buf[BUFSIZ];
  847. int syslog_level = ast_syslog_priority_from_loglevel(msg->level);
  848. if (syslog_level < 0) {
  849. /* we are locked here, so cannot ast_log() */
  850. fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", msg->level);
  851. return;
  852. }
  853. snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
  854. levels[msg->level], msg->process_id, msg->file, msg->line, msg->function, msg->message);
  855. term_strip(buf, buf, strlen(buf) + 1);
  856. syslog(syslog_level, "%s", buf);
  857. }
  858. /*! \brief Print a normal log message to the channels */
  859. static void logger_print_normal(struct logmsg *logmsg)
  860. {
  861. struct logchannel *chan = NULL;
  862. char buf[BUFSIZ];
  863. struct verb *v = NULL;
  864. if (logmsg->level == __LOG_VERBOSE) {
  865. char *tmpmsg = ast_strdupa(logmsg->message + 1);
  866. /* Iterate through the list of verbosers and pass them the log message string */
  867. AST_RWLIST_RDLOCK(&verbosers);
  868. AST_RWLIST_TRAVERSE(&verbosers, v, list)
  869. v->verboser(logmsg->message);
  870. AST_RWLIST_UNLOCK(&verbosers);
  871. ast_string_field_set(logmsg, message, tmpmsg);
  872. }
  873. AST_RWLIST_RDLOCK(&logchannels);
  874. if (!AST_RWLIST_EMPTY(&logchannels)) {
  875. AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
  876. /* If the channel is disabled, then move on to the next one */
  877. if (chan->disabled)
  878. continue;
  879. /* Check syslog channels */
  880. if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
  881. ast_log_vsyslog(logmsg);
  882. /* Console channels */
  883. } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
  884. char linestr[128];
  885. char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
  886. /* If the level is verbose, then skip it */
  887. if (logmsg->level == __LOG_VERBOSE)
  888. continue;
  889. /* Turn the numerical line number into a string */
  890. snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
  891. /* Build string to print out */
  892. snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
  893. logmsg->date,
  894. term_color(tmp1, logmsg->level_name, colors[logmsg->level], 0, sizeof(tmp1)),
  895. logmsg->process_id,
  896. term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
  897. term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
  898. term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
  899. logmsg->message);
  900. /* Print out */
  901. ast_console_puts_mutable(buf, logmsg->level);
  902. /* File channels */
  903. } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
  904. int res = 0;
  905. /* If no file pointer exists, skip it */
  906. if (!chan->fileptr) {
  907. continue;
  908. }
  909. /* Print out to the file */
  910. res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
  911. logmsg->date, logmsg->level_name, logmsg->process_id, logmsg->file, term_strip(buf, logmsg->message, BUFSIZ));
  912. if (res <= 0 && !ast_strlen_zero(logmsg->message)) {
  913. fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
  914. if (errno == ENOMEM || errno == ENOSPC)
  915. fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
  916. else
  917. fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
  918. manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
  919. chan->disabled = 1;
  920. } else if (res > 0) {
  921. fflush(chan->fileptr);
  922. }
  923. }
  924. }
  925. } else if (logmsg->level != __LOG_VERBOSE) {
  926. fputs(logmsg->message, stdout);
  927. }
  928. AST_RWLIST_UNLOCK(&logchannels);
  929. /* If we need to reload because of the file size, then do so */
  930. if (filesize_reload_needed) {
  931. reload_logger(-1);
  932. ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
  933. }
  934. return;
  935. }
  936. /*! \brief Actual logging thread */
  937. static void *logger_thread(void *data)
  938. {
  939. struct logmsg *next = NULL, *msg = NULL;
  940. for (;;) {
  941. /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
  942. AST_LIST_LOCK(&logmsgs);
  943. if (AST_LIST_EMPTY(&logmsgs)) {
  944. if (close_logger_thread) {
  945. AST_LIST_UNLOCK(&logmsgs);
  946. break;
  947. } else {
  948. ast_cond_wait(&logcond, &logmsgs.lock);
  949. }
  950. }
  951. next = AST_LIST_FIRST(&logmsgs);
  952. AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
  953. AST_LIST_UNLOCK(&logmsgs);
  954. /* Otherwise go through and process each message in the order added */
  955. while ((msg = next)) {
  956. /* Get the next entry now so that we can free our current structure later */
  957. next = AST_LIST_NEXT(msg, list);
  958. /* Depending on the type, send it to the proper function */
  959. logger_print_normal(msg);
  960. /* Free the data since we are done */
  961. ast_free(msg);
  962. }
  963. }
  964. return NULL;
  965. }
  966. /*!
  967. * \internal
  968. * \brief Initialize the logger queue.
  969. *
  970. * \note Assumes logchannels is write locked on entry.
  971. *
  972. * \return Nothing
  973. */
  974. static void logger_queue_init(void)
  975. {
  976. ast_unload_realtime("queue_log");
  977. if (logfiles.queue_log) {
  978. char qfname[PATH_MAX];
  979. if (logger_queue_rt_start()) {
  980. return;
  981. }
  982. /* Open the log file. */
  983. snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR,
  984. queue_log_name);
  985. if (qlog) {
  986. /* Just in case it was already open. */
  987. fclose(qlog);
  988. }
  989. qlog = fopen(qfname, "a");
  990. if (!qlog) {
  991. ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
  992. }
  993. }
  994. }
  995. int init_logger(void)
  996. {
  997. /* auto rotate if sig SIGXFSZ comes a-knockin */
  998. sigaction(SIGXFSZ, &handle_SIGXFSZ, NULL);
  999. /* Re-initialize the logmsgs mutex. The recursive mutex can be accessed prior
  1000. * to Asterisk being forked into the background, which can cause the thread
  1001. * ID tracked by the underlying pthread mutex to be different than the ID of
  1002. * the thread that unlocks the mutex. Since init_logger is called after the
  1003. * fork, it is safe to initialize the mutex here for future accesses.
  1004. */
  1005. ast_mutex_destroy(&logmsgs.lock);
  1006. ast_mutex_init(&logmsgs.lock);
  1007. ast_cond_init(&logcond, NULL);
  1008. /* start logger thread */
  1009. if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
  1010. ast_cond_destroy(&logcond);
  1011. return -1;
  1012. }
  1013. /* register the logger cli commands */
  1014. ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
  1015. ast_mkdir(ast_config_AST_LOG_DIR, 0777);
  1016. /* create log channels */
  1017. init_logger_chain(0 /* locked */);
  1018. logger_initialized = 1;
  1019. return 0;
  1020. }
  1021. void close_logger(void)
  1022. {
  1023. struct logchannel *f = NULL;
  1024. struct verb *cur = NULL;
  1025. ast_cli_unregister_multiple(cli_logger, ARRAY_LEN(cli_logger));
  1026. logger_initialized = 0;
  1027. /* Stop logger thread */
  1028. AST_LIST_LOCK(&logmsgs);
  1029. close_logger_thread = 1;
  1030. ast_cond_signal(&logcond);
  1031. AST_LIST_UNLOCK(&logmsgs);
  1032. if (logthread != AST_PTHREADT_NULL)
  1033. pthread_join(logthread, NULL);
  1034. AST_RWLIST_WRLOCK(&verbosers);
  1035. while ((cur = AST_LIST_REMOVE_HEAD(&verbosers, list))) {
  1036. ast_free(cur);
  1037. }
  1038. AST_RWLIST_UNLOCK(&verbosers);
  1039. AST_RWLIST_WRLOCK(&logchannels);
  1040. if (qlog) {
  1041. fclose(qlog);
  1042. qlog = NULL;
  1043. }
  1044. while ((f = AST_LIST_REMOVE_HEAD(&logchannels, list))) {
  1045. if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
  1046. fclose(f->fileptr);
  1047. f->fileptr = NULL;
  1048. }
  1049. ast_free(f);
  1050. }
  1051. closelog(); /* syslog */
  1052. AST_RWLIST_UNLOCK(&logchannels);
  1053. }
  1054. /*!
  1055. * \brief send log messages to syslog and/or the console
  1056. */
  1057. void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
  1058. {
  1059. struct logmsg *logmsg = NULL;
  1060. struct ast_str *buf = NULL;
  1061. struct ast_tm tm;
  1062. struct timeval now = ast_tvnow();
  1063. int res = 0;
  1064. va_list ap;
  1065. char datestring[256];
  1066. if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
  1067. return;
  1068. if (level != __LOG_VERBOSE && AST_RWLIST_EMPTY(&logchannels)) {
  1069. /*
  1070. * we don't have the logger chain configured yet,
  1071. * so just log to stdout
  1072. */
  1073. int result;
  1074. va_start(ap, fmt);
  1075. result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
  1076. va_end(ap);
  1077. if (result != AST_DYNSTR_BUILD_FAILED) {
  1078. term_filter_escapes(ast_str_buffer(buf));
  1079. fputs(ast_str_buffer(buf), stdout);
  1080. }
  1081. return;
  1082. }
  1083. /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
  1084. are non-zero; LOG_DEBUG messages can still be displayed if option_debug
  1085. is zero, if option_verbose is non-zero (this allows for 'level zero'
  1086. LOG_DEBUG messages to be displayed, if the logmask on any channel
  1087. allows it)
  1088. */
  1089. if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
  1090. return;
  1091. /* Ignore anything that never gets logged anywhere */
  1092. if (level != __LOG_VERBOSE && !(global_logmask & (1 << level)))
  1093. return;
  1094. /* Build string */
  1095. va_start(ap, fmt);
  1096. res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
  1097. va_end(ap);
  1098. /* If the build failed, then abort and free this structure */
  1099. if (res == AST_DYNSTR_BUILD_FAILED)
  1100. return;
  1101. /* Create a new logging message */
  1102. if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
  1103. return;
  1104. /* Copy string over */
  1105. ast_string_field_set(logmsg, message, ast_str_buffer(buf));
  1106. /* Set type */
  1107. if (level == __LOG_VERBOSE) {
  1108. logmsg->type = LOGMSG_VERBOSE;
  1109. } else {
  1110. logmsg->type = LOGMSG_NORMAL;
  1111. }
  1112. /* Create our date/time */
  1113. ast_localtime(&now, &tm, NULL);
  1114. ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
  1115. ast_string_field_set(logmsg, date, datestring);
  1116. /* Copy over data */
  1117. logmsg->level = level;
  1118. logmsg->line = line;
  1119. ast_string_field_set(logmsg, level_name, levels[level]);
  1120. ast_string_field_set(logmsg, file, file);
  1121. ast_string_field_set(logmsg, function, function);
  1122. logmsg->process_id = (long) ast_get_tid();
  1123. /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
  1124. if (logthread != AST_PTHREADT_NULL) {
  1125. AST_LIST_LOCK(&logmsgs);
  1126. if (close_logger_thread) {
  1127. /* Logger is either closing or closed. We cannot log this message. */
  1128. ast_free(logmsg);
  1129. } else {
  1130. AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
  1131. ast_cond_signal(&logcond);
  1132. }
  1133. AST_LIST_UNLOCK(&logmsgs);
  1134. } else {
  1135. logger_print_normal(logmsg);
  1136. ast_free(logmsg);
  1137. }
  1138. }
  1139. #ifdef HAVE_BKTR
  1140. struct ast_bt *ast_bt_create(void)
  1141. {
  1142. struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
  1143. if (!bt) {
  1144. ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
  1145. return NULL;
  1146. }
  1147. bt->alloced = 1;
  1148. ast_bt_get_addresses(bt);
  1149. return bt;
  1150. }
  1151. int ast_bt_get_addresses(struct ast_bt *bt)
  1152. {
  1153. bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
  1154. return 0;
  1155. }
  1156. void *ast_bt_destroy(struct ast_bt *bt)
  1157. {
  1158. if (bt->alloced) {
  1159. ast_free(bt);
  1160. }
  1161. return NULL;
  1162. }
  1163. char **ast_bt_get_symbols(void **addresses, size_t num_frames)
  1164. {
  1165. char **strings;
  1166. #if defined(BETTER_BACKTRACES)
  1167. int stackfr;
  1168. bfd *bfdobj; /* bfd.h */
  1169. Dl_info dli; /* dlfcn.h */
  1170. long allocsize;
  1171. asymbol **syms = NULL; /* bfd.h */
  1172. bfd_vma offset; /* bfd.h */
  1173. const char *lastslash;
  1174. asection *section;
  1175. const char *file, *func;
  1176. unsigned int line;
  1177. char address_str[128];
  1178. char msg[1024];
  1179. size_t strings_size;
  1180. size_t *eachlen;
  1181. #endif
  1182. #if defined(BETTER_BACKTRACES)
  1183. strings_size = num_frames * sizeof(*strings);
  1184. eachlen = ast_calloc(num_frames, sizeof(*eachlen));
  1185. strings = ast_std_calloc(num_frames, sizeof(*strings));
  1186. if (!eachlen || !strings) {
  1187. ast_free(eachlen);
  1188. ast_std_free(strings);
  1189. return NULL;
  1190. }
  1191. for (stackfr = 0; stackfr < num_frames; stackfr++) {
  1192. int found = 0, symbolcount;
  1193. msg[0] = '\0';
  1194. if (!dladdr(addresses[stackfr], &dli)) {
  1195. continue;
  1196. }
  1197. if (strcmp(dli.dli_fname, "asterisk") == 0) {
  1198. char asteriskpath[256];
  1199. if (!(dli.dli_fname = ast_utils_which("asterisk", asteriskpath, sizeof(asteriskpath)))) {
  1200. /* This will fail to find symbols */
  1201. ast_log(LOG_DEBUG, "Failed to find asterisk binary for debug symbols.\n");
  1202. dli.dli_fname = "asterisk";
  1203. }
  1204. }
  1205. lastslash = strrchr(dli.dli_fname, '/');
  1206. if ((bfdobj = bfd_openr(dli.dli_fname, NULL)) &&
  1207. bfd_check_format(bfdobj, bfd_object) &&
  1208. (allocsize = bfd_get_symtab_upper_bound(bfdobj)) > 0 &&
  1209. (syms = ast_malloc(allocsize)) &&
  1210. (symbolcount = bfd_canonicalize_symtab(bfdobj, syms))) {
  1211. if (bfdobj->flags & DYNAMIC) {
  1212. offset = addresses[stackfr] - dli.dli_fbase;
  1213. } else {
  1214. offset = addresses[stackfr] - (void *) 0;
  1215. }
  1216. for (section = bfdobj->sections; section; section = section->next) {
  1217. if (!bfd_get_section_flags(bfdobj, section) & SEC_ALLOC ||
  1218. section->vma > offset ||
  1219. section->size + section->vma < offset) {
  1220. continue;
  1221. }
  1222. if (!bfd_find_nearest_line(bfdobj, section, syms, offset - section->vma, &file, &func, &line)) {
  1223. continue;
  1224. }
  1225. /* file can possibly be null even with a success result from bfd_find_nearest_line */
  1226. file = file ? file : "";
  1227. /* Stack trace output */
  1228. found++;
  1229. if ((lastslash = strrchr(file, '/'))) {
  1230. const char *prevslash;
  1231. for (prevslash = lastslash - 1; *prevslash != '/' && prevslash >= file; prevslash--) {
  1232. }
  1233. if (prevslash >= file) {
  1234. lastslash = prevslash;
  1235. }
  1236. }
  1237. if (dli.dli_saddr == NULL) {
  1238. address_str[0] = '\0';
  1239. } else {
  1240. snprintf(address_str, sizeof(address_str), " (%p+%lX)",
  1241. dli.dli_saddr,
  1242. (unsigned long) (addresses[stackfr] - dli.dli_saddr));
  1243. }
  1244. snprintf(msg, sizeof(msg), "%s:%u %s()%s",
  1245. lastslash ? lastslash + 1 : file, line,
  1246. S_OR(func, "???"),
  1247. address_str);
  1248. break; /* out of section iteration */
  1249. }
  1250. }
  1251. if (bfdobj) {
  1252. bfd_close(bfdobj);
  1253. ast_free(syms);
  1254. }
  1255. /* Default output, if we cannot find the information within BFD */
  1256. if (!found) {
  1257. if (dli.dli_saddr == NULL) {
  1258. address_str[0] = '\0';
  1259. } else {
  1260. snprintf(address_str, sizeof(address_str), " (%p+%lX)",
  1261. dli.dli_saddr,
  1262. (unsigned long) (addresses[stackfr] - dli.dli_saddr));
  1263. }
  1264. snprintf(msg, sizeof(msg), "%s %s()%s",
  1265. lastslash ? lastslash + 1 : dli.dli_fname,
  1266. S_OR(dli.dli_sname, "<unknown>"),
  1267. address_str);
  1268. }
  1269. if (!ast_strlen_zero(msg)) {
  1270. char **tmp;
  1271. eachlen[stackfr] = strlen(msg) + 1;
  1272. if (!(tmp = ast_std_realloc(strings, strings_size + eachlen[stackfr]))) {
  1273. ast_std_free(strings);
  1274. strings = NULL;
  1275. break; /* out of stack frame iteration */
  1276. }
  1277. strings = tmp;
  1278. strings[stackfr] = (char *) strings + strings_size;
  1279. strcpy(strings[stackfr], msg);/* Safe since we just allocated the room. */
  1280. strings_size += eachlen[stackfr];
  1281. }
  1282. }
  1283. if (strings) {
  1284. /* Recalculate the offset pointers because of the reallocs. */
  1285. strings[0] = (char *) strings + num_frames * sizeof(*strings);
  1286. for (stackfr = 1; stackfr < num_frames; stackfr++) {
  1287. strings[stackfr] = strings[stackfr - 1] + eachlen[stackfr - 1];
  1288. }
  1289. }
  1290. ast_free(eachlen);
  1291. #else /* !defined(BETTER_BACKTRACES) */
  1292. strings = backtrace_symbols(addresses, num_frames);
  1293. #endif /* defined(BETTER_BACKTRACES) */
  1294. return strings;
  1295. }
  1296. #endif /* HAVE_BKTR */
  1297. void ast_backtrace(void)
  1298. {
  1299. #ifdef HAVE_BKTR
  1300. struct ast_bt *bt;
  1301. int i = 0;
  1302. char **strings;
  1303. if (!(bt = ast_bt_create())) {
  1304. ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
  1305. return;
  1306. }
  1307. if ((strings = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
  1308. ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
  1309. for (i = 3; i < bt->num_frames - 2; i++) {
  1310. ast_log(LOG_DEBUG, "#%d: [%p] %s\n", i - 3, bt->addresses[i], strings[i]);
  1311. }
  1312. ast_std_free(strings);
  1313. } else {
  1314. ast_debug(1, "Could not allocate memory for backtrace\n");
  1315. }
  1316. ast_bt_destroy(bt);
  1317. #else
  1318. ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
  1319. #endif /* defined(HAVE_BKTR) */
  1320. }
  1321. void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
  1322. {
  1323. struct ast_str *buf = NULL;
  1324. int res = 0;
  1325. if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
  1326. return;
  1327. if (ast_opt_timestamp) {
  1328. struct timeval now;
  1329. struct ast_tm tm;
  1330. char date[40];
  1331. char *datefmt;
  1332. now = ast_tvnow();
  1333. ast_localtime(&now, &tm, NULL);
  1334. ast_strftime(date, sizeof(date), dateformat, &tm);
  1335. datefmt = ast_alloca(strlen(date) + 3 + strlen(fmt) + 1);
  1336. sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
  1337. fmt = datefmt;
  1338. } else {
  1339. char *tmp = ast_alloca(strlen(fmt) + 2);
  1340. sprintf(tmp, "%c%s", 127, fmt);
  1341. fmt = tmp;
  1342. }
  1343. /* Build string */
  1344. res = ast_str_set_va(&buf, 0, fmt, ap);
  1345. /* If the build failed then we can drop this allocated message */
  1346. if (res == AST_DYNSTR_BUILD_FAILED)
  1347. return;
  1348. ast_log(__LOG_VERBOSE, file, line, func, "%s", ast_str_buffer(buf));
  1349. }
  1350. void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
  1351. {
  1352. va_list ap;
  1353. va_start(ap, fmt);
  1354. __ast_verbose_ap(file, line, func, fmt, ap);
  1355. va_end(ap);
  1356. }
  1357. /* No new code should use this directly, but we have the ABI for backwards compat */
  1358. #undef ast_verbose
  1359. void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
  1360. void ast_verbose(const char *fmt, ...)
  1361. {
  1362. va_list ap;
  1363. va_start(ap, fmt);
  1364. __ast_verbose_ap("", 0, "", fmt, ap);
  1365. va_end(ap);
  1366. }
  1367. int ast_register_verbose(void (*v)(const char *string))
  1368. {
  1369. struct verb *verb;
  1370. if (!(verb = ast_malloc(sizeof(*verb))))
  1371. return -1;
  1372. verb->verboser = v;
  1373. AST_RWLIST_WRLOCK(&verbosers);
  1374. AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
  1375. AST_RWLIST_UNLOCK(&verbosers);
  1376. return 0;
  1377. }
  1378. int ast_unregister_verbose(void (*v)(const char *string))
  1379. {
  1380. struct verb *cur;
  1381. AST_RWLIST_WRLOCK(&verbosers);
  1382. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
  1383. if (cur->verboser == v) {
  1384. AST_RWLIST_REMOVE_CURRENT(list);
  1385. ast_free(cur);
  1386. break;
  1387. }
  1388. }
  1389. AST_RWLIST_TRAVERSE_SAFE_END;
  1390. AST_RWLIST_UNLOCK(&verbosers);
  1391. return cur ? 0 : -1;
  1392. }
  1393. static void update_logchannels(void)
  1394. {
  1395. struct logchannel *cur;
  1396. AST_RWLIST_WRLOCK(&logchannels);
  1397. global_logmask = 0;
  1398. AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
  1399. cur->logmask = make_components(cur->components, cur->lineno);
  1400. global_logmask |= cur->logmask;
  1401. }
  1402. AST_RWLIST_UNLOCK(&logchannels);
  1403. }
  1404. int ast_logger_register_level(const char *name)
  1405. {
  1406. unsigned int level;
  1407. unsigned int available = 0;
  1408. AST_RWLIST_WRLOCK(&logchannels);
  1409. for (level = 0; level < ARRAY_LEN(levels); level++) {
  1410. if ((level >= 16) && !available && !levels[level]) {
  1411. available = level;
  1412. continue;
  1413. }
  1414. if (levels[level] && !strcasecmp(levels[level], name)) {
  1415. ast_log(LOG_WARNING,
  1416. "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
  1417. name);
  1418. AST_RWLIST_UNLOCK(&logchannels);
  1419. return -1;
  1420. }
  1421. }
  1422. if (!available) {
  1423. ast_log(LOG_WARNING,
  1424. "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
  1425. name);
  1426. AST_RWLIST_UNLOCK(&logchannels);
  1427. return -1;
  1428. }
  1429. levels[available] = ast_strdup(name);
  1430. AST_RWLIST_UNLOCK(&logchannels);
  1431. ast_debug(1, "Registered dynamic logger level '%s' with index %u.\n", name, available);
  1432. update_logchannels();
  1433. return available;
  1434. }
  1435. void ast_logger_unregister_level(const char *name)
  1436. {
  1437. unsigned int found = 0;
  1438. unsigned int x;
  1439. AST_RWLIST_WRLOCK(&logchannels);
  1440. for (x = 16; x < ARRAY_LEN(levels); x++) {
  1441. if (!levels[x]) {
  1442. continue;
  1443. }
  1444. if (strcasecmp(levels[x], name)) {
  1445. continue;
  1446. }
  1447. found = 1;
  1448. break;
  1449. }
  1450. if (found) {
  1451. /* take this level out of the global_logmask, to ensure that no new log messages
  1452. * will be queued for it
  1453. */
  1454. global_logmask &= ~(1 << x);
  1455. ast_free(levels[x]);
  1456. levels[x] = NULL;
  1457. AST_RWLIST_UNLOCK(&logchannels);
  1458. ast_debug(1, "Unregistered dynamic logger level '%s' with index %u.\n", name, x);
  1459. update_logchannels();
  1460. } else {
  1461. AST_RWLIST_UNLOCK(&logchannels);
  1462. }
  1463. }