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 "plugin.h"
30 #include "utils/common/common.h"
31 
32 #include "utils/cmds/flush.h"
33 #include "utils/cmds/getthreshold.h"
34 #include "utils/cmds/getval.h"
35 #include "utils/cmds/listval.h"
36 #include "utils/cmds/putnotif.h"
37 #include "utils/cmds/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;
59 
60 /* socket configuration */
61 static int sock_fd = -1;
62 static char *sock_file;
63 static char *sock_group;
64 static int sock_perms = S_IRWXU | S_IRWXG;
65 static bool delete_socket;
66 
67 static pthread_t listen_thread = (pthread_t)0;
68 
69 /*
70  * Functions
71  */
us_open_socket(void)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     ERROR("unixsock plugin: socket failed: %s", STRERRNO);
79     return -1;
80   }
81 
82   sa.sun_family = AF_UNIX;
83   sstrncpy(sa.sun_path, (sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
84            sizeof(sa.sun_path));
85 
86   DEBUG("unixsock plugin: socket path = %s", sa.sun_path);
87 
88   if (delete_socket) {
89     errno = 0;
90     status = unlink(sa.sun_path);
91     if ((status != 0) && (errno != ENOENT)) {
92       WARNING("unixsock plugin: Deleting socket file \"%s\" failed: %s",
93               sa.sun_path, STRERRNO);
94     } else if (status == 0) {
95       INFO("unixsock plugin: Successfully deleted socket file \"%s\".",
96            sa.sun_path);
97     }
98   }
99 
100   status = bind(sock_fd, (struct sockaddr *)&sa, sizeof(sa));
101   if (status != 0) {
102     ERROR("unixsock plugin: bind failed: %s", STRERRNO);
103     close(sock_fd);
104     sock_fd = -1;
105     return -1;
106   }
107 
108   status = chmod(sa.sun_path, sock_perms);
109   if (status == -1) {
110     ERROR("unixsock plugin: chmod failed: %s", STRERRNO);
111     close(sock_fd);
112     sock_fd = -1;
113     return -1;
114   }
115 
116   status = listen(sock_fd, 8);
117   if (status != 0) {
118     ERROR("unixsock plugin: listen failed: %s", STRERRNO);
119     close(sock_fd);
120     sock_fd = -1;
121     return -1;
122   }
123 
124   do {
125     const char *grpname;
126     struct group *g;
127     struct group sg;
128 
129     long int grbuf_size = sysconf(_SC_GETGR_R_SIZE_MAX);
130     if (grbuf_size <= 0)
131       grbuf_size = sysconf(_SC_PAGESIZE);
132     if (grbuf_size <= 0)
133       grbuf_size = 4096;
134     char grbuf[grbuf_size];
135 
136     grpname = (sock_group != NULL) ? sock_group : COLLECTD_GRP_NAME;
137     g = NULL;
138 
139     status = getgrnam_r(grpname, &sg, grbuf, sizeof(grbuf), &g);
140     if (status != 0) {
141       WARNING("unixsock plugin: getgrnam_r (%s) failed: %s", grpname,
142               STRERROR(status));
143       break;
144     }
145     if (g == NULL) {
146       WARNING("unixsock plugin: No such group: `%s'", grpname);
147       break;
148     }
149 
150     if (chown((sock_file != NULL) ? sock_file : US_DEFAULT_PATH, (uid_t)-1,
151               g->gr_gid) != 0) {
152       WARNING("unixsock plugin: chown (%s, -1, %i) failed: %s",
153               (sock_file != NULL) ? sock_file : US_DEFAULT_PATH, (int)g->gr_gid,
154               STRERRNO);
155     }
156   } while (0);
157 
158   return 0;
159 } /* int us_open_socket */
160 
us_handle_client(void * arg)161 static void *us_handle_client(void *arg) {
162   int fdin;
163   int fdout;
164   FILE *fhin, *fhout;
165 
166   fdin = *((int *)arg);
167   free(arg);
168   arg = NULL;
169 
170   DEBUG("unixsock plugin: us_handle_client: Reading from fd #%i", fdin);
171 
172   fdout = dup(fdin);
173   if (fdout < 0) {
174     ERROR("unixsock plugin: dup failed: %s", STRERRNO);
175     close(fdin);
176     pthread_exit((void *)1);
177   }
178 
179   fhin = fdopen(fdin, "r");
180   if (fhin == NULL) {
181     ERROR("unixsock plugin: fdopen failed: %s", STRERRNO);
182     close(fdin);
183     close(fdout);
184     pthread_exit((void *)1);
185     return (void *)1;
186   }
187 
188   fhout = fdopen(fdout, "w");
189   if (fhout == NULL) {
190     ERROR("unixsock plugin: fdopen failed: %s", STRERRNO);
191     fclose(fhin); /* this closes fdin as well */
192     close(fdout);
193     pthread_exit((void *)1);
194     return (void *)1;
195   }
196 
197   /* change output buffer to line buffered mode */
198   if (setvbuf(fhout, NULL, _IOLBF, 0) != 0) {
199     ERROR("unixsock plugin: setvbuf failed: %s", STRERRNO);
200     fclose(fhin);
201     fclose(fhout);
202     pthread_exit((void *)1);
203     return (void *)0;
204   }
205 
206   while (42) {
207     char buffer[1024];
208     char buffer_copy[1024];
209     char *fields[128];
210     int fields_num;
211 
212     errno = 0;
213     if (fgets(buffer, sizeof(buffer), fhin) == NULL) {
214       if ((errno == EINTR) || (errno == EAGAIN))
215         continue;
216 
217       if (errno != 0) {
218         WARNING("unixsock plugin: failed to read from socket #%i: %s",
219                 fileno(fhin), STRERRNO);
220       }
221       break;
222     }
223 
224     size_t len = strlen(buffer);
225     while ((len > 0) &&
226            ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r')))
227       buffer[--len] = '\0';
228 
229     if (len == 0)
230       continue;
231 
232     sstrncpy(buffer_copy, buffer, sizeof(buffer_copy));
233 
234     fields_num =
235         strsplit(buffer_copy, fields, sizeof(fields) / sizeof(fields[0]));
236     if (fields_num < 1) {
237       fprintf(fhout, "-1 Internal error\n");
238       fclose(fhin);
239       fclose(fhout);
240       pthread_exit((void *)1);
241       return (void *)1;
242     }
243 
244     if (strcasecmp(fields[0], "getval") == 0) {
245       cmd_handle_getval(fhout, buffer);
246     } else if (strcasecmp(fields[0], "getthreshold") == 0) {
247       handle_getthreshold(fhout, buffer);
248     } else if (strcasecmp(fields[0], "putval") == 0) {
249       cmd_handle_putval(fhout, buffer);
250     } else if (strcasecmp(fields[0], "listval") == 0) {
251       cmd_handle_listval(fhout, buffer);
252     } else if (strcasecmp(fields[0], "putnotif") == 0) {
253       handle_putnotif(fhout, buffer);
254     } else if (strcasecmp(fields[0], "flush") == 0) {
255       cmd_handle_flush(fhout, buffer);
256     } else {
257       if (fprintf(fhout, "-1 Unknown command: %s\n", fields[0]) < 0) {
258         WARNING("unixsock plugin: failed to write to socket #%i: %s",
259                 fileno(fhout), STRERRNO);
260         break;
261       }
262     }
263   } /* while (fgets) */
264 
265   DEBUG("unixsock plugin: us_handle_client: Exiting..");
266   fclose(fhin);
267   fclose(fhout);
268 
269   pthread_exit((void *)0);
270   return (void *)0;
271 } /* void *us_handle_client */
272 
us_server_thread(void * arg)273 static void *us_server_thread(void __attribute__((unused)) * arg) {
274   int status;
275   int *remote_fd;
276   pthread_t th;
277 
278   if (us_open_socket() != 0)
279     pthread_exit((void *)1);
280 
281   while (loop != 0) {
282     DEBUG("unixsock plugin: Calling accept..");
283     status = accept(sock_fd, NULL, NULL);
284     if (status < 0) {
285 
286       if (errno == EINTR)
287         continue;
288 
289       ERROR("unixsock plugin: accept failed: %s", STRERRNO);
290       close(sock_fd);
291       sock_fd = -1;
292       pthread_exit((void *)1);
293     }
294 
295     remote_fd = malloc(sizeof(*remote_fd));
296     if (remote_fd == NULL) {
297       WARNING("unixsock plugin: malloc failed: %s", STRERRNO);
298       close(status);
299       continue;
300     }
301     *remote_fd = status;
302 
303     DEBUG("Spawning child to handle connection on fd #%i", *remote_fd);
304 
305     status = plugin_thread_create(&th, us_handle_client, (void *)remote_fd,
306                                   "unixsock conn");
307     if (status == 0) {
308       pthread_detach(th);
309     } else {
310       WARNING("unixsock plugin: pthread_create failed: %s", STRERRNO);
311       close(*remote_fd);
312       free(remote_fd);
313       continue;
314     }
315   } /* while (loop) */
316 
317   close(sock_fd);
318   sock_fd = -1;
319 
320   status = unlink((sock_file != NULL) ? sock_file : US_DEFAULT_PATH);
321   if (status != 0) {
322     NOTICE("unixsock plugin: unlink (%s) failed: %s",
323            (sock_file != NULL) ? sock_file : US_DEFAULT_PATH, STRERRNO);
324   }
325 
326   return (void *)0;
327 } /* void *us_server_thread */
328 
us_config(const char * key,const char * val)329 static int us_config(const char *key, const char *val) {
330   if (strcasecmp(key, "SocketFile") == 0) {
331     char *new_sock_file = strdup(val);
332     if (new_sock_file == NULL)
333       return 1;
334 
335     sfree(sock_file);
336     sock_file = new_sock_file;
337   } else if (strcasecmp(key, "SocketGroup") == 0) {
338     char *new_sock_group = strdup(val);
339     if (new_sock_group == NULL)
340       return 1;
341 
342     sfree(sock_group);
343     sock_group = new_sock_group;
344   } else if (strcasecmp(key, "SocketPerms") == 0) {
345     sock_perms = (int)strtol(val, NULL, 8);
346   } else if (strcasecmp(key, "DeleteSocket") == 0) {
347     if (IS_TRUE(val))
348       delete_socket = true;
349     else
350       delete_socket = false;
351   } else {
352     return -1;
353   }
354 
355   return 0;
356 } /* int us_config */
357 
us_init(void)358 static int us_init(void) {
359   static int have_init;
360 
361   int status;
362 
363   /* Initialize only once. */
364   if (have_init != 0)
365     return 0;
366   have_init = 1;
367 
368   loop = 1;
369 
370   status = plugin_thread_create(&listen_thread, us_server_thread, NULL,
371                                 "unixsock listen");
372   if (status != 0) {
373     ERROR("unixsock plugin: pthread_create failed: %s", STRERRNO);
374     return -1;
375   }
376 
377   return 0;
378 } /* int us_init */
379 
us_shutdown(void)380 static int us_shutdown(void) {
381   void *ret;
382 
383   loop = 0;
384 
385   if (listen_thread != (pthread_t)0) {
386     pthread_kill(listen_thread, SIGTERM);
387     pthread_join(listen_thread, &ret);
388     listen_thread = (pthread_t)0;
389   }
390 
391   plugin_unregister_init("unixsock");
392   plugin_unregister_shutdown("unixsock");
393 
394   return 0;
395 } /* int us_shutdown */
396 
module_register(void)397 void module_register(void) {
398   plugin_register_config("unixsock", us_config, config_keys, config_keys_num);
399   plugin_register_init("unixsock", us_init);
400   plugin_register_shutdown("unixsock", us_shutdown);
401 } /* void module_register (void) */
402