logging.c 15 KB

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