i3
log.c
Go to the documentation of this file.
1/*
2 * vim:ts=4:sw=4:expandtab
3 *
4 * i3 - an improved dynamic 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)
129}
130
131/*
132 * Opens the logbuffer.
133 *
134 */
135void open_logbuffer(void) {
136 /* Reserve 1% of the RAM for the logfile, but at max 25 MiB.
137 * For 512 MiB of RAM this will lead to a 5 MiB log buffer.
138 * At the moment (2011-12-10), no testcase leads to an i3 log
139 * of more than ~ 600 KiB. */
141 if (physical_mem_bytes * 0.01 < (long long)shmlog_size) {
143 }
144
145#if defined(__FreeBSD__)
146 sasprintf(&shmlogname, "/tmp/i3-log-%d", getpid());
147#else
148 sasprintf(&shmlogname, "/i3-log-%d", getpid());
149#endif
150 logbuffer_shm = shm_open(shmlogname, O_RDWR | O_CREAT, S_IREAD | S_IWRITE);
151 if (logbuffer_shm == -1) {
152 fprintf(stderr, "Could not shm_open SHM segment for the i3 log: %s\n", strerror(errno));
153 return;
154 }
155
156#if defined(__OpenBSD__) || defined(__APPLE__)
157 if (ftruncate(logbuffer_shm, logbuffer_size) == -1) {
158 fprintf(stderr, "Could not ftruncate SHM segment for the i3 log: %s\n", strerror(errno));
159#else
160 int ret;
161 if ((ret = posix_fallocate(logbuffer_shm, 0, logbuffer_size)) != 0) {
162 fprintf(stderr, "Could not ftruncate SHM segment for the i3 log: %s\n", strerror(ret));
163#endif
164 close(logbuffer_shm);
165 shm_unlink(shmlogname);
166 return;
167 }
168
169 logbuffer = mmap(NULL, logbuffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, logbuffer_shm, 0);
170 if (logbuffer == MAP_FAILED) {
172 fprintf(stderr, "Could not mmap SHM segment for the i3 log: %s\n", strerror(errno));
173 return;
174 }
175
176 /* Initialize with 0-bytes, just to be sure… */
177 memset(logbuffer, '\0', logbuffer_size);
178
180
184}
185
186/*
187 * Closes the logbuffer.
188 *
189 */
190void close_logbuffer(void) {
191 close(logbuffer_shm);
192 shm_unlink(shmlogname);
193 free(shmlogname);
194 logbuffer = NULL;
195 shmlogname = "";
196}
197
198/*
199 * Set verbosity of i3. If verbose is set to true, informative messages will
200 * be printed to stdout. If verbose is set to false, only errors will be
201 * printed.
202 *
203 */
204void set_verbosity(bool _verbose) {
205 verbose = _verbose;
206}
207
208/*
209 * Get debug logging.
210 *
211 */
213 return debug_logging;
214}
215
216/*
217 * Set debug logging.
218 *
219 */
220void set_debug_logging(const bool _debug_logging) {
221 debug_logging = _debug_logging;
222}
223
224/*
225 * Logs the given message to stdout (if print is true) while prefixing the
226 * current time to it. Additionally, the message will be saved in the i3 SHM
227 * log if enabled.
228 * This is to be called by *LOG() which includes filename/linenumber/function.
229 *
230 */
231static void vlog(const bool print, const char *fmt, va_list args) {
232 /* Precisely one page to not consume too much memory but to hold enough
233 * data to be useful. */
234 static char message[4096];
235 static struct tm result;
236 static time_t t;
237 static struct tm *tmp;
238 static size_t len;
239
240 /* Get current time */
241 t = time(NULL);
242 /* Convert time to local time (determined by the locale) */
243 tmp = localtime_r(&t, &result);
244 /* Generate time prefix */
245 len = strftime(message, sizeof(message), "%x %X - ", tmp);
246
247 /*
248 * logbuffer print
249 * ----------------
250 * true true format message, save, print
251 * true false format message, save
252 * false true print message only
253 * false false INVALID, never called
254 */
255 if (!logbuffer) {
256#ifdef DEBUG_TIMING
257 struct timeval tv;
258 gettimeofday(&tv, NULL);
259 printf("%s%d.%d - ", message, tv.tv_sec, tv.tv_usec);
260#else
261 printf("%s", message);
262#endif
263 vprintf(fmt, args);
264 } else {
265 len += vsnprintf(message + len, sizeof(message) - len, fmt, args);
266 if (len >= sizeof(message)) {
267 fprintf(stderr, "BUG: single log message > 4k\n");
268
269 /* vsnprintf returns the number of bytes that *would have been written*,
270 * not the actual amount written. Thus, limit len to sizeof(message) to avoid
271 * memory corruption and outputting garbage later. */
272 len = sizeof(message);
273
274 /* Punch in a newline so the next log message is not dangling at
275 * the end of the truncated message. */
276 message[len - 2] = '\n';
277 }
278
279 /* If there is no space for the current message in the ringbuffer, we
280 * need to wrap and write to the beginning again. */
281 if (len >= (size_t)(logbuffer_size - (logwalk - logbuffer))) {
286 }
287
288 /* Copy the buffer, move the write pointer to the byte after our
289 * current message. */
290 strncpy(logwalk, message, len);
291 logwalk += len;
292
294
295 if (print)
296 fwrite(message, len, 1, stdout);
297
298 log_broadcast_to_clients(message, len);
299 }
300}
301
302/*
303 * Logs the given message to stdout while prefixing the current time to it,
304 * but only if verbose mode is activated.
305 *
306 */
307void verboselog(char *fmt, ...) {
308 va_list args;
309
310 if (!logbuffer && !verbose)
311 return;
312
313 va_start(args, fmt);
314 vlog(verbose, fmt, args);
315 va_end(args);
316}
317
318/*
319 * Logs the given message to stdout while prefixing the current time to it.
320 *
321 */
322void errorlog(char *fmt, ...) {
323 va_list args;
324
325 va_start(args, fmt);
326 vlog(true, fmt, args);
327 va_end(args);
328
329 /* also log to the error logfile, if opened */
330 va_start(args, fmt);
331 vfprintf(errorfile, fmt, args);
332 fflush(errorfile);
333 va_end(args);
334}
335
336/*
337 * Logs the given message to stdout while prefixing the current time to it,
338 * but only if debug logging was activated.
339 * This is to be called by DLOG() which includes filename/linenumber
340 *
341 */
342void debuglog(char *fmt, ...) {
343 va_list args;
344
345 if (!logbuffer && !(debug_logging))
346 return;
347
348 va_start(args, fmt);
349 vlog(debug_logging, fmt, args);
350 va_end(args);
351}
352
353/*
354 * Deletes the unused log files. Useful if i3 exits immediately, eg.
355 * because --get-socketpath was called. We don't care for syscall
356 * failures. This function is invoked automatically when exiting.
357 */
359 struct stat st;
360 char *slash;
361
362 if (!errorfilename)
363 return;
364
365 /* don't delete the log file if it contains something */
366 if ((stat(errorfilename, &st)) == -1 || st.st_size > 0)
367 return;
368
369 if (unlink(errorfilename) == -1)
370 return;
371
372 if ((slash = strrchr(errorfilename, '/')) != NULL) {
373 *slash = '\0';
374 /* possibly fails with ENOTEMPTY if there are files (or
375 * sockets) left. */
376 rmdir(errorfilename);
377 }
378}
379
381
382/*
383 * Handler for activity on the listening socket, meaning that a new client
384 * has just connected and we should accept() them. Sets up the event handler
385 * for activity on the new connection and inserts the file descriptor into
386 * the list of log clients.
387 *
388 */
389void log_new_client(EV_P_ struct ev_io *w, int revents) {
390 struct sockaddr_un peer;
391 socklen_t len = sizeof(struct sockaddr_un);
392 int fd;
393 if ((fd = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
394 if (errno != EINTR) {
395 perror("accept()");
396 }
397 return;
398 }
399
400 /* Close this file descriptor on exec() */
401 (void)fcntl(fd, F_SETFD, FD_CLOEXEC);
402
404
405 log_client *client = scalloc(1, sizeof(log_client));
406 client->fd = fd;
408
409 DLOG("log: new client connected on fd %d\n", fd);
410}
411
412void log_broadcast_to_clients(const char *message, size_t len) {
414 while (current != TAILQ_END(&log_clients)) {
415 /* XXX: In case slow connections turn out to be a problem here
416 * (unlikely as long as i3-dump-log is the only consumer), introduce
417 * buffering, similar to the IPC interface. */
418 ssize_t n = writeall(current->fd, message, len);
419 log_client *previous = current;
420 current = TAILQ_NEXT(current, clients);
421 if (n < 0) {
422 TAILQ_REMOVE(&log_clients, previous, clients);
423 free(previous);
424 }
425 }
426}
int shmlog_size
Definition log.c:47
void errorlog(char *fmt,...)
Definition log.c:322
void debuglog(char *fmt,...)
Definition log.c:342
bool get_debug_logging(void)
Checks if debug logging is active.
Definition log.c:212
void log_new_client(EV_P_ struct ev_io *w, int revents)
Definition log.c:389
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:220
char * current_log_stream_socket_path
Definition log.c:380
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:135
void verboselog(char *fmt,...)
Definition log.c:307
char * shmlogname
Definition log.c:44
void set_verbosity(bool _verbose)
Set verbosity of i3.
Definition log.c:204
void purge_zerobyte_logfile(void)
Deletes the unused log files.
Definition log.c:358
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:412
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:231
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:190
#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