logging.c 15 KB

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