Modify last commit to keep compiler happy since it claims devbuf can never be null...
[monky] / src / common.c
1 /* -*- mode: c; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
2  * vim: ts=4 sw=4 noet ai cindent syntax=c
3  *
4  * Conky, a system monitor, based on torsmo
5  *
6  * Any original torsmo code is licensed under the BSD license
7  *
8  * All code written since the fork of torsmo is licensed under the GPL
9  *
10  * Please see COPYING for details
11  *
12  * Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
13  * Copyright (c) 2005-2010 Brenden Matthews, Philip Kovacs, et. al.
14  *      (see AUTHORS)
15  * All rights reserved.
16  *
17  * This program is free software: you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation, either version 3 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  * You should have received a copy of the GNU General Public License
27  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
28  *
29  */
30
31 #include "config.h"
32 #include "conky.h"
33 #include "fs.h"
34 #include "logging.h"
35 #include "net_stat.h"
36 #include "specials.h"
37 #include "timeinfo.h"
38 #include <ctype.h>
39 #include <errno.h>
40 #include <sys/time.h>
41 #include <sys/ioctl.h>
42 #include <net/if.h>
43 #include <netinet/in.h>
44 #include <pthread.h>
45 #include <semaphore.h>
46 #include <unistd.h>
47 #include "diskio.h"
48 #include <fcntl.h>
49
50 /* check for OS and include appropriate headers */
51 #if defined(__linux__)
52 #include "linux.h"
53 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
54 #include "freebsd.h"
55 #elif defined(__OpenBSD__)
56 #include "openbsd.h"
57 #endif
58
59 /* folds a string over top of itself, like so:
60  *
61  * if start is "blah", and you call it with count = 1, the result will be "lah"
62  */
63 void strfold(char *start, int count)
64 {
65         char *curplace;
66         for (curplace = start + count; *curplace != 0; curplace++) {
67                 *(curplace - count) = *curplace;
68         }
69         *(curplace - count) = 0;
70 }
71
72 #ifndef HAVE_STRNDUP
73 // use our own strndup() if it's not available
74 char *strndup(const char *s, size_t n)
75 {
76         if (strlen(s) > n) {
77                 char *ret = malloc(n + 1);
78                 strncpy(ret, s, n);
79                 ret[n] = 0;
80                 return ret;
81         } else {
82                 return strdup(s);
83         }
84 }
85 #endif /* HAVE_STRNDUP */
86
87 void update_uname(void)
88 {
89         uname(&info.uname_s);
90 }
91
92 double get_time(void)
93 {
94         struct timeval tv;
95
96         gettimeofday(&tv, 0);
97         return tv.tv_sec + (tv.tv_usec / 1000000.0);
98 }
99
100 /* Converts '~/...' paths to '/home/blah/...' assumes that 'dest' is at least
101  * DEFAULT_TEXT_BUFFER_SIZE.  It's similar to variable_substitute, except only
102  * cheques for $HOME and ~/ in path */
103 void to_real_path(char *dest, const char *source)
104 {
105         char tmp[DEFAULT_TEXT_BUFFER_SIZE];
106         if (sscanf(source, "~/%s", tmp) || sscanf(source, "$HOME/%s", tmp)) {
107                 char *homedir = getenv("HOME");
108                 if (homedir) {
109                         snprintf(dest, DEFAULT_TEXT_BUFFER_SIZE, "%s/%s", homedir, tmp);
110                 } else {
111                         NORM_ERR("$HOME environment variable doesn't exist");
112                         strncpy(dest, source, DEFAULT_TEXT_BUFFER_SIZE);
113                 }
114         } else if (dest != source) {    //see changelog 2009-06-29 if you doubt that this check is necessary 
115                 strncpy(dest, source, DEFAULT_TEXT_BUFFER_SIZE);
116         }
117 }
118
119 int open_fifo(const char *file, int *reported)
120 {
121         char path[DEFAULT_TEXT_BUFFER_SIZE];
122         int fd = 0;
123
124         to_real_path(path, file);
125         fd = open(file, O_RDONLY | O_NONBLOCK);
126
127         if (fd == -1) {
128                 if (!reported || *reported == 0) {
129                         NORM_ERR("can't open %s: %s", file, strerror(errno));
130                         if (reported) {
131                                 *reported = 1;
132                         }
133                 }
134                 return -1;
135         }
136
137         return fd;
138 }
139
140 FILE *open_file(const char *file, int *reported)
141 {
142         char path[DEFAULT_TEXT_BUFFER_SIZE];
143         FILE *fp = 0;
144
145         to_real_path(path, file);
146         fp = fopen(file, "r");
147
148         if (!fp) {
149                 if (!reported || *reported == 0) {
150                         NORM_ERR("can't open %s: %s", file, strerror(errno));
151                         if (reported) {
152                                 *reported = 1;
153                         }
154                 }
155                 return NULL;
156         }
157
158         return fp;
159 }
160
161 void variable_substitute(const char *s, char *dest, unsigned int n)
162 {
163         while (*s && n > 1) {
164                 if (*s == '$') {
165                         s++;
166                         if (*s != '$') {
167                                 char buf[256];
168                                 const char *a, *var;
169                                 unsigned int len;
170
171                                 /* variable is either $foo or ${foo} */
172                                 if (*s == '{') {
173                                         s++;
174                                         a = s;
175                                         while (*s && *s != '}') {
176                                                 s++;
177                                         }
178                                 } else {
179                                         a = s;
180                                         while (*s && (isalnum((int) *s) || *s == '_')) {
181                                                 s++;
182                                         }
183                                 }
184
185                                 /* copy variable to buffer and look it up */
186                                 len = (s - a > 255) ? 255 : (s - a);
187                                 strncpy(buf, a, len);
188                                 buf[len] = '\0';
189
190                                 if (*s == '}') {
191                                         s++;
192                                 }
193
194                                 var = getenv(buf);
195
196                                 if (var) {
197                                         /* add var to dest */
198                                         len = strlen(var);
199                                         if (len >= n) {
200                                                 len = n - 1;
201                                         }
202                                         strncpy(dest, var, len);
203                                         dest += len;
204                                         n -= len;
205                                 }
206                                 continue;
207                         }
208                 }
209
210                 *dest++ = *s++;
211                 n--;
212         }
213
214         *dest = '\0';
215 }
216
217 void format_seconds(char *buf, unsigned int n, long seconds)
218 {
219         long days;
220         int hours, minutes;
221
222         if (times_in_seconds()) {
223                 snprintf(buf, n, "%ld", seconds);
224                 return;
225         }
226
227         days = seconds / 86400;
228         seconds %= 86400;
229         hours = seconds / 3600;
230         seconds %= 3600;
231         minutes = seconds / 60;
232         seconds %= 60;
233
234         if (days > 0) {
235                 snprintf(buf, n, "%ldd %dh %dm", days, hours, minutes);
236         } else {
237                 snprintf(buf, n, "%dh %dm %lds", hours, minutes, seconds);
238         }
239 }
240
241 void format_seconds_short(char *buf, unsigned int n, long seconds)
242 {
243         long days;
244         int hours, minutes;
245
246         if (times_in_seconds()) {
247                 snprintf(buf, n, "%ld", seconds);
248                 return;
249         }
250
251         days = seconds / 86400;
252         seconds %= 86400;
253         hours = seconds / 3600;
254         seconds %= 3600;
255         minutes = seconds / 60;
256         seconds %= 60;
257
258         if (days > 0) {
259                 snprintf(buf, n, "%ldd %dh", days, hours);
260         } else if (hours > 0) {
261                 snprintf(buf, n, "%dh %dm", hours, minutes);
262         } else {
263                 snprintf(buf, n, "%dm %lds", minutes, seconds);
264         }
265 }
266
267 /* Linked list containing the functions to call upon each update interval.
268  * Populated while initialising text objects in construct_text_object(). */
269 static struct update_cb {
270         struct update_cb *next;
271         void (*func)(void);
272         pthread_t thread;
273         sem_t start_wait, end_wait;
274
275     /* set to 1 when starting the thread
276          * set to 0 to request thread termination */
277         volatile char running;
278 } update_cb_head = {
279         .next = NULL,
280         .func = NULL,
281 };
282
283 static void *run_update_callback(void *) __attribute__((noreturn));
284
285 static int threading_started = 0;
286
287 /* Register an update callback. Don't allow duplicates, to minimise side
288  * effects and overhead. */
289 void add_update_callback(void (*func)(void))
290 {
291         struct update_cb *uc = &update_cb_head;
292
293         if (!func)
294                 return;
295
296         while (uc->next) {
297                 if (uc->next->func == func)
298                         return;
299                 uc = uc->next;
300         }
301
302         uc->next = malloc(sizeof(struct update_cb));
303         uc = uc->next;
304
305         memset(uc, 0, sizeof(struct update_cb));
306         uc->func = func;
307         sem_init(&uc->start_wait, 0, 0);
308         sem_init(&uc->end_wait, 0, 0);
309
310         if (threading_started) {
311                 if (!uc->running) {
312                         uc->running = 1;
313                         pthread_create(&uc->thread, NULL, &run_update_callback, uc);
314                 }
315         }
316 }
317
318 /* Free the list element uc and all decendants recursively. */
319 static void __free_update_callbacks(struct update_cb *uc)
320 {
321         if (uc->next)
322                 __free_update_callbacks(uc->next);
323
324         if (uc->running) {
325                 /* send cancellation request, then trigger and join the thread */
326                 uc->running = 0;
327                 sem_post(&uc->start_wait);
328         }
329         if (pthread_join(uc->thread, NULL)) {
330                 NORM_ERR("Error destroying thread");
331         }
332
333         /* finally destroy the semaphores */
334         sem_destroy(&uc->start_wait);
335         sem_destroy(&uc->end_wait);
336
337         free(uc);
338 }
339
340 /* Free the whole list of update callbacks. */
341 void free_update_callbacks(void)
342 {
343         if (update_cb_head.next)
344                 __free_update_callbacks(update_cb_head.next);
345         update_cb_head.next = NULL;
346 }
347
348 /* We cannot start threads before we forked to background, because the threads
349  * would remain in the wrong process. Because of that, add_update_callback()
350  * doesn't create threads before start_update_threading() is called.
351  * start_update_threading() starts all threads previously registered, and sets a
352  * flag so that future threads are automagically started by
353  * add_update_callback().
354  * This text is almost longer than the actual code.
355  */
356 void start_update_threading(void)
357 {
358         struct update_cb *uc;
359
360         threading_started = 1;
361
362         for (uc = update_cb_head.next; uc; uc = uc->next) {
363                 if (!uc->running) {
364                         uc->running = 1;
365                         pthread_create(&uc->thread, NULL, &run_update_callback, uc);
366                 }
367         }
368 }
369
370 static void *run_update_callback(void *data)
371 {
372         struct update_cb *ucb = data;
373
374         if (!ucb || !ucb->func) pthread_exit(NULL);
375
376         while (1) {
377                 if (sem_wait(&ucb->start_wait)) pthread_exit(NULL);
378                 if (ucb->running == 0) pthread_exit(NULL);
379                 (*ucb->func)();
380                 if (sem_post(&ucb->end_wait)) pthread_exit(NULL);
381         }
382 }
383
384 int no_buffers;
385
386 void update_stuff(void)
387 {
388         int i;
389         struct update_cb *uc;
390
391         /* clear speeds and up status in case device was removed and doesn't get
392          * updated */
393
394         #ifdef HAVE_OPENMP
395         #pragma omp parallel for schedule(dynamic,10)
396         #endif /* HAVE_OPENMP */
397         for (i = 0; i < MAX_NET_INTERFACES; i++) {
398                 if (netstats[i].dev) {
399                         netstats[i].up = 0;
400                         netstats[i].recv_speed = 0.0;
401                         netstats[i].trans_speed = 0.0;
402                 }
403         }
404
405         prepare_update();
406
407         for (uc = update_cb_head.next; uc; uc = uc->next) {
408                 if (sem_post(&uc->start_wait)) {
409                         NORM_ERR("Semaphore error");
410                 }
411         }
412         /* need to synchronise here, otherwise locking is needed (as data
413          * would be printed with some update callbacks still running) */
414         for (uc = update_cb_head.next; uc; uc = uc->next)
415                 sem_wait(&uc->end_wait);
416
417         /* XXX: move the following into the update_meminfo() functions? */
418         if (no_buffers) {
419                 info.mem -= info.bufmem;
420                 info.memeasyfree += info.bufmem;
421         }
422 }
423
424 /* Ohkie to return negative values for temperatures */
425 int round_to_int_temp(float f)
426 {
427         if (f >= 0.0) {
428                 return (int) (f + 0.5);
429         } else {
430                 return (int) (f - 0.5);
431         }
432 }
433 /* Don't return negative values for cpugraph, bar, gauge, percentage.
434  * Causes unreasonable numbers to show */
435 unsigned int round_to_int(float f)
436 {
437         if (f >= 0.0) {
438                 return (int) (f + 0.5);
439         } else {
440                 return 0;
441         }
442 }
443
444 void scan_loadavg_arg(struct text_object *obj, const char *arg)
445 {
446         obj->data.i = 0;
447         if (arg && !arg[1] && isdigit(arg[0])) {
448                 obj->data.i = atoi(arg);
449                 if (obj->data.i > 3 || obj->data.i < 1) {
450                         NORM_ERR("loadavg arg needs to be in range (1,3)");
451                         obj->data.i = 0;
452                 }
453         }
454         /* convert to array index (or the default (-1)) */
455         obj->data.i--;
456 }
457
458 void print_loadavg(struct text_object *obj, char *p, int p_max_size)
459 {
460         float *v = info.loadavg;
461
462         if (obj->data.i < 0) {
463                 snprintf(p, p_max_size, "%.2f %.2f %.2f", v[0], v[1], v[2]);
464         } else {
465                 snprintf(p, p_max_size, "%.2f", v[obj->data.i]);
466         }
467 }
468
469 #ifdef X11
470 void scan_loadgraph_arg(struct text_object *obj, const char *arg)
471 {
472         char *buf = 0;
473
474         buf = scan_graph(obj, arg, 0);
475         if (buf)
476                 free(buf);
477 }
478
479 void print_loadgraph(struct text_object *obj, char *p, int p_max_size)
480 {
481         new_graph(obj, p, p_max_size, info.loadavg[0]);
482 }
483 #endif /* X11 */