Merge branch 'collectd-5.7' into collectd-5.8
[collectd.git] / src / unixsock.c
1 /**
2  * collectd - src/unixsock.c
3  * Copyright (C) 2007,2008  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  **/
26
27 #include "collectd.h"
28
29 #include "common.h"
30 #include "plugin.h"
31
32 #include "utils_cmd_flush.h"
33 #include "utils_cmd_getthreshold.h"
34 #include "utils_cmd_getval.h"
35 #include "utils_cmd_listval.h"
36 #include "utils_cmd_putnotif.h"
37 #include "utils_cmd_putval.h"
38
39 #include <sys/stat.h>
40 #include <sys/un.h>
41
42 #include <grp.h>
43
44 #ifndef UNIX_PATH_MAX
45 #define UNIX_PATH_MAX sizeof(((struct sockaddr_un *)0)->sun_path)
46 #endif
47
48 #define US_DEFAULT_PATH LOCALSTATEDIR "/run/" PACKAGE_NAME "-unixsock"
49
50 /*
51  * Private variables
52  */
53 /* valid configuration file keys */
54 static const char *config_keys[] = {"SocketFile", "SocketGroup", "SocketPerms",
55                                     "DeleteSocket"};
56 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
57
58 static int loop = 0;
59
60 /* socket configuration */
61 static int sock_fd = -1;
62 static char *sock_file = NULL;
63 static char *sock_group = NULL;
64 static int sock_perms = S_IRWXU | S_IRWXG;
65 static _Bool delete_socket = 0;
66
67 static pthread_t listen_thread = (pthread_t)0;
68
69 /*
70  * Functions
71  */
72 static int us_open_socket(void) {
73   struct sockaddr_un sa = {0};
74   int status;
75
76   sock_fd = socket(PF_UNIX, SOCK_STREAM, 0);
77   if (sock_fd < 0) {
78     char errbuf[1024];
79     ERROR("unixsock plugin: socket failed: %s",
80           sstrerror(errno, errbuf, sizeof(errbuf)));
81     return -1;
82   }
83
84   sa.sun_family = AF_UNIX;
85   sstrncpy(sa.sun_path, (sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
86            sizeof(sa.sun_path));
87
88   DEBUG("unixsock plugin: socket path = %s", sa.sun_path);
89
90   if (delete_socket) {
91     errno = 0;
92     status = unlink(sa.sun_path);
93     if ((status != 0) && (errno != ENOENT)) {
94       char errbuf[1024];
95       WARNING("unixsock plugin: Deleting socket file \"%s\" failed: %s",
96               sa.sun_path, sstrerror(errno, errbuf, sizeof(errbuf)));
97     } else if (status == 0) {
98       INFO("unixsock plugin: Successfully deleted socket file \"%s\".",
99            sa.sun_path);
100     }
101   }
102
103   status = bind(sock_fd, (struct sockaddr *)&sa, sizeof(sa));
104   if (status != 0) {
105     char errbuf[1024];
106     sstrerror(errno, errbuf, sizeof(errbuf));
107     ERROR("unixsock plugin: bind failed: %s", errbuf);
108     close(sock_fd);
109     sock_fd = -1;
110     return -1;
111   }
112
113   status = chmod(sa.sun_path, sock_perms);
114   if (status == -1) {
115     char errbuf[1024];
116     ERROR("unixsock plugin: chmod failed: %s",
117           sstrerror(errno, errbuf, sizeof(errbuf)));
118     close(sock_fd);
119     sock_fd = -1;
120     return -1;
121   }
122
123   status = listen(sock_fd, 8);
124   if (status != 0) {
125     char errbuf[1024];
126     ERROR("unixsock plugin: listen failed: %s",
127           sstrerror(errno, errbuf, sizeof(errbuf)));
128     close(sock_fd);
129     sock_fd = -1;
130     return -1;
131   }
132
133   do {
134     const char *grpname;
135     struct group *g;
136     struct group sg;
137
138     long int grbuf_size = sysconf(_SC_GETGR_R_SIZE_MAX);
139     if (grbuf_size <= 0)
140       grbuf_size = sysconf(_SC_PAGESIZE);
141     if (grbuf_size <= 0)
142       grbuf_size = 4096;
143     char grbuf[grbuf_size];
144
145     grpname = (sock_group != NULL) ? sock_group : COLLECTD_GRP_NAME;
146     g = NULL;
147
148     status = getgrnam_r(grpname, &sg, grbuf, sizeof(grbuf), &g);
149     if (status != 0) {
150       char errbuf[1024];
151       WARNING("unixsock plugin: getgrnam_r (%s) failed: %s", grpname,
152               sstrerror(status, errbuf, sizeof(errbuf)));
153       break;
154     }
155     if (g == NULL) {
156       WARNING("unixsock plugin: No such group: `%s'", grpname);
157       break;
158     }
159
160     if (chown((sock_file != NULL) ? sock_file : US_DEFAULT_PATH, (uid_t)-1,
161               g->gr_gid) != 0) {
162       char errbuf[1024];
163       WARNING("unixsock plugin: chown (%s, -1, %i) failed: %s",
164               (sock_file != NULL) ? sock_file : US_DEFAULT_PATH, (int)g->gr_gid,
165               sstrerror(errno, errbuf, sizeof(errbuf)));
166     }
167   } while (0);
168
169   return 0;
170 } /* int us_open_socket */
171
172 static void *us_handle_client(void *arg) {
173   int fdin;
174   int fdout;
175   FILE *fhin, *fhout;
176
177   fdin = *((int *)arg);
178   free(arg);
179   arg = NULL;
180
181   DEBUG("unixsock plugin: us_handle_client: Reading from fd #%i", fdin);
182
183   fdout = dup(fdin);
184   if (fdout < 0) {
185     char errbuf[1024];
186     ERROR("unixsock plugin: dup failed: %s",
187           sstrerror(errno, errbuf, sizeof(errbuf)));
188     close(fdin);
189     pthread_exit((void *)1);
190   }
191
192   fhin = fdopen(fdin, "r");
193   if (fhin == NULL) {
194     char errbuf[1024];
195     ERROR("unixsock plugin: fdopen failed: %s",
196           sstrerror(errno, errbuf, sizeof(errbuf)));
197     close(fdin);
198     close(fdout);
199     pthread_exit((void *)1);
200     return (void *)1;
201   }
202
203   fhout = fdopen(fdout, "w");
204   if (fhout == NULL) {
205     char errbuf[1024];
206     ERROR("unixsock plugin: fdopen failed: %s",
207           sstrerror(errno, errbuf, sizeof(errbuf)));
208     fclose(fhin); /* this closes fdin as well */
209     close(fdout);
210     pthread_exit((void *)1);
211     return (void *)1;
212   }
213
214   /* change output buffer to line buffered mode */
215   if (setvbuf(fhout, NULL, _IOLBF, 0) != 0) {
216     char errbuf[1024];
217     ERROR("unixsock plugin: setvbuf failed: %s",
218           sstrerror(errno, errbuf, sizeof(errbuf)));
219     fclose(fhin);
220     fclose(fhout);
221     pthread_exit((void *)1);
222     return (void *)0;
223   }
224
225   while (42) {
226     char buffer[1024];
227     char buffer_copy[1024];
228     char *fields[128];
229     int fields_num;
230     int len;
231
232     errno = 0;
233     if (fgets(buffer, sizeof(buffer), fhin) == NULL) {
234       if ((errno == EINTR) || (errno == EAGAIN))
235         continue;
236
237       if (errno != 0) {
238         char errbuf[1024];
239         WARNING("unixsock plugin: failed to read from socket #%i: %s",
240                 fileno(fhin), sstrerror(errno, errbuf, sizeof(errbuf)));
241       }
242       break;
243     }
244
245     len = strlen(buffer);
246     while ((len > 0) &&
247            ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r')))
248       buffer[--len] = '\0';
249
250     if (len == 0)
251       continue;
252
253     sstrncpy(buffer_copy, buffer, sizeof(buffer_copy));
254
255     fields_num =
256         strsplit(buffer_copy, fields, sizeof(fields) / sizeof(fields[0]));
257     if (fields_num < 1) {
258       fprintf(fhout, "-1 Internal error\n");
259       fclose(fhin);
260       fclose(fhout);
261       pthread_exit((void *)1);
262       return (void *)1;
263     }
264
265     if (strcasecmp(fields[0], "getval") == 0) {
266       cmd_handle_getval(fhout, buffer);
267     } else if (strcasecmp(fields[0], "getthreshold") == 0) {
268       handle_getthreshold(fhout, buffer);
269     } else if (strcasecmp(fields[0], "putval") == 0) {
270       cmd_handle_putval(fhout, buffer);
271     } else if (strcasecmp(fields[0], "listval") == 0) {
272       cmd_handle_listval(fhout, buffer);
273     } else if (strcasecmp(fields[0], "putnotif") == 0) {
274       handle_putnotif(fhout, buffer);
275     } else if (strcasecmp(fields[0], "flush") == 0) {
276       cmd_handle_flush(fhout, buffer);
277     } else {
278       if (fprintf(fhout, "-1 Unknown command: %s\n", fields[0]) < 0) {
279         char errbuf[1024];
280         WARNING("unixsock plugin: failed to write to socket #%i: %s",
281                 fileno(fhout), sstrerror(errno, errbuf, sizeof(errbuf)));
282         break;
283       }
284     }
285   } /* while (fgets) */
286
287   DEBUG("unixsock plugin: us_handle_client: Exiting..");
288   fclose(fhin);
289   fclose(fhout);
290
291   pthread_exit((void *)0);
292   return (void *)0;
293 } /* void *us_handle_client */
294
295 static void *us_server_thread(void __attribute__((unused)) * arg) {
296   int status;
297   int *remote_fd;
298   pthread_t th;
299   pthread_attr_t th_attr;
300
301   pthread_attr_init(&th_attr);
302   pthread_attr_setdetachstate(&th_attr, PTHREAD_CREATE_DETACHED);
303
304   if (us_open_socket() != 0)
305     pthread_exit((void *)1);
306
307   while (loop != 0) {
308     DEBUG("unixsock plugin: Calling accept..");
309     status = accept(sock_fd, NULL, NULL);
310     if (status < 0) {
311       char errbuf[1024];
312
313       if (errno == EINTR)
314         continue;
315
316       ERROR("unixsock plugin: accept failed: %s",
317             sstrerror(errno, errbuf, sizeof(errbuf)));
318       close(sock_fd);
319       sock_fd = -1;
320       pthread_attr_destroy(&th_attr);
321       pthread_exit((void *)1);
322     }
323
324     remote_fd = malloc(sizeof(*remote_fd));
325     if (remote_fd == NULL) {
326       char errbuf[1024];
327       WARNING("unixsock plugin: malloc failed: %s",
328               sstrerror(errno, errbuf, sizeof(errbuf)));
329       close(status);
330       continue;
331     }
332     *remote_fd = status;
333
334     DEBUG("Spawning child to handle connection on fd #%i", *remote_fd);
335
336     status = plugin_thread_create(&th, &th_attr, us_handle_client,
337                                   (void *)remote_fd, "unixsock conn");
338     if (status != 0) {
339       char errbuf[1024];
340       WARNING("unixsock plugin: pthread_create failed: %s",
341               sstrerror(errno, errbuf, sizeof(errbuf)));
342       close(*remote_fd);
343       free(remote_fd);
344       continue;
345     }
346   } /* while (loop) */
347
348   close(sock_fd);
349   sock_fd = -1;
350   pthread_attr_destroy(&th_attr);
351
352   status = unlink((sock_file != NULL) ? sock_file : US_DEFAULT_PATH);
353   if (status != 0) {
354     char errbuf[1024];
355     NOTICE("unixsock plugin: unlink (%s) failed: %s",
356            (sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
357            sstrerror(errno, errbuf, sizeof(errbuf)));
358   }
359
360   return (void *)0;
361 } /* void *us_server_thread */
362
363 static int us_config(const char *key, const char *val) {
364   if (strcasecmp(key, "SocketFile") == 0) {
365     char *new_sock_file = strdup(val);
366     if (new_sock_file == NULL)
367       return 1;
368
369     sfree(sock_file);
370     sock_file = new_sock_file;
371   } else if (strcasecmp(key, "SocketGroup") == 0) {
372     char *new_sock_group = strdup(val);
373     if (new_sock_group == NULL)
374       return 1;
375
376     sfree(sock_group);
377     sock_group = new_sock_group;
378   } else if (strcasecmp(key, "SocketPerms") == 0) {
379     sock_perms = (int)strtol(val, NULL, 8);
380   } else if (strcasecmp(key, "DeleteSocket") == 0) {
381     if (IS_TRUE(val))
382       delete_socket = 1;
383     else
384       delete_socket = 0;
385   } else {
386     return -1;
387   }
388
389   return 0;
390 } /* int us_config */
391
392 static int us_init(void) {
393   static int have_init = 0;
394
395   int status;
396
397   /* Initialize only once. */
398   if (have_init != 0)
399     return 0;
400   have_init = 1;
401
402   loop = 1;
403
404   status = plugin_thread_create(&listen_thread, NULL, us_server_thread, NULL,
405                                 "unixsock listen");
406   if (status != 0) {
407     char errbuf[1024];
408     ERROR("unixsock plugin: pthread_create failed: %s",
409           sstrerror(errno, errbuf, sizeof(errbuf)));
410     return -1;
411   }
412
413   return 0;
414 } /* int us_init */
415
416 static int us_shutdown(void) {
417   void *ret;
418
419   loop = 0;
420
421   if (listen_thread != (pthread_t)0) {
422     pthread_kill(listen_thread, SIGTERM);
423     pthread_join(listen_thread, &ret);
424     listen_thread = (pthread_t)0;
425   }
426
427   plugin_unregister_init("unixsock");
428   plugin_unregister_shutdown("unixsock");
429
430   return 0;
431 } /* int us_shutdown */
432
433 void module_register(void) {
434   plugin_register_config("unixsock", us_config, config_keys, config_keys_num);
435   plugin_register_init("unixsock", us_init);
436   plugin_register_shutdown("unixsock", us_shutdown);
437 } /* void module_register (void) */