1
0

logging.c 14 KB

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