i3
log.c
Go to the documentation of this file.
1/*
2 * vim:ts=4:sw=4:expandtab
3 *
4 * i3 - an improved tiling window manager
5 * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6 *
7 * log.c: Logging functions.
8 *
9 */
10#include <config.h>
11
12#include "all.h"
13#include "shmlog.h"
14
15#include <libev/ev.h>
16#include <libgen.h>
17#include <sys/socket.h>
18#include <sys/un.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <stdarg.h>
22#include <stdbool.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/mman.h>
27#include <sys/stat.h>
28#include <sys/time.h>
29#include <unistd.h>
30
31#if defined(__APPLE__)
32#include <sys/sysctl.h>
33#endif
34
35static bool debug_logging = false;
36static bool verbose = false;
37static FILE *errorfile;
39
40/* SHM logging variables */
41
42/* The name for the SHM (/i3-log-%pid). Will end up on /dev/shm on most
43 * systems. Global so that we can clean up at exit. */
44char *shmlogname = "";
45/* Size limit for the SHM log, by default 25 MiB. Can be overwritten using the
46 * flag --shmlog-size. */
48/* If enabled, logbuffer will point to a memory mapping of the i3 SHM log. */
49static char *logbuffer;
50/* A pointer (within logbuffer) where data will be written to next. */
51static char *logwalk;
52/* A pointer to the shmlog header */
54/* A pointer to the byte where we last wrapped. Necessary to not print the
55 * left-overs at the end of the ringbuffer. */
56static char *loglastwrap;
57/* Size (in bytes) of the i3 SHM log. */
58static int logbuffer_size;
59/* File descriptor for shm_open. */
60static int logbuffer_shm;
61/* Size (in bytes) of physical memory */
62static long long physical_mem_bytes;
63
70
71TAILQ_HEAD(log_client_head, log_client)
73
74void log_broadcast_to_clients(const char *message, size_t len);
75
76/*
77 * Writes the offsets for the next write and for the last wrap to the
78 * shmlog_header.
79 * Necessary to print the i3 SHM log in the correct order.
80 *
81 */
87
88/*
89 * Initializes logging by creating an error logfile in /tmp (or
90 * XDG_RUNTIME_DIR, see get_process_filename()).
91 *
92 * Will be called twice if --shmlog-size is specified.
93 *
94 */
95void init_logging(void) {
96 if (!errorfilename) {
97 if (!(errorfilename = get_process_filename("errorlog"))) {
98 fprintf(stderr, "Could not initialize errorlog\n");
99 } else {
100 errorfile = fopen(errorfilename, "w");
101 if (!errorfile) {
102 fprintf(stderr, "Could not initialize errorlog on %s: %s\n",
103 errorfilename, strerror(errno));
104 } else {
105 if (fcntl(fileno(errorfile), F_SETFD, FD_CLOEXEC)) {
106 fprintf(stderr, "Could not set close-on-exec flag\n");
107 }
108 }
109 }
110 }
111 if (physical_mem_bytes == 0) {
112#if defined(__APPLE__)
113 int mib[2] = {CTL_HW, HW_MEMSIZE};
114 size_t length = sizeof(long long);
115 sysctl(mib, 2, &physical_mem_bytes, &length, NULL, 0);
116#else
117 physical_mem_bytes = (long long)sysconf(_SC_PHYS_PAGES) *
118 sysconf(_SC_PAGESIZE);
119#endif
120 }
121 /* Start SHM logging if shmlog_size is > 0. shmlog_size is SHMLOG_SIZE by
122 * default on development versions, and 0 on release versions. If it is
123 * not > 0, the user has turned it off, so let's close the logbuffer. */
124 if (shmlog_size > 0 && logbuffer == NULL) {
126 } else if (shmlog_size <= 0 && logbuffer) {
128 }
130}
131
132/*
133 * Opens the logbuffer.
134 *
135 */
136void open_logbuffer(void) {
137 /* Reserve 1% of the RAM for the logfile, but at max 25 MiB.
138 * For 512 MiB of RAM this will lead to a 5 MiB log buffer.
139 * At the moment (2011-12-10), no testcase leads to an i3 log
140 * of more than ~ 600 KiB. */
142 if (physical_mem_bytes * 0.01 < (long long)shmlog_size) {
144 }
145
146#if defined(__FreeBSD__)
147 sasprintf(&shmlogname, "/tmp/i3-log-%d", getpid());
148#else
149 sasprintf(&shmlogname, "/i3-log-%d", getpid());
150#endif
151 logbuffer_shm = shm_open(shmlogname, O_RDWR | O_CREAT, S_IREAD | S_IWRITE);
152 if (logbuffer_shm == -1) {
153 fprintf(stderr, "Could not shm_open SHM segment for the i3 log: %s\n", strerror(errno));
154 return;
155 }
156
157#if defined(__OpenBSD__) || defined(__APPLE__)
158 if (ftruncate(logbuffer_shm, logbuffer_size) == -1) {
159 fprintf(stderr, "Could not ftruncate SHM segment for the i3 log: %s\n", strerror(errno));
160#else
161 int ret;
162 if ((ret = posix_fallocate(logbuffer_shm, 0, logbuffer_size)) != 0) {
163 fprintf(stderr, "Could not ftruncate SHM segment for the i3 log: %s\n", strerror(ret));
164#endif
165 close(logbuffer_shm);
166 shm_unlink(shmlogname);
167 return;
168 }
169
170 logbuffer = mmap(NULL, logbuffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, logbuffer_shm, 0);
171 if (logbuffer == MAP_FAILED) {
173 fprintf(stderr, "Could not mmap SHM segment for the i3 log: %s\n", strerror(errno));
174 return;
175 }
176
177 /* Initialize with 0-bytes, just to be sure… */
178 memset(logbuffer, '\0', logbuffer_size);
179
181
185}
186
187/*
188 * Closes the logbuffer.
189 *
190 */
191void close_logbuffer(void) {
192 close(logbuffer_shm);
193 shm_unlink(shmlogname);
194 free(shmlogname);
195 logbuffer = NULL;
196 shmlogname = "";
197}
198
199/*
200 * Set verbosity of i3. If verbose is set to true, informative messages will
201 * be printed to stdout. If verbose is set to false, only errors will be
202 * printed.
203 *
204 */
205void set_verbosity(bool _verbose) {
206 verbose = _verbose;
207}
208
209/*
210 * Get debug logging.
211 *
212 */
214 return debug_logging;
215}
216
217/*
218 * Set debug logging.
219 *
220 */
221void set_debug_logging(const bool _debug_logging) {
222 debug_logging = _debug_logging;
223}
224
225/*
226 * Logs the given message to stdout (if print is true) while prefixing the
227 * current time to it. Additionally, the message will be saved in the i3 SHM
228 * log if enabled.
229 * This is to be called by *LOG() which includes filename/linenumber/function.
230 *
231 */
232static void vlog(const bool print, const char *fmt, va_list args) {
233 /* Precisely one page to not consume too much memory but to hold enough
234 * data to be useful. */
235 static char message[4096];
236 static struct tm result;
237 static time_t t;
238 static struct tm *tmp;
239 static size_t len;
240
241 /* Get current time */
242 t = time(NULL);
243 /* Convert time to local time (determined by the locale) */
244 tmp = localtime_r(&t, &result);
245 /* Generate time prefix */
246 len = strftime(message, sizeof(message), "%x %X - ", tmp);
247
248 /*
249 * logbuffer print
250 * ----------------
251 * true true format message, save, print
252 * true false format message, save
253 * false true print message only
254 * false false INVALID, never called
255 */
256 if (!logbuffer) {
257#ifdef DEBUG_TIMING
258 struct timeval tv;
259 gettimeofday(&tv, NULL);
260 printf("%s%d.%d - ", message, tv.tv_sec, tv.tv_usec);
261#else
262 printf("%s", message);
263#endif
264 vprintf(fmt, args);
265 } else {
266 len += vsnprintf(message + len, sizeof(message) - len, fmt, args);
267 if (len >= sizeof(message)) {
268 fprintf(stderr, "BUG: single log message > 4k\n");
269
270 /* vsnprintf returns the number of bytes that *would have been written*,
271 * not the actual amount written. Thus, limit len to sizeof(message) to avoid
272 * memory corruption and outputting garbage later. */
273 len = sizeof(message);
274
275 /* Punch in a newline so the next log message is not dangling at
276 * the end of the truncated message. */
277 message[len - 2] = '\n';
278 }
279
280 /* If there is no space for the current message in the ringbuffer, we
281 * need to wrap and write to the beginning again. */
282 if (len >= (size_t)(logbuffer_size - (logwalk - logbuffer))) {
287 }
288
289 /* Copy the buffer, move the write pointer to the byte after our
290 * current message. */
291 strncpy(logwalk, message, len);
292 logwalk += len;
293
295
296 if (print) {
297 fwrite(message, len, 1, stdout);
298 }
299
300 log_broadcast_to_clients(message, len);
301 }
302}
303
304/*
305 * Logs the given message to stdout while prefixing the current time to it,
306 * but only if verbose mode is activated.
307 *
308 */
309void verboselog(char *fmt, ...) {
310 va_list args;
311
312 if (!logbuffer && !verbose) {
313 return;
314 }
315
316 va_start(args, fmt);
317 vlog(verbose, fmt, args);
318 va_end(args);
319}
320
321/*
322 * Logs the given message to stdout while prefixing the current time to it.
323 *
324 */
325void errorlog(char *fmt, ...) {
326 va_list args;
327
328 va_start(args, fmt);
329 vlog(true, fmt, args);
330 va_end(args);
331
332 /* also log to the error logfile, if opened */
333 if (!errorfile) {
334 return;
335 }
336 va_start(args, fmt);
337 vfprintf(errorfile, fmt, args);
338 fflush(errorfile);
339 va_end(args);
340}
341
342/*
343 * Logs the given message to stdout while prefixing the current time to it,
344 * but only if debug logging was activated.
345 * This is to be called by DLOG() which includes filename/linenumber
346 *
347 */
348void debuglog(char *fmt, ...) {
349 va_list args;
350
351 if (!logbuffer && !(debug_logging)) {
352 return;
353 }
354
355 va_start(args, fmt);
356 vlog(debug_logging, fmt, args);
357 va_end(args);
358}
359
360/*
361 * Deletes the unused log files. Useful if i3 exits immediately, eg.
362 * because --get-socketpath was called. We don't care for syscall
363 * failures. This function is invoked automatically when exiting.
364 */
366 struct stat st;
367 char *slash;
368
369 if (!errorfilename) {
370 return;
371 }
372
373 /* don't delete the log file if it contains something */
374 if ((stat(errorfilename, &st)) == -1 || st.st_size > 0) {
375 return;
376 }
377
378 if (unlink(errorfilename) == -1) {
379 return;
380 }
381
382 if ((slash = strrchr(errorfilename, '/')) != NULL) {
383 *slash = '\0';
384 /* possibly fails with ENOTEMPTY if there are files (or
385 * sockets) left. */
386 rmdir(errorfilename);
387 }
388}
389
391
392/*
393 * Handler for activity on the listening socket, meaning that a new client
394 * has just connected and we should accept() them. Sets up the event handler
395 * for activity on the new connection and inserts the file descriptor into
396 * the list of log clients.
397 *
398 */
399void log_new_client(EV_P_ struct ev_io *w, int revents) {
400 struct sockaddr_un peer;
401 socklen_t len = sizeof(struct sockaddr_un);
402 int fd;
403 if ((fd = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
404 if (errno != EINTR) {
405 perror("accept()");
406 }
407 return;
408 }
409
410 /* Close this file descriptor on exec() */
411 (void)fcntl(fd, F_SETFD, FD_CLOEXEC);
412
414
415 log_client *client = scalloc(1, sizeof(log_client));
416 client->fd = fd;
418
419 DLOG("log: new client connected on fd %d\n", fd);
420}
421
422void log_broadcast_to_clients(const char *message, size_t len) {
424 while (current != TAILQ_END(&log_clients)) {
425 /* XXX: In case slow connections turn out to be a problem here
426 * (unlikely as long as i3-dump-log is the only consumer), introduce
427 * buffering, similar to the IPC interface. */
428 ssize_t n = writeall(current->fd, message, len);
429 log_client *previous = current;
430 current = TAILQ_NEXT(current, clients);
431 if (n < 0) {
432 TAILQ_REMOVE(&log_clients, previous, clients);
433 free(previous);
434 }
435 }
436}
int shmlog_size
Definition log.c:47
void errorlog(char *fmt,...)
Definition log.c:325
void debuglog(char *fmt,...)
Definition log.c:348
bool get_debug_logging(void)
Checks if debug logging is active.
Definition log.c:213
void log_new_client(EV_P_ struct ev_io *w, int revents)
Definition log.c:399
static bool debug_logging
Definition log.c:35
static int logbuffer_shm
Definition log.c:60
log_clients
Definition log.c:72
void init_logging(void)
Initializes logging by creating an error logfile in /tmp (or XDG_RUNTIME_DIR, see get_process_filenam...
Definition log.c:95
static int logbuffer_size
Definition log.c:58
void set_debug_logging(const bool _debug_logging)
Set debug logging.
Definition log.c:221
char * current_log_stream_socket_path
Definition log.c:390
static char * logbuffer
Definition log.c:49
static i3_shmlog_header * header
Definition log.c:53
void open_logbuffer(void)
Opens the logbuffer.
Definition log.c:136
void verboselog(char *fmt,...)
Definition log.c:309
char * shmlogname
Definition log.c:44
void set_verbosity(bool _verbose)
Set verbosity of i3.
Definition log.c:205
void purge_zerobyte_logfile(void)
Deletes the unused log files.
Definition log.c:365
static char * logwalk
Definition log.c:51
char * errorfilename
Definition log.c:38
void log_broadcast_to_clients(const char *message, size_t len)
Definition log.c:422
static char * loglastwrap
Definition log.c:56
static bool verbose
Definition log.c:36
static void vlog(const bool print, const char *fmt, va_list args)
Definition log.c:232
static long long physical_mem_bytes
Definition log.c:62
static FILE * errorfile
Definition log.c:37
static void store_log_markers(void)
Definition log.c:82
void close_logbuffer(void)
Closes the logbuffer.
Definition log.c:191
#define DLOG(fmt,...)
Definition libi3.h:105
ssize_t writeall(int fd, const void *buf, size_t count)
Wrapper around correct write which returns -1 (meaning that write failed) or count (meaning that all ...
void set_nonblock(int sockfd)
Puts the given socket file descriptor into non-blocking mode or dies if setting O_NONBLOCK failed.
void * scalloc(size_t num, size_t size)
Safe-wrapper around calloc which exits if malloc returns NULL (meaning that there is no more memory a...
int sasprintf(char **strp, const char *fmt,...)
Safe-wrapper around asprintf which exits if it returns -1 (meaning that there is no more memory avail...
char * get_process_filename(const char *prefix)
Returns the name of a temporary file with the specified prefix.
#define TAILQ_END(head)
Definition queue.h:337
#define TAILQ_HEAD(name, type)
Definition queue.h:318
#define TAILQ_INSERT_TAIL(head, elm, field)
Definition queue.h:376
#define TAILQ_FIRST(head)
Definition queue.h:336
#define TAILQ_REMOVE(head, elm, field)
Definition queue.h:402
#define TAILQ_NEXT(elm, field)
Definition queue.h:338
#define TAILQ_HEAD_INITIALIZER(head)
Definition queue.h:324
#define TAILQ_ENTRY(type)
Definition queue.h:327
struct i3_shmlog_header i3_shmlog_header
Header of the shmlog file.
int fd
Definition log.c:65
clients
Definition log.c:68
Header of the shmlog file.
Definition shmlog.h:22
uint32_t offset_last_wrap
Definition shmlog.h:27
uint32_t offset_next_write
Definition shmlog.h:24
uint32_t wrap_count
Definition shmlog.h:37
uint32_t size
Definition shmlog.h:31