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