logging.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /*
  2. * Session logging.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <ctype.h>
  7. #include <time.h>
  8. #include <assert.h>
  9. #include "putty.h"
  10. /* log session to file stuff ... */
  11. struct LogContext {
  12. FILE *lgfp;
  13. enum { L_CLOSED, L_OPENING, L_OPEN, L_ERROR } state;
  14. bufchain queue;
  15. Filename *currlogfilename;
  16. LogPolicy *lp;
  17. Conf *conf;
  18. int logtype; /* cached out of conf */
  19. };
  20. static Filename *xlatlognam(Filename *s, char *hostname, int port,
  21. struct tm *tm);
  22. /*
  23. * Internal wrapper function which must be called for _all_ output
  24. * to the log file. It takes care of opening the log file if it
  25. * isn't open, buffering data if it's in the process of being
  26. * opened asynchronously, etc.
  27. */
  28. static void logwrite(LogContext *ctx, ptrlen data)
  29. {
  30. /*
  31. * In state L_CLOSED, we call logfopen, which will set the state
  32. * to one of L_OPENING, L_OPEN or L_ERROR. Hence we process all of
  33. * those three _after_ processing L_CLOSED.
  34. */
  35. if (ctx->state == L_CLOSED)
  36. logfopen(ctx);
  37. if (ctx->state == L_OPENING) {
  38. bufchain_add(&ctx->queue, data.ptr, data.len);
  39. } else if (ctx->state == L_OPEN) {
  40. assert(ctx->lgfp);
  41. if (fwrite(data.ptr, 1, data.len, ctx->lgfp) < data.len) {
  42. logfclose(ctx);
  43. ctx->state = L_ERROR;
  44. lp_eventlog(ctx->lp, "Disabled writing session log "
  45. "due to error while writing");
  46. }
  47. } /* else L_ERROR, so ignore the write */
  48. }
  49. /*
  50. * Convenience wrapper on logwrite() which printf-formats the
  51. * string.
  52. */
  53. static PRINTF_LIKE(2, 3) void logprintf(LogContext *ctx, const char *fmt, ...)
  54. {
  55. va_list ap;
  56. char *data;
  57. va_start(ap, fmt);
  58. data = dupvprintf(fmt, ap);
  59. va_end(ap);
  60. logwrite(ctx, ptrlen_from_asciz(data));
  61. sfree(data);
  62. }
  63. /*
  64. * Flush any open log file.
  65. */
  66. void logflush(LogContext *ctx)
  67. {
  68. if (ctx->logtype > 0)
  69. if (ctx->state == L_OPEN)
  70. fflush(ctx->lgfp);
  71. }
  72. LogPolicy *log_get_policy(LogContext *ctx)
  73. {
  74. return ctx->lp;
  75. }
  76. static void logfopen_callback(void *vctx, int mode)
  77. {
  78. LogContext *ctx = (LogContext *)vctx;
  79. char buf[256], *event;
  80. struct tm tm;
  81. const char *fmode;
  82. bool shout = false;
  83. if (mode == 0) {
  84. ctx->state = L_ERROR; /* disable logging */
  85. } else {
  86. fmode = (mode == 1 ? "ab" : "wb");
  87. ctx->lgfp = f_open(ctx->currlogfilename, fmode, false);
  88. if (ctx->lgfp) {
  89. ctx->state = L_OPEN;
  90. } else {
  91. ctx->state = L_ERROR;
  92. shout = true;
  93. }
  94. }
  95. if (ctx->state == L_OPEN && conf_get_bool(ctx->conf, CONF_logheader)) {
  96. /* Write header line into log file. */
  97. tm = ltime();
  98. strftime(buf, 24, "%Y.%m.%d %H:%M:%S", &tm);
  99. logprintf(ctx, "=~=~=~=~=~=~=~=~=~=~=~= PuTTY log %s"
  100. " =~=~=~=~=~=~=~=~=~=~=~=\r\n", buf);
  101. }
  102. event = dupprintf("%s session log (%s mode) to file: %s",
  103. ctx->state == L_ERROR ?
  104. (mode == 0 ? "Disabled writing" : "Error writing") :
  105. (mode == 1 ? "Appending" : "Writing new"),
  106. (ctx->logtype == LGTYP_ASCII ? "ASCII" :
  107. ctx->logtype == LGTYP_DEBUG ? "raw" :
  108. ctx->logtype == LGTYP_PACKETS ? "SSH packets" :
  109. ctx->logtype == LGTYP_SSHRAW ? "SSH raw data" :
  110. "unknown"),
  111. filename_to_str(ctx->currlogfilename));
  112. lp_eventlog(ctx->lp, event);
  113. if (shout) {
  114. /*
  115. * If we failed to open the log file due to filesystem error
  116. * (as opposed to user action such as clicking Cancel in the
  117. * askappend box), we should log it more prominently.
  118. */
  119. lp_logging_error(ctx->lp, event);
  120. }
  121. sfree(event);
  122. /*
  123. * Having either succeeded or failed in opening the log file,
  124. * we should write any queued data out.
  125. */
  126. assert(ctx->state != L_OPENING); /* make _sure_ it won't be requeued */
  127. while (bufchain_size(&ctx->queue)) {
  128. ptrlen data = bufchain_prefix(&ctx->queue);
  129. logwrite(ctx, data);
  130. bufchain_consume(&ctx->queue, data.len);
  131. }
  132. logflush(ctx);
  133. }
  134. /*
  135. * Open the log file. Takes care of detecting an already-existing
  136. * file and asking the user whether they want to append, overwrite
  137. * or cancel logging.
  138. */
  139. void logfopen(LogContext *ctx)
  140. {
  141. struct tm tm;
  142. int mode;
  143. /* Prevent repeat calls */
  144. if (ctx->state != L_CLOSED)
  145. return;
  146. if (!ctx->logtype)
  147. return;
  148. tm = ltime();
  149. /* substitute special codes in file name */
  150. if (ctx->currlogfilename)
  151. filename_free(ctx->currlogfilename);
  152. ctx->currlogfilename =
  153. xlatlognam(conf_get_filename(ctx->conf, CONF_logfilename),
  154. conf_get_str(ctx->conf, CONF_host),
  155. conf_get_int(ctx->conf, CONF_port), &tm);
  156. if (open_for_write_would_lose_data(ctx->currlogfilename)) {
  157. int logxfovr = conf_get_int(ctx->conf, CONF_logxfovr);
  158. if (logxfovr != LGXF_ASK) {
  159. mode = ((logxfovr == LGXF_OVR) ? 2 : 1);
  160. } else
  161. mode = lp_askappend(ctx->lp, ctx->currlogfilename,
  162. logfopen_callback, ctx);
  163. } else
  164. mode = 2; /* create == overwrite */
  165. if (mode < 0)
  166. ctx->state = L_OPENING;
  167. else
  168. logfopen_callback(ctx, mode); /* open the file */
  169. }
  170. void logfclose(LogContext *ctx)
  171. {
  172. if (ctx->lgfp) {
  173. fclose(ctx->lgfp);
  174. ctx->lgfp = NULL;
  175. }
  176. ctx->state = L_CLOSED;
  177. }
  178. /*
  179. * Log session traffic.
  180. */
  181. void logtraffic(LogContext *ctx, unsigned char c, int logmode)
  182. {
  183. if (ctx->logtype > 0) {
  184. if (ctx->logtype == logmode)
  185. logwrite(ctx, make_ptrlen(&c, 1));
  186. }
  187. }
  188. static void logevent_internal(LogContext *ctx, const char *event)
  189. {
  190. if (ctx->logtype == LGTYP_PACKETS || ctx->logtype == LGTYP_SSHRAW) {
  191. logprintf(ctx, "Event Log: %s\r\n", event);
  192. logflush(ctx);
  193. }
  194. lp_eventlog(ctx->lp, event);
  195. }
  196. void logevent(LogContext *ctx, const char *event)
  197. {
  198. if (!ctx)
  199. return;
  200. /*
  201. * Replace newlines in Event Log messages with spaces. (Sometimes
  202. * the same message string is reused for the Event Log and a GUI
  203. * dialog box; newlines are sometimes appropriate in the latter,
  204. * but never in the former.)
  205. */
  206. if (strchr(event, '\n') || strchr(event, '\r')) {
  207. char *dup = dupstr(event);
  208. char *p = dup, *q = dup;
  209. while (*p) {
  210. if (*p == '\r' || *p == '\n') {
  211. do {
  212. p++;
  213. } while (*p == '\r' || *p == '\n');
  214. *q++ = ' ';
  215. } else {
  216. *q++ = *p++;
  217. }
  218. }
  219. *q = '\0';
  220. logevent_internal(ctx, dup);
  221. sfree(dup);
  222. } else {
  223. logevent_internal(ctx, event);
  224. }
  225. }
  226. void logevent_and_free(LogContext *ctx, char *event)
  227. {
  228. logevent(ctx, event);
  229. sfree(event);
  230. }
  231. void logeventvf(LogContext *ctx, const char *fmt, va_list ap)
  232. {
  233. logevent_and_free(ctx, dupvprintf(fmt, ap));
  234. }
  235. void logeventf(LogContext *ctx, const char *fmt, ...)
  236. {
  237. va_list ap;
  238. va_start(ap, fmt);
  239. logeventvf(ctx, fmt, ap);
  240. va_end(ap);
  241. }
  242. /*
  243. * Log an SSH packet.
  244. * If n_blanks != 0, blank or omit some parts.
  245. * Set of blanking areas must be in increasing order.
  246. */
  247. void log_packet(LogContext *ctx, int direction, int type,
  248. const char *texttype, const void *data, size_t len,
  249. int n_blanks, const struct logblank_t *blanks,
  250. const unsigned long *seq,
  251. unsigned downstream_id, const char *additional_log_text)
  252. {
  253. char dumpdata[128], smalldata[5];
  254. size_t p = 0, b = 0, omitted = 0;
  255. int output_pos = 0; /* NZ if pending output in dumpdata */
  256. if (!(ctx->logtype == LGTYP_SSHRAW ||
  257. (ctx->logtype == LGTYP_PACKETS && texttype)))
  258. return;
  259. /* Packet header. */
  260. if (texttype) {
  261. logprintf(ctx, "%s packet ",
  262. direction == PKT_INCOMING ? "Incoming" : "Outgoing");
  263. if (seq)
  264. logprintf(ctx, "#0x%lx, ", *seq);
  265. logprintf(ctx, "type %d / 0x%02x (%s)", type, type, texttype);
  266. if (downstream_id) {
  267. logprintf(ctx, " on behalf of downstream #%u", downstream_id);
  268. if (additional_log_text)
  269. logprintf(ctx, " (%s)", additional_log_text);
  270. }
  271. logprintf(ctx, "\r\n");
  272. } else {
  273. /*
  274. * Raw data is logged with a timestamp, so that it's possible
  275. * to determine whether a mysterious delay occurred at the
  276. * client or server end. (Timestamping the raw data avoids
  277. * cluttering the normal case of only logging decrypted SSH
  278. * messages, and also adds conceptual rigour in the case where
  279. * an SSH message arrives in several pieces.)
  280. */
  281. char buf[256];
  282. struct tm tm;
  283. tm = ltime();
  284. strftime(buf, 24, "%Y-%m-%d %H:%M:%S", &tm);
  285. logprintf(ctx, "%s raw data at %s\r\n",
  286. direction == PKT_INCOMING ? "Incoming" : "Outgoing",
  287. buf);
  288. }
  289. /*
  290. * Output a hex/ASCII dump of the packet body, blanking/omitting
  291. * parts as specified.
  292. */
  293. while (p < len) {
  294. int blktype;
  295. /* Move to a current entry in the blanking array. */
  296. while ((b < n_blanks) &&
  297. (p >= blanks[b].offset + blanks[b].len))
  298. b++;
  299. /* Work out what type of blanking to apply to
  300. * this byte. */
  301. blktype = PKTLOG_EMIT; /* default */
  302. if ((b < n_blanks) &&
  303. (p >= blanks[b].offset) &&
  304. (p < blanks[b].offset + blanks[b].len))
  305. blktype = blanks[b].type;
  306. /* If we're about to stop omitting, it's time to say how
  307. * much we omitted. */
  308. if ((blktype != PKTLOG_OMIT) && omitted) {
  309. logprintf(ctx, " (%"SIZEu" byte%s omitted)\r\n",
  310. omitted, (omitted==1?"":"s"));
  311. omitted = 0;
  312. }
  313. /* (Re-)initialise dumpdata as necessary
  314. * (start of row, or if we've just stopped omitting) */
  315. if (!output_pos && !omitted)
  316. sprintf(dumpdata, " %08"SIZEx"%*s\r\n",
  317. p-(p%16), 1+3*16+2+16, "");
  318. /* Deal with the current byte. */
  319. if (blktype == PKTLOG_OMIT) {
  320. omitted++;
  321. } else {
  322. int c;
  323. if (blktype == PKTLOG_BLANK) {
  324. c = 'X';
  325. sprintf(smalldata, "XX");
  326. } else { /* PKTLOG_EMIT */
  327. c = ((const unsigned char *)data)[p];
  328. sprintf(smalldata, "%02x", c);
  329. }
  330. dumpdata[10+2+3*(p%16)] = smalldata[0];
  331. dumpdata[10+2+3*(p%16)+1] = smalldata[1];
  332. dumpdata[10+1+3*16+2+(p%16)] = (c >= 0x20 && c < 0x7F ? c : '.');
  333. output_pos = (p%16) + 1;
  334. }
  335. p++;
  336. /* Flush row if necessary */
  337. if (((p % 16) == 0) || (p == len) || omitted) {
  338. if (output_pos) {
  339. strcpy(dumpdata + 10+1+3*16+2+output_pos, "\r\n");
  340. logwrite(ctx, ptrlen_from_asciz(dumpdata));
  341. output_pos = 0;
  342. }
  343. }
  344. }
  345. /* Tidy up */
  346. if (omitted)
  347. logprintf(ctx, " (%"SIZEu" byte%s omitted)\r\n",
  348. omitted, (omitted==1?"":"s"));
  349. logflush(ctx);
  350. }
  351. LogContext *log_init(LogPolicy *lp, Conf *conf)
  352. {
  353. LogContext *ctx = snew(LogContext);
  354. ctx->lgfp = NULL;
  355. ctx->state = L_CLOSED;
  356. ctx->lp = lp;
  357. ctx->conf = conf_copy(conf);
  358. ctx->logtype = conf_get_int(ctx->conf, CONF_logtype);
  359. ctx->currlogfilename = NULL;
  360. bufchain_init(&ctx->queue);
  361. return ctx;
  362. }
  363. void log_free(LogContext *ctx)
  364. {
  365. logfclose(ctx);
  366. bufchain_clear(&ctx->queue);
  367. if (ctx->currlogfilename)
  368. filename_free(ctx->currlogfilename);
  369. conf_free(ctx->conf);
  370. sfree(ctx);
  371. }
  372. void log_reconfig(LogContext *ctx, Conf *conf)
  373. {
  374. bool reset_logging;
  375. if (!filename_equal(conf_get_filename(ctx->conf, CONF_logfilename),
  376. conf_get_filename(conf, CONF_logfilename)) ||
  377. conf_get_int(ctx->conf, CONF_logtype) !=
  378. conf_get_int(conf, CONF_logtype))
  379. reset_logging = true;
  380. else
  381. reset_logging = false;
  382. if (reset_logging)
  383. logfclose(ctx);
  384. conf_free(ctx->conf);
  385. ctx->conf = conf_copy(conf);
  386. ctx->logtype = conf_get_int(ctx->conf, CONF_logtype);
  387. if (reset_logging)
  388. logfopen(ctx);
  389. }
  390. /*
  391. * translate format codes into time/date strings
  392. * and insert them into log file name
  393. *
  394. * "&Y":YYYY "&m":MM "&d":DD "&T":hhmmss "&h":<hostname> "&&":&
  395. */
  396. static Filename *xlatlognam(Filename *src, char *hostname, int port,
  397. struct tm *tm)
  398. {
  399. char buf[32], *bufp;
  400. int size;
  401. strbuf *buffer;
  402. const char *s;
  403. Filename *ret;
  404. buffer = strbuf_new();
  405. s = filename_to_str(src);
  406. while (*s) {
  407. bool sanitise = false;
  408. /* Let (bufp, len) be the string to append. */
  409. bufp = buf; /* don't usually override this */
  410. if (*s == '&') {
  411. char c;
  412. s++;
  413. size = 0;
  414. if (*s) switch (c = *s++, tolower((unsigned char)c)) {
  415. case 'y':
  416. size = strftime(buf, sizeof(buf), "%Y", tm);
  417. break;
  418. case 'm':
  419. size = strftime(buf, sizeof(buf), "%m", tm);
  420. break;
  421. case 'd':
  422. size = strftime(buf, sizeof(buf), "%d", tm);
  423. break;
  424. case 't':
  425. size = strftime(buf, sizeof(buf), "%H%M%S", tm);
  426. break;
  427. case 'h':
  428. bufp = hostname;
  429. size = strlen(bufp);
  430. break;
  431. case 'p':
  432. size = sprintf(buf, "%d", port);
  433. break;
  434. default:
  435. buf[0] = '&';
  436. size = 1;
  437. if (c != '&')
  438. buf[size++] = c;
  439. }
  440. /* Never allow path separators - or any other illegal
  441. * filename character - to come out of any of these
  442. * auto-format directives. E.g. 'hostname' can contain
  443. * colons, if it's an IPv6 address, and colons aren't
  444. * legal in filenames on Windows. */
  445. sanitise = true;
  446. } else {
  447. buf[0] = *s++;
  448. size = 1;
  449. }
  450. while (size-- > 0) {
  451. char c = *bufp++;
  452. if (sanitise)
  453. c = filename_char_sanitise(c);
  454. put_byte(buffer, c);
  455. }
  456. }
  457. ret = filename_from_str(buffer->s);
  458. strbuf_free(buffer);
  459. return ret;
  460. }