]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - logging.c
Sprinkle some header comments in various files in an attempt to explain what
[PuTTY.git] / logging.c
1 /*
2  * Session logging.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <ctype.h>
8
9 #include <time.h>
10 #include <assert.h>
11
12 #include "putty.h"
13
14 /* log session to file stuff ... */
15 struct LogContext {
16     FILE *lgfp;
17     enum { L_CLOSED, L_OPENING, L_OPEN, L_ERROR } state;
18     bufchain queue;
19     Filename currlogfilename;
20     void *frontend;
21     Config cfg;
22 };
23
24 static void xlatlognam(Filename *d, Filename s, char *hostname, struct tm *tm);
25
26 /*
27  * Internal wrapper function which must be called for _all_ output
28  * to the log file. It takes care of opening the log file if it
29  * isn't open, buffering data if it's in the process of being
30  * opened asynchronously, etc.
31  */
32 static void logwrite(struct LogContext *ctx, void *data, int len)
33 {
34     /*
35      * In state L_CLOSED, we call logfopen, which will set the state
36      * to one of L_OPENING, L_OPEN or L_ERROR. Hence we process all of
37      * those three _after_ processing L_CLOSED.
38      */
39     if (ctx->state == L_CLOSED)
40         logfopen(ctx);
41
42     if (ctx->state == L_OPENING) {
43         bufchain_add(&ctx->queue, data, len);
44     } else if (ctx->state == L_OPEN) {
45         assert(ctx->lgfp);
46         fwrite(data, 1, len, ctx->lgfp);
47     }                                  /* else L_ERROR, so ignore the write */
48 }
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
59     va_start(ap, fmt);
60     data = dupvprintf(fmt, ap);
61     va_end(ap);
62
63     logwrite(ctx, data, strlen(data));
64     sfree(data);
65 }
66
67 /*
68  * Flush any open log file.
69  */
70 void logflush(void *handle) {
71     struct LogContext *ctx = (struct LogContext *)handle;
72     if (ctx->cfg.logtype > 0)
73         if (ctx->state == L_OPEN)
74             fflush(ctx->lgfp);
75 }
76
77 static void logfopen_callback(void *handle, int mode)
78 {
79     struct LogContext *ctx = (struct LogContext *)handle;
80     char buf[256], *event;
81     struct tm tm;
82     const char *fmode;
83
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);
89         if (ctx->lgfp)
90             ctx->state = L_OPEN;
91         else
92             ctx->state = L_ERROR;
93     }
94
95     if (ctx->state == L_OPEN) {
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
103     event = dupprintf("%s session log (%s mode) to file: %s",
104                       (mode == 0 ? "Disabled writing" :
105                        mode == 1 ? "Appending" : "Writing new"),
106                       (ctx->cfg.logtype == LGTYP_ASCII ? "ASCII" :
107                        ctx->cfg.logtype == LGTYP_DEBUG ? "raw" :
108                        ctx->cfg.logtype == LGTYP_PACKETS ? "SSH packets" :
109                        "unknown"),
110                       filename_to_str(&ctx->currlogfilename));
111     logevent(ctx->frontend, event);
112     sfree(event);
113
114     /*
115      * Having either succeeded or failed in opening the log file,
116      * we should write any queued data out.
117      */
118     assert(ctx->state != L_OPENING);   /* make _sure_ it won't be requeued */
119     while (bufchain_size(&ctx->queue)) {
120         void *data;
121         int len;
122         bufchain_prefix(&ctx->queue, &data, &len);
123         logwrite(ctx, data, len);
124         bufchain_consume(&ctx->queue, len);
125     }
126 }
127
128 /*
129  * Open the log file. Takes care of detecting an already-existing
130  * file and asking the user whether they want to append, overwrite
131  * or cancel logging.
132  */
133 void logfopen(void *handle)
134 {
135     struct LogContext *ctx = (struct LogContext *)handle;
136     struct tm tm;
137     int mode;
138
139     /* Prevent repeat calls */
140     if (ctx->state != L_CLOSED)
141         return;
142
143     if (!ctx->cfg.logtype)
144         return;
145
146     tm = ltime();
147
148     /* substitute special codes in file name */
149     xlatlognam(&ctx->currlogfilename, ctx->cfg.logfilename,ctx->cfg.host, &tm);
150
151     ctx->lgfp = f_open(ctx->currlogfilename, "r");  /* file already present? */
152     if (ctx->lgfp) {
153         fclose(ctx->lgfp);
154         if (ctx->cfg.logxfovr != LGXF_ASK) {
155             mode = ((ctx->cfg.logxfovr == LGXF_OVR) ? 2 : 1);
156         } else
157             mode = askappend(ctx->frontend, ctx->currlogfilename,
158                              logfopen_callback, ctx);
159     } else
160         mode = 2;                      /* create == overwrite */
161
162     if (mode < 0)
163         ctx->state = L_OPENING;
164     else
165         logfopen_callback(ctx, mode);  /* open the file */
166 }
167
168 void logfclose(void *handle)
169 {
170     struct LogContext *ctx = (struct LogContext *)handle;
171     if (ctx->lgfp) {
172         fclose(ctx->lgfp);
173         ctx->lgfp = NULL;
174     }
175     ctx->state = L_CLOSED;
176 }
177
178 /*
179  * Log session traffic.
180  */
181 void logtraffic(void *handle, unsigned char c, int logmode)
182 {
183     struct LogContext *ctx = (struct LogContext *)handle;
184     if (ctx->cfg.logtype > 0) {
185         if (ctx->cfg.logtype == logmode)
186             logwrite(ctx, &c, 1);
187     }
188 }
189
190 /*
191  * Log an Event Log entry. Used in SSH packet logging mode; this is
192  * also as convenient a place as any to put the output of Event Log
193  * entries to stderr when a command-line tool is in verbose mode.
194  * (In particular, this is a better place to put it than in the
195  * front ends, because it only has to be done once for all
196  * platforms. Platforms which don't have a meaningful stderr can
197  * just avoid defining FLAG_STDERR.
198  */
199 void log_eventlog(void *handle, const char *event)
200 {
201     struct LogContext *ctx = (struct LogContext *)handle;
202     if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) {
203         fprintf(stderr, "%s\n", event);
204         fflush(stderr);
205     }
206     if (ctx->cfg.logtype != LGTYP_PACKETS)
207         return;
208     logprintf(ctx, "Event Log: %s\r\n", event);
209 }
210
211 /*
212  * Log an SSH packet.
213  * If n_blanks != 0, blank or omit some parts.
214  * Set of blanking areas must be in increasing order.
215  */
216 void log_packet(void *handle, int direction, int type,
217                 char *texttype, void *data, int len,
218                 int n_blanks, const struct logblank_t *blanks)
219 {
220     struct LogContext *ctx = (struct LogContext *)handle;
221     char dumpdata[80], smalldata[5];
222     int p = 0, b = 0, omitted = 0;
223     int output_pos = 0; /* NZ if pending output in dumpdata */
224
225     if (ctx->cfg.logtype != LGTYP_PACKETS)
226         return;
227
228     /* Packet header. */
229     logprintf(ctx, "%s packet type %d / 0x%02x (%s)\r\n",
230               direction == PKT_INCOMING ? "Incoming" : "Outgoing",
231               type, type, texttype);
232
233     /*
234      * Output a hex/ASCII dump of the packet body, blanking/omitting
235      * parts as specified.
236      */
237     while (p < len) {
238         int blktype;
239
240         /* Move to a current entry in the blanking array. */
241         while ((b < n_blanks) &&
242                (p >= blanks[b].offset + blanks[b].len))
243             b++;
244         /* Work out what type of blanking to apply to
245          * this byte. */
246         blktype = PKTLOG_EMIT; /* default */
247         if ((b < n_blanks) &&
248             (p >= blanks[b].offset) &&
249             (p < blanks[b].offset + blanks[b].len))
250             blktype = blanks[b].type;
251
252         /* If we're about to stop omitting, it's time to say how
253          * much we omitted. */
254         if ((blktype != PKTLOG_OMIT) && omitted) {
255             logprintf(ctx, "  (%d byte%s omitted)\r\n",
256                       omitted, (omitted==1?"":"s"));
257             omitted = 0;
258         }
259
260         /* (Re-)initialise dumpdata as necessary
261          * (start of row, or if we've just stopped omitting) */
262         if (!output_pos && !omitted)
263             sprintf(dumpdata, "  %08x%*s\r\n", p-(p%16), 1+3*16+2+16, "");
264
265         /* Deal with the current byte. */
266         if (blktype == PKTLOG_OMIT) {
267             omitted++;
268         } else {
269             int c;
270             if (blktype == PKTLOG_BLANK) {
271                 c = 'X';
272                 sprintf(smalldata, "XX");
273             } else {  /* PKTLOG_EMIT */
274                 c = ((unsigned char *)data)[p];
275                 sprintf(smalldata, "%02x", c);
276             }
277             dumpdata[10+2+3*(p%16)] = smalldata[0];
278             dumpdata[10+2+3*(p%16)+1] = smalldata[1];
279             dumpdata[10+1+3*16+2+(p%16)] = (isprint(c) ? c : '.');
280             output_pos = (p%16) + 1;
281         }
282
283         p++;
284
285         /* Flush row if necessary */
286         if (((p % 16) == 0) || (p == len) || omitted) {
287             if (output_pos) {
288                 strcpy(dumpdata + 10+1+3*16+2+output_pos, "\r\n");
289                 logwrite(ctx, dumpdata, strlen(dumpdata));
290                 output_pos = 0;
291             }
292         }
293
294     }
295
296     /* Tidy up */
297     if (omitted)
298         logprintf(ctx, "  (%d byte%s omitted)\r\n",
299                   omitted, (omitted==1?"":"s"));
300     logflush(ctx);
301 }
302
303 void *log_init(void *frontend, Config *cfg)
304 {
305     struct LogContext *ctx = snew(struct LogContext);
306     ctx->lgfp = NULL;
307     ctx->state = L_CLOSED;
308     ctx->frontend = frontend;
309     ctx->cfg = *cfg;                   /* STRUCTURE COPY */
310     bufchain_init(&ctx->queue);
311     return ctx;
312 }
313
314 void log_free(void *handle)
315 {
316     struct LogContext *ctx = (struct LogContext *)handle;
317
318     logfclose(ctx);
319     bufchain_clear(&ctx->queue);
320     sfree(ctx);
321 }
322
323 void log_reconfig(void *handle, Config *cfg)
324 {
325     struct LogContext *ctx = (struct LogContext *)handle;
326     int reset_logging;
327
328     if (!filename_equal(ctx->cfg.logfilename, cfg->logfilename) ||
329         ctx->cfg.logtype != cfg->logtype)
330         reset_logging = TRUE;
331     else
332         reset_logging = FALSE;
333
334     if (reset_logging)
335         logfclose(ctx);
336
337     ctx->cfg = *cfg;                   /* STRUCTURE COPY */
338
339     if (reset_logging)
340         logfopen(ctx);
341 }
342
343 /*
344  * translate format codes into time/date strings
345  * and insert them into log file name
346  *
347  * "&Y":YYYY   "&m":MM   "&d":DD   "&T":hhmm   "&h":<hostname>   "&&":&
348  */
349 static void xlatlognam(Filename *dest, Filename src,
350                        char *hostname, struct tm *tm) {
351     char buf[10], *bufp;
352     int size;
353     char buffer[FILENAME_MAX];
354     int len = sizeof(buffer)-1;
355     char *d;
356     const char *s;
357
358     d = buffer;
359     s = filename_to_str(&src);
360
361     while (*s) {
362         /* Let (bufp, len) be the string to append. */
363         bufp = buf;                    /* don't usually override this */
364         if (*s == '&') {
365             char c;
366             s++;
367             size = 0;
368             if (*s) switch (c = *s++, tolower(c)) {
369               case 'y':
370                 size = strftime(buf, sizeof(buf), "%Y", tm);
371                 break;
372               case 'm':
373                 size = strftime(buf, sizeof(buf), "%m", tm);
374                 break;
375               case 'd':
376                 size = strftime(buf, sizeof(buf), "%d", tm);
377                 break;
378               case 't':
379                 size = strftime(buf, sizeof(buf), "%H%M%S", tm);
380                 break;
381               case 'h':
382                 bufp = hostname;
383                 size = strlen(bufp);
384                 break;
385               default:
386                 buf[0] = '&';
387                 size = 1;
388                 if (c != '&')
389                     buf[size++] = c;
390             }
391         } else {
392             buf[0] = *s++;
393             size = 1;
394         }
395         if (size > len)
396             size = len;
397         memcpy(d, bufp, size);
398         d += size;
399         len -= size;
400     }
401     *d = '\0';
402
403     *dest = filename_from_str(buffer);
404 }