Tree wide: Replace sstrerror() with STRERRNO.
[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     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       char errbuf[1024];
142       WARNING("unixsock plugin: getgrnam_r (%s) failed: %s", grpname,
143               sstrerror(status, errbuf, sizeof(errbuf)));
144       break;
145     }
146     if (g == NULL) {
147       WARNING("unixsock plugin: No such group: `%s'", grpname);
148       break;
149     }
150
151     if (chown((sock_file != NULL) ? sock_file : US_DEFAULT_PATH, (uid_t)-1,
152               g->gr_gid) != 0) {
153       WARNING("unixsock plugin: chown (%s, -1, %i) failed: %s",
154               (sock_file != NULL) ? sock_file : US_DEFAULT_PATH, (int)g->gr_gid,
155               STRERRNO);
156     }
157   } while (0);
158
159   return 0;
160 } /* int us_open_socket */
161
162 static void *us_handle_client(void *arg) {
163   int fdin;
164   int fdout;
165   FILE *fhin, *fhout;
166
167   fdin = *((int *)arg);
168   free(arg);
169   arg = NULL;
170
171   DEBUG("unixsock plugin: us_handle_client: Reading from fd #%i", fdin);
172
173   fdout = dup(fdin);
174   if (fdout < 0) {
175     ERROR("unixsock plugin: dup failed: %s", STRERRNO);
176     close(fdin);
177     pthread_exit((void *)1);
178   }
179
180   fhin = fdopen(fdin, "r");
181   if (fhin == NULL) {
182     ERROR("unixsock plugin: fdopen failed: %s", STRERRNO);
183     close(fdin);
184     close(fdout);
185     pthread_exit((void *)1);
186     return (void *)1;
187   }
188
189   fhout = fdopen(fdout, "w");
190   if (fhout == NULL) {
191     ERROR("unixsock plugin: fdopen failed: %s", STRERRNO);
192     fclose(fhin); /* this closes fdin as well */
193     close(fdout);
194     pthread_exit((void *)1);
195     return (void *)1;
196   }
197
198   /* change output buffer to line buffered mode */
199   if (setvbuf(fhout, NULL, _IOLBF, 0) != 0) {
200     ERROR("unixsock plugin: setvbuf failed: %s", STRERRNO);
201     fclose(fhin);
202     fclose(fhout);
203     pthread_exit((void *)1);
204     return (void *)0;
205   }
206
207   while (42) {
208     char buffer[1024];
209     char buffer_copy[1024];
210     char *fields[128];
211     int fields_num;
212     int len;
213
214     errno = 0;
215     if (fgets(buffer, sizeof(buffer), fhin) == NULL) {
216       if ((errno == EINTR) || (errno == EAGAIN))
217         continue;
218
219       if (errno != 0) {
220         WARNING("unixsock plugin: failed to read from socket #%i: %s",
221                 fileno(fhin), STRERRNO);
222       }
223       break;
224     }
225
226     len = strlen(buffer);
227     while ((len > 0) &&
228            ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r')))
229       buffer[--len] = '\0';
230
231     if (len == 0)
232       continue;
233
234     sstrncpy(buffer_copy, buffer, sizeof(buffer_copy));
235
236     fields_num =
237         strsplit(buffer_copy, fields, sizeof(fields) / sizeof(fields[0]));
238     if (fields_num < 1) {
239       fprintf(fhout, "-1 Internal error\n");
240       fclose(fhin);
241       fclose(fhout);
242       pthread_exit((void *)1);
243       return (void *)1;
244     }
245
246     if (strcasecmp(fields[0], "getval") == 0) {
247       cmd_handle_getval(fhout, buffer);
248     } else if (strcasecmp(fields[0], "getthreshold") == 0) {
249       handle_getthreshold(fhout, buffer);
250     } else if (strcasecmp(fields[0], "putval") == 0) {
251       cmd_handle_putval(fhout, buffer);
252     } else if (strcasecmp(fields[0], "listval") == 0) {
253       cmd_handle_listval(fhout, buffer);
254     } else if (strcasecmp(fields[0], "putnotif") == 0) {
255       handle_putnotif(fhout, buffer);
256     } else if (strcasecmp(fields[0], "flush") == 0) {
257       cmd_handle_flush(fhout, buffer);
258     } else {
259       if (fprintf(fhout, "-1 Unknown command: %s\n", fields[0]) < 0) {
260         WARNING("unixsock plugin: failed to write to socket #%i: %s",
261                 fileno(fhout), STRERRNO);
262         break;
263       }
264     }
265   } /* while (fgets) */
266
267   DEBUG("unixsock plugin: us_handle_client: Exiting..");
268   fclose(fhin);
269   fclose(fhout);
270
271   pthread_exit((void *)0);
272   return (void *)0;
273 } /* void *us_handle_client */
274
275 static void *us_server_thread(void __attribute__((unused)) * arg) {
276   int status;
277   int *remote_fd;
278   pthread_t th;
279   pthread_attr_t th_attr;
280
281   pthread_attr_init(&th_attr);
282   pthread_attr_setdetachstate(&th_attr, PTHREAD_CREATE_DETACHED);
283
284   if (us_open_socket() != 0)
285     pthread_exit((void *)1);
286
287   while (loop != 0) {
288     DEBUG("unixsock plugin: Calling accept..");
289     status = accept(sock_fd, NULL, NULL);
290     if (status < 0) {
291
292       if (errno == EINTR)
293         continue;
294
295       ERROR("unixsock plugin: accept failed: %s", STRERRNO);
296       close(sock_fd);
297       sock_fd = -1;
298       pthread_attr_destroy(&th_attr);
299       pthread_exit((void *)1);
300     }
301
302     remote_fd = malloc(sizeof(*remote_fd));
303     if (remote_fd == NULL) {
304       WARNING("unixsock plugin: malloc failed: %s", STRERRNO);
305       close(status);
306       continue;
307     }
308     *remote_fd = status;
309
310     DEBUG("Spawning child to handle connection on fd #%i", *remote_fd);
311
312     status = plugin_thread_create(&th, &th_attr, us_handle_client,
313                                   (void *)remote_fd, "unixsock conn");
314     if (status != 0) {
315       WARNING("unixsock plugin: pthread_create failed: %s", STRERRNO);
316       close(*remote_fd);
317       free(remote_fd);
318       continue;
319     }
320   } /* while (loop) */
321
322   close(sock_fd);
323   sock_fd = -1;
324   pthread_attr_destroy(&th_attr);
325
326   status = unlink((sock_file != NULL) ? sock_file : US_DEFAULT_PATH);
327   if (status != 0) {
328     NOTICE("unixsock plugin: unlink (%s) failed: %s",
329            (sock_file != NULL) ? sock_file : US_DEFAULT_PATH, STRERRNO);
330   }
331
332   return (void *)0;
333 } /* void *us_server_thread */
334
335 static int us_config(const char *key, const char *val) {
336   if (strcasecmp(key, "SocketFile") == 0) {
337     char *new_sock_file = strdup(val);
338     if (new_sock_file == NULL)
339       return 1;
340
341     sfree(sock_file);
342     sock_file = new_sock_file;
343   } else if (strcasecmp(key, "SocketGroup") == 0) {
344     char *new_sock_group = strdup(val);
345     if (new_sock_group == NULL)
346       return 1;
347
348     sfree(sock_group);
349     sock_group = new_sock_group;
350   } else if (strcasecmp(key, "SocketPerms") == 0) {
351     sock_perms = (int)strtol(val, NULL, 8);
352   } else if (strcasecmp(key, "DeleteSocket") == 0) {
353     if (IS_TRUE(val))
354       delete_socket = 1;
355     else
356       delete_socket = 0;
357   } else {
358     return -1;
359   }
360
361   return 0;
362 } /* int us_config */
363
364 static int us_init(void) {
365   static int have_init = 0;
366
367   int status;
368
369   /* Initialize only once. */
370   if (have_init != 0)
371     return 0;
372   have_init = 1;
373
374   loop = 1;
375
376   status = plugin_thread_create(&listen_thread, NULL, us_server_thread, NULL,
377                                 "unixsock listen");
378   if (status != 0) {
379     ERROR("unixsock plugin: pthread_create failed: %s", STRERRNO);
380     return -1;
381   }
382
383   return 0;
384 } /* int us_init */
385
386 static int us_shutdown(void) {
387   void *ret;
388
389   loop = 0;
390
391   if (listen_thread != (pthread_t)0) {
392     pthread_kill(listen_thread, SIGTERM);
393     pthread_join(listen_thread, &ret);
394     listen_thread = (pthread_t)0;
395   }
396
397   plugin_unregister_init("unixsock");
398   plugin_unregister_shutdown("unixsock");
399
400   return 0;
401 } /* int us_shutdown */
402
403 void module_register(void) {
404   plugin_register_config("unixsock", us_config, config_keys, config_keys_num);
405   plugin_register_init("unixsock", us_init);
406   plugin_register_shutdown("unixsock", us_shutdown);
407 } /* void module_register (void) */