Merge pull request #3329 from efuss/fix-3311
[collectd.git] / src / exec.c
1 /**
2  * collectd - src/exec.c
3  * Copyright (C) 2007-2010  Florian octo Forster
4  * Copyright (C) 2007-2009  Sebastian Harl
5  * Copyright (C) 2008       Peter Holik
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; only version 2 of the License is applicable.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  *
20  * Authors:
21  *   Florian octo Forster <octo at collectd.org>
22  *   Sebastian Harl <sh at tokkee.org>
23  *   Peter Holik <peter at holik.at>
24  **/
25
26 #define _DEFAULT_SOURCE
27 #define _BSD_SOURCE /* For setgroups */
28
29 /* _GNU_SOURCE is needed in Linux to use execvpe */
30 #define _GNU_SOURCE
31
32 #include "collectd.h"
33
34 #include "plugin.h"
35 #include "utils/common/common.h"
36
37 #include "utils/cmds/putnotif.h"
38 #include "utils/cmds/putval.h"
39
40 #include <grp.h>
41 #include <pwd.h>
42 #include <signal.h>
43 #include <sys/types.h>
44
45 #ifdef HAVE_SYS_CAPABILITY_H
46 #include <sys/capability.h>
47 #endif
48
49 extern char **environ;
50
51 #define PL_NORMAL 0x01
52 #define PL_NOTIF_ACTION 0x02
53
54 #define PL_RUNNING 0x10
55
56 /*
57  * Private data types
58  */
59 /*
60  * Access to this structure is serialized using the `pl_lock' lock and the
61  * `PL_RUNNING' flag. The execution of notifications is *not* serialized, so
62  * all functions used to handle notifications MUST NOT write to this structure.
63  * The `pid' and `status' fields are thus unused if the `PL_NOTIF_ACTION' flag
64  * is set.
65  * The `PL_RUNNING' flag is set in `exec_read' and unset in `exec_read_one'.
66  */
67 struct program_list_s;
68 typedef struct program_list_s program_list_t;
69 struct program_list_s {
70   char *user;
71   char *group;
72   char *exec;
73   char **argv;
74   int pid;
75   int status;
76   int flags;
77   program_list_t *next;
78 };
79
80 typedef struct program_list_and_notification_s {
81   program_list_t *pl;
82   notification_t n;
83 } program_list_and_notification_t;
84
85 /*
86  * constants
87  */
88 const long int MAX_GRBUF_SIZE = 65536;
89
90 /*
91  * Private variables
92  */
93 static program_list_t *pl_head;
94 static pthread_mutex_t pl_lock = PTHREAD_MUTEX_INITIALIZER;
95
96 /*
97  * Functions
98  */
99 static void sigchld_handler(int __attribute__((unused)) signal) /* {{{ */
100 {
101   pid_t pid;
102   int status;
103   while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
104     program_list_t *pl;
105     for (pl = pl_head; pl != NULL; pl = pl->next)
106       if (pl->pid == pid)
107         break;
108     if (pl != NULL)
109       pl->status = status;
110   } /* while (waitpid) */
111 } /* void sigchld_handler }}} */
112
113 static int exec_config_exec(oconfig_item_t *ci) /* {{{ */
114 {
115   program_list_t *pl;
116   char buffer[128];
117   int i;
118
119   if (ci->children_num != 0) {
120     WARNING("exec plugin: The config option `%s' may not be a block.", ci->key);
121     return -1;
122   }
123   if (ci->values_num < 2) {
124     WARNING("exec plugin: The config option `%s' needs at least two "
125             "arguments.",
126             ci->key);
127     return -1;
128   }
129   if ((ci->values[0].type != OCONFIG_TYPE_STRING) ||
130       (ci->values[1].type != OCONFIG_TYPE_STRING)) {
131     WARNING("exec plugin: The first two arguments to the `%s' option must "
132             "be string arguments.",
133             ci->key);
134     return -1;
135   }
136
137   pl = calloc(1, sizeof(*pl));
138   if (pl == NULL) {
139     ERROR("exec plugin: calloc failed.");
140     return -1;
141   }
142
143   if (strcasecmp("NotificationExec", ci->key) == 0)
144     pl->flags |= PL_NOTIF_ACTION;
145   else
146     pl->flags |= PL_NORMAL;
147
148   pl->user = strdup(ci->values[0].value.string);
149   if (pl->user == NULL) {
150     ERROR("exec plugin: strdup failed.");
151     sfree(pl);
152     return -1;
153   }
154
155   pl->group = strchr(pl->user, ':');
156   if (pl->group != NULL) {
157     *pl->group = '\0';
158     pl->group++;
159   }
160
161   pl->exec = strdup(ci->values[1].value.string);
162   if (pl->exec == NULL) {
163     ERROR("exec plugin: strdup failed.");
164     sfree(pl->user);
165     sfree(pl);
166     return -1;
167   }
168
169   pl->argv = calloc(ci->values_num, sizeof(*pl->argv));
170   if (pl->argv == NULL) {
171     ERROR("exec plugin: calloc failed.");
172     sfree(pl->exec);
173     sfree(pl->user);
174     sfree(pl);
175     return -1;
176   }
177
178   {
179     char *tmp = strrchr(ci->values[1].value.string, '/');
180     if (tmp == NULL)
181       sstrncpy(buffer, ci->values[1].value.string, sizeof(buffer));
182     else
183       sstrncpy(buffer, tmp + 1, sizeof(buffer));
184   }
185   pl->argv[0] = strdup(buffer);
186   if (pl->argv[0] == NULL) {
187     ERROR("exec plugin: strdup failed.");
188     sfree(pl->argv);
189     sfree(pl->exec);
190     sfree(pl->user);
191     sfree(pl);
192     return -1;
193   }
194
195   for (i = 1; i < (ci->values_num - 1); i++) {
196     if (ci->values[i + 1].type == OCONFIG_TYPE_STRING) {
197       pl->argv[i] = strdup(ci->values[i + 1].value.string);
198     } else {
199       if (ci->values[i + 1].type == OCONFIG_TYPE_NUMBER) {
200         snprintf(buffer, sizeof(buffer), "%lf", ci->values[i + 1].value.number);
201       } else {
202         if (ci->values[i + 1].value.boolean)
203           sstrncpy(buffer, "true", sizeof(buffer));
204         else
205           sstrncpy(buffer, "false", sizeof(buffer));
206       }
207
208       pl->argv[i] = strdup(buffer);
209     }
210
211     if (pl->argv[i] == NULL) {
212       ERROR("exec plugin: strdup failed.");
213       break;
214     }
215   } /* for (i) */
216
217   if (i < (ci->values_num - 1)) {
218     while ((--i) >= 0) {
219       sfree(pl->argv[i]);
220     }
221     sfree(pl->argv);
222     sfree(pl->exec);
223     sfree(pl->user);
224     sfree(pl);
225     return -1;
226   }
227
228   for (i = 0; pl->argv[i] != NULL; i++) {
229     DEBUG("exec plugin: argv[%i] = %s", i, pl->argv[i]);
230   }
231
232   pl->next = pl_head;
233   pl_head = pl;
234
235   return 0;
236 } /* int exec_config_exec }}} */
237
238 static int exec_config(oconfig_item_t *ci) /* {{{ */
239 {
240   for (int i = 0; i < ci->children_num; i++) {
241     oconfig_item_t *child = ci->children + i;
242     if ((strcasecmp("Exec", child->key) == 0) ||
243         (strcasecmp("NotificationExec", child->key) == 0))
244       exec_config_exec(child);
245     else {
246       WARNING("exec plugin: Unknown config option `%s'.", child->key);
247     }
248   } /* for (i) */
249
250   return 0;
251 } /* int exec_config }}} */
252
253 __attribute__((noreturn)) static void exec_child(program_list_t *pl,
254                                                  char **envp, int uid, int gid,
255                                                  int egid) /* {{{ */
256 {
257   int status;
258
259 #if HAVE_SETGROUPS
260   if (getuid() == 0) {
261     gid_t glist[2];
262     size_t glist_len;
263
264     glist[0] = gid;
265     glist_len = 1;
266
267     if ((gid != egid) && (egid != -1)) {
268       glist[1] = egid;
269       glist_len = 2;
270     }
271
272     setgroups(glist_len, glist);
273   }
274 #endif /* HAVE_SETGROUPS */
275
276   status = setgid(gid);
277   if (status != 0) {
278     ERROR("exec plugin: setgid (%i) failed: %s", gid, STRERRNO);
279     exit(-1);
280   }
281
282   if (egid != -1) {
283     status = setegid(egid);
284     if (status != 0) {
285       ERROR("exec plugin: setegid (%i) failed: %s", egid, STRERRNO);
286       exit(-1);
287     }
288   }
289
290   status = setuid(uid);
291   if (status != 0) {
292     ERROR("exec plugin: setuid (%i) failed: %s", uid, STRERRNO);
293     exit(-1);
294   }
295
296 #ifdef HAVE_EXECVPE
297   execvpe(pl->exec, pl->argv, envp);
298 #else
299   environ = envp;
300   execvp(pl->exec, pl->argv);
301 #endif
302
303   ERROR("exec plugin: Failed to execute ``%s'': %s", pl->exec, STRERRNO);
304   exit(-1);
305 } /* void exec_child }}} */
306
307 static void reset_signal_mask(void) /* {{{ */
308 {
309   sigset_t ss;
310
311   sigemptyset(&ss);
312   sigprocmask(SIG_SETMASK, &ss, /* old mask = */ NULL);
313 } /* }}} void reset_signal_mask */
314
315 static int create_pipe(int fd_pipe[2]) /* {{{ */
316 {
317   int status;
318
319   status = pipe(fd_pipe);
320   if (status != 0) {
321     ERROR("exec plugin: pipe failed: %s", STRERRNO);
322     return -1;
323   }
324
325   return 0;
326 } /* }}} int create_pipe */
327
328 static void close_pipe(int fd_pipe[2]) /* {{{ */
329 {
330   if (fd_pipe[0] != -1)
331     close(fd_pipe[0]);
332
333   if (fd_pipe[1] != -1)
334     close(fd_pipe[1]);
335 } /* }}} void close_pipe */
336
337 /*
338  * Get effective group ID from group name.
339  * Input arguments:
340  *       pl  :program list struct with group name
341  *       gid :group id to fallback in case egid cannot be determined.
342  * Returns:
343  *       egid effective group id if successfull,
344  *            -1 if group is not defined/not found.
345  *            -2 for any buffer allocation error.
346  */
347 static int getegr_id(program_list_t *pl, int gid) /* {{{ */
348 {
349   if (pl->group == NULL) {
350     return -1;
351   }
352   if (strcmp(pl->group, "") == 0) {
353     return gid;
354   }
355   struct group *gr_ptr = NULL;
356   struct group gr;
357
358   long int grbuf_size = sysconf(_SC_GETGR_R_SIZE_MAX);
359   if (grbuf_size <= 0)
360     grbuf_size = sysconf(_SC_PAGESIZE);
361   if (grbuf_size <= 0)
362     grbuf_size = 4096;
363
364   char *temp = NULL;
365   char *grbuf = NULL;
366
367   do {
368     temp = realloc(grbuf, grbuf_size);
369     if (temp == NULL) {
370       ERROR("exec plugin: getegr_id for %s: realloc buffer[%ld] failed ",
371             pl->group, grbuf_size);
372       sfree(grbuf);
373       return -2;
374     }
375     grbuf = temp;
376     if (getgrnam_r(pl->group, &gr, grbuf, grbuf_size, &gr_ptr) == 0) {
377       sfree(grbuf);
378       if (gr_ptr == NULL) {
379         ERROR("exec plugin: No such group: `%s'", pl->group);
380         return -1;
381       }
382       return gr.gr_gid;
383     } else if (errno == ERANGE) {
384       grbuf_size += grbuf_size; // increment buffer size and try again
385     } else {
386       ERROR("exec plugin: getegr_id failed %s", STRERRNO);
387       sfree(grbuf);
388       return -2;
389     }
390   } while (grbuf_size <= MAX_GRBUF_SIZE);
391   ERROR("exec plugin: getegr_id Max grbuf size reached  for %s", pl->group);
392   sfree(grbuf);
393   return -2;
394 }
395
396 /*
397  * Creates three pipes (one for reading, one for writing and one for errors),
398  * forks a child, sets up the pipes so that fd_in is connected to STDIN of
399  * the child and fd_out is connected to STDOUT and fd_err is connected to STDERR
400  * of the child. Then is calls `exec_child'.
401  */
402 static int fork_child(program_list_t *pl, int *fd_in, int *fd_out,
403                       int *fd_err) /* {{{ */
404 {
405   int fd_pipe_in[2] = {-1, -1};
406   int fd_pipe_out[2] = {-1, -1};
407   int fd_pipe_err[2] = {-1, -1};
408   int status;
409   int pid;
410
411   int uid;
412   int gid;
413   int egid;
414
415   struct passwd *sp_ptr;
416   struct passwd sp;
417
418   if (pl->pid != 0)
419     return -1;
420
421   long int nambuf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
422   if (nambuf_size <= 0)
423     nambuf_size = sysconf(_SC_PAGESIZE);
424   if (nambuf_size <= 0)
425     nambuf_size = 4096;
426   char nambuf[nambuf_size];
427
428   if ((create_pipe(fd_pipe_in) == -1) || (create_pipe(fd_pipe_out) == -1) ||
429       (create_pipe(fd_pipe_err) == -1))
430     goto failed;
431
432   sp_ptr = NULL;
433   status = getpwnam_r(pl->user, &sp, nambuf, sizeof(nambuf), &sp_ptr);
434   if (status != 0) {
435     ERROR("exec plugin: Failed to get user information for user ``%s'': %s",
436           pl->user, STRERROR(status));
437     goto failed;
438   }
439
440   if (sp_ptr == NULL) {
441     ERROR("exec plugin: No such user: `%s'", pl->user);
442     goto failed;
443   }
444
445   uid = sp.pw_uid;
446   gid = sp.pw_gid;
447   if (uid == 0) {
448     ERROR("exec plugin: Cowardly refusing to exec program as root.");
449     goto failed;
450   }
451
452   /* The group configured in the configfile is set as effective group, because
453    * this way the forked process can (re-)gain the user's primary group. */
454   egid = getegr_id(pl, gid);
455   if (egid == -2) {
456     goto failed;
457   }
458
459   double interval = CDTIME_T_TO_DOUBLE(plugin_get_interval());
460
461   pid = fork();
462   if (pid < 0) {
463     ERROR("exec plugin: fork failed: %s", STRERRNO);
464     goto failed;
465   } else if (pid == 0) {
466     char interval_buf[128];
467     snprintf(interval_buf, sizeof(interval_buf), "COLLECTD_INTERVAL=%.3f",
468              interval);
469
470     /* max hostname len is 255, so this should be enough */
471     char hostname_buf[300];
472     snprintf(hostname_buf, sizeof(hostname_buf), "COLLECTD_HOSTNAME=%s",
473              hostname_g);
474
475     size_t env_size = 0;
476     while (environ[env_size] != NULL) {
477       ++env_size;
478     }
479
480     /* Copy the environment variables */
481     char *envp[env_size + 3];
482     size_t envp_idx;
483     for (envp_idx = 0; environ[envp_idx] != NULL && envp_idx < env_size;
484          ++envp_idx) {
485       envp[envp_idx] = environ[envp_idx];
486     }
487
488     /* Add the collectd environment variables */
489     envp[envp_idx++] = interval_buf;
490     envp[envp_idx++] = hostname_buf;
491     envp[envp_idx++] = NULL;
492
493     /* Close all file descriptors but the pipe end we need. */
494     int fd_num = getdtablesize();
495     for (int fd = 0; fd < fd_num; fd++) {
496       if ((fd == fd_pipe_in[0]) || (fd == fd_pipe_out[1]) ||
497           (fd == fd_pipe_err[1]))
498         continue;
499       close(fd);
500     }
501
502     /* Connect the `in' pipe to STDIN */
503     if (fd_pipe_in[0] != STDIN_FILENO) {
504       dup2(fd_pipe_in[0], STDIN_FILENO);
505       close(fd_pipe_in[0]);
506     }
507
508     /* Now connect the `out' pipe to STDOUT */
509     if (fd_pipe_out[1] != STDOUT_FILENO) {
510       dup2(fd_pipe_out[1], STDOUT_FILENO);
511       close(fd_pipe_out[1]);
512     }
513
514     /* Now connect the `err' pipe to STDERR */
515     if (fd_pipe_err[1] != STDERR_FILENO) {
516       dup2(fd_pipe_err[1], STDERR_FILENO);
517       close(fd_pipe_err[1]);
518     }
519
520     /* Unblock all signals */
521     reset_signal_mask();
522
523     exec_child(pl, envp, uid, gid, egid);
524     /* does not return */
525   }
526
527   close(fd_pipe_in[0]);
528   close(fd_pipe_out[1]);
529   close(fd_pipe_err[1]);
530
531   if (fd_in != NULL)
532     *fd_in = fd_pipe_in[1];
533   else
534     close(fd_pipe_in[1]);
535
536   if (fd_out != NULL)
537     *fd_out = fd_pipe_out[0];
538   else
539     close(fd_pipe_out[0]);
540
541   if (fd_err != NULL)
542     *fd_err = fd_pipe_err[0];
543   else
544     close(fd_pipe_err[0]);
545
546   return pid;
547
548 failed:
549   close_pipe(fd_pipe_in);
550   close_pipe(fd_pipe_out);
551   close_pipe(fd_pipe_err);
552
553   return -1;
554 } /* int fork_child }}} */
555
556 static int parse_line(char *buffer) /* {{{ */
557 {
558   if (strncasecmp("PUTVAL", buffer, strlen("PUTVAL")) == 0)
559     return cmd_handle_putval(stdout, buffer);
560   else if (strncasecmp("PUTNOTIF", buffer, strlen("PUTNOTIF")) == 0)
561     return handle_putnotif(stdout, buffer);
562   else {
563     ERROR("exec plugin: Unable to parse command, ignoring line: \"%s\"",
564           buffer);
565     return -1;
566   }
567 } /* int parse_line }}} */
568
569 static void *exec_read_one(void *arg) /* {{{ */
570 {
571   program_list_t *pl = (program_list_t *)arg;
572   int fd, fd_err, highest_fd;
573   fd_set fdset, copy;
574   int status;
575   char buffer[1200]; /* if not completely read */
576   char buffer_err[1024];
577   char *pbuffer = buffer;
578   char *pbuffer_err = buffer_err;
579
580   status = fork_child(pl, NULL, &fd, &fd_err);
581   if (status < 0) {
582     /* Reset the "running" flag */
583     pthread_mutex_lock(&pl_lock);
584     pl->flags &= ~PL_RUNNING;
585     pthread_mutex_unlock(&pl_lock);
586     pthread_exit((void *)1);
587   }
588   pl->pid = status;
589
590   assert(pl->pid != 0);
591
592   FD_ZERO(&fdset);
593   FD_SET(fd, &fdset);
594   FD_SET(fd_err, &fdset);
595
596   /* Determine the highest file descriptor */
597   highest_fd = (fd > fd_err) ? fd : fd_err;
598
599   /* We use a copy of fdset, as select modifies it */
600   copy = fdset;
601
602   while (1) {
603     int len;
604
605     status = select(highest_fd + 1, &copy, NULL, NULL, NULL);
606     if (status < 0) {
607       if (errno == EINTR)
608         continue;
609       break;
610     }
611
612     if (FD_ISSET(fd, &copy)) {
613       char *pnl;
614
615       len = read(fd, pbuffer, sizeof(buffer) - 1 - (pbuffer - buffer));
616
617       if (len < 0) {
618         if (errno == EAGAIN || errno == EINTR)
619           continue;
620         break;
621       } else if (len == 0)
622         break; /* We've reached EOF */
623
624       pbuffer[len] = '\0';
625
626       len += pbuffer - buffer;
627       pbuffer = buffer;
628
629       while ((pnl = strchr(pbuffer, '\n'))) {
630         *pnl = '\0';
631         if (*(pnl - 1) == '\r')
632           *(pnl - 1) = '\0';
633
634         parse_line(pbuffer);
635
636         pbuffer = ++pnl;
637       }
638       /* not completely read ? */
639       if (pbuffer - buffer < len) {
640         len -= pbuffer - buffer;
641         memmove(buffer, pbuffer, len);
642         pbuffer = buffer + len;
643       } else
644         pbuffer = buffer;
645     } else if (FD_ISSET(fd_err, &copy)) {
646       char *pnl;
647
648       len = read(fd_err, pbuffer_err,
649                  sizeof(buffer_err) - 1 - (pbuffer_err - buffer_err));
650
651       if (len < 0) {
652         if (errno == EAGAIN || errno == EINTR)
653           continue;
654         break;
655       } else if (len == 0) {
656         /* We've reached EOF */
657         NOTICE("exec plugin: Program `%s' has closed STDERR.", pl->exec);
658
659         /* Remove file descriptor form select() set. */
660         FD_CLR(fd_err, &fdset);
661         copy = fdset;
662         highest_fd = fd;
663
664         /* Clean up file descriptor */
665         close(fd_err);
666         fd_err = -1;
667         continue;
668       }
669
670       pbuffer_err[len] = '\0';
671
672       len += pbuffer_err - buffer_err;
673       pbuffer_err = buffer_err;
674
675       while ((pnl = strchr(pbuffer_err, '\n'))) {
676         *pnl = '\0';
677         if (*(pnl - 1) == '\r')
678           *(pnl - 1) = '\0';
679
680         ERROR("exec plugin: exec_read_one: error = %s", pbuffer_err);
681
682         pbuffer_err = ++pnl;
683       }
684       /* not completely read ? */
685       if (pbuffer_err - buffer_err < len) {
686         len -= pbuffer_err - buffer_err;
687         memmove(buffer_err, pbuffer_err, len);
688         pbuffer_err = buffer_err + len;
689       } else
690         pbuffer_err = buffer_err;
691     }
692     /* reset copy */
693     copy = fdset;
694   }
695
696   DEBUG("exec plugin: exec_read_one: Waiting for `%s' to exit.", pl->exec);
697   if (waitpid(pl->pid, &status, 0) > 0)
698     pl->status = status;
699
700   DEBUG("exec plugin: Child %i exited with status %i.", (int)pl->pid,
701         pl->status);
702
703   pl->pid = 0;
704
705   pthread_mutex_lock(&pl_lock);
706   pl->flags &= ~PL_RUNNING;
707   pthread_mutex_unlock(&pl_lock);
708
709   close(fd);
710   if (fd_err >= 0)
711     close(fd_err);
712
713   pthread_exit((void *)0);
714   return NULL;
715 } /* void *exec_read_one }}} */
716
717 static void *exec_notification_one(void *arg) /* {{{ */
718 {
719   program_list_t *pl = ((program_list_and_notification_t *)arg)->pl;
720   notification_t *n = &((program_list_and_notification_t *)arg)->n;
721   int fd;
722   FILE *fh;
723   int pid;
724   int status;
725   const char *severity;
726
727   pid = fork_child(pl, &fd, NULL, NULL);
728   if (pid < 0) {
729     sfree(arg);
730     pthread_exit((void *)1);
731   }
732
733   fh = fdopen(fd, "w");
734   if (fh == NULL) {
735     ERROR("exec plugin: fdopen (%i) failed: %s", fd, STRERRNO);
736     kill(pid, SIGTERM);
737     close(fd);
738     sfree(arg);
739     pthread_exit((void *)1);
740   }
741
742   severity = "FAILURE";
743   if (n->severity == NOTIF_WARNING)
744     severity = "WARNING";
745   else if (n->severity == NOTIF_OKAY)
746     severity = "OKAY";
747
748   fprintf(fh,
749           "Severity: %s\n"
750           "Time: %.3f\n",
751           severity, CDTIME_T_TO_DOUBLE(n->time));
752
753   /* Print the optional fields */
754   if (strlen(n->host) > 0)
755     fprintf(fh, "Host: %s\n", n->host);
756   if (strlen(n->plugin) > 0)
757     fprintf(fh, "Plugin: %s\n", n->plugin);
758   if (strlen(n->plugin_instance) > 0)
759     fprintf(fh, "PluginInstance: %s\n", n->plugin_instance);
760   if (strlen(n->type) > 0)
761     fprintf(fh, "Type: %s\n", n->type);
762   if (strlen(n->type_instance) > 0)
763     fprintf(fh, "TypeInstance: %s\n", n->type_instance);
764
765   for (notification_meta_t *meta = n->meta; meta != NULL; meta = meta->next) {
766     if (meta->type == NM_TYPE_STRING)
767       fprintf(fh, "%s: %s\n", meta->name, meta->nm_value.nm_string);
768     else if (meta->type == NM_TYPE_SIGNED_INT)
769       fprintf(fh, "%s: %" PRIi64 "\n", meta->name,
770               meta->nm_value.nm_signed_int);
771     else if (meta->type == NM_TYPE_UNSIGNED_INT)
772       fprintf(fh, "%s: %" PRIu64 "\n", meta->name,
773               meta->nm_value.nm_unsigned_int);
774     else if (meta->type == NM_TYPE_DOUBLE)
775       fprintf(fh, "%s: %e\n", meta->name, meta->nm_value.nm_double);
776     else if (meta->type == NM_TYPE_BOOLEAN)
777       fprintf(fh, "%s: %s\n", meta->name,
778               meta->nm_value.nm_boolean ? "true" : "false");
779   }
780
781   fprintf(fh, "\n%s\n", n->message);
782
783   fflush(fh);
784   fclose(fh);
785
786   waitpid(pid, &status, 0);
787
788   DEBUG("exec plugin: Child %i exited with status %i.", pid, status);
789
790   if (n->meta != NULL)
791     plugin_notification_meta_free(n->meta);
792   n->meta = NULL;
793   sfree(arg);
794   pthread_exit((void *)0);
795   return NULL;
796 } /* void *exec_notification_one }}} */
797
798 static int exec_init(void) /* {{{ */
799 {
800   struct sigaction sa = {.sa_handler = sigchld_handler};
801
802   sigaction(SIGCHLD, &sa, NULL);
803
804 #if defined(HAVE_SYS_CAPABILITY_H) && defined(CAP_SETUID) && defined(CAP_SETGID)
805   if ((check_capability(CAP_SETUID) != 0) ||
806       (check_capability(CAP_SETGID) != 0)) {
807     if (getuid() == 0)
808       WARNING(
809           "exec plugin: Running collectd as root, but the CAP_SETUID "
810           "or CAP_SETGID capabilities are missing. The plugin's read function "
811           "will probably fail. Is your init system dropping capabilities?");
812     else
813       WARNING(
814           "exec plugin: collectd doesn't have the CAP_SETUID or "
815           "CAP_SETGID capabilities. If you don't want to run collectd as root, "
816           "try running \"setcap 'cap_setuid=ep cap_setgid=ep'\" on the "
817           "collectd binary.");
818   }
819 #endif
820
821   return 0;
822 } /* int exec_init }}} */
823
824 static int exec_read(void) /* {{{ */
825 {
826   for (program_list_t *pl = pl_head; pl != NULL; pl = pl->next) {
827     pthread_t t;
828     pthread_attr_t attr;
829
830     /* Only execute `normal' style executables here. */
831     if ((pl->flags & PL_NORMAL) == 0)
832       continue;
833
834     pthread_mutex_lock(&pl_lock);
835     /* Skip if a child is already running. */
836     if ((pl->flags & PL_RUNNING) != 0) {
837       pthread_mutex_unlock(&pl_lock);
838       continue;
839     }
840     pl->flags |= PL_RUNNING;
841     pthread_mutex_unlock(&pl_lock);
842
843     pthread_attr_init(&attr);
844     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
845     int status =
846         plugin_thread_create(&t, &attr, exec_read_one, (void *)pl, "exec read");
847     if (status != 0) {
848       ERROR("exec plugin: plugin_thread_create failed.");
849     }
850     pthread_attr_destroy(&attr);
851   } /* for (pl) */
852
853   return 0;
854 } /* int exec_read }}} */
855
856 static int exec_notification(const notification_t *n, /* {{{ */
857                              user_data_t __attribute__((unused)) * user_data) {
858   program_list_and_notification_t *pln;
859
860   for (program_list_t *pl = pl_head; pl != NULL; pl = pl->next) {
861     pthread_t t;
862     pthread_attr_t attr;
863
864     /* Only execute `notification' style executables here. */
865     if ((pl->flags & PL_NOTIF_ACTION) == 0)
866       continue;
867
868     /* Skip if a child is already running. */
869     if (pl->pid != 0)
870       continue;
871
872     pln = malloc(sizeof(*pln));
873     if (pln == NULL) {
874       ERROR("exec plugin: malloc failed.");
875       continue;
876     }
877
878     pln->pl = pl;
879     memcpy(&pln->n, n, sizeof(notification_t));
880
881     /* Set the `meta' member to NULL, otherwise `plugin_notification_meta_copy'
882      * will run into an endless loop. */
883     pln->n.meta = NULL;
884     plugin_notification_meta_copy(&pln->n, n);
885
886     pthread_attr_init(&attr);
887     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
888     int status = plugin_thread_create(&t, &attr, exec_notification_one,
889                                       (void *)pln, "exec notify");
890     if (status != 0) {
891       ERROR("exec plugin: plugin_thread_create failed.");
892     }
893     pthread_attr_destroy(&attr);
894   } /* for (pl) */
895
896   return 0;
897 } /* }}} int exec_notification */
898
899 static int exec_shutdown(void) /* {{{ */
900 {
901   program_list_t *pl;
902   program_list_t *next;
903
904   pl = pl_head;
905   while (pl != NULL) {
906     next = pl->next;
907
908     if (pl->pid > 0) {
909       kill(pl->pid, SIGTERM);
910       INFO("exec plugin: Sent SIGTERM to %hu", (unsigned short int)pl->pid);
911     }
912
913     for (int i = 0; pl->argv[i] != NULL; i++) {
914       sfree(pl->argv[i]);
915     }
916     sfree(pl->argv);
917     sfree(pl->exec);
918     sfree(pl->user);
919     sfree(pl);
920
921     pl = next;
922   } /* while (pl) */
923   pl_head = NULL;
924
925   return 0;
926 } /* int exec_shutdown }}} */
927
928 void module_register(void) {
929   plugin_register_complex_config("exec", exec_config);
930   plugin_register_init("exec", exec_init);
931   plugin_register_read("exec", exec_read);
932   plugin_register_notification("exec", exec_notification,
933                                /* user_data = */ NULL);
934   plugin_register_shutdown("exec", exec_shutdown);
935 } /* void module_register */