logging.c 13 KB

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