libcollectdclient: Implement server code.
[collectd.git] / src / libcollectdclient / server.c
1 /**
2  * Copyright 2017 Florian Forster
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to deal
6  * in the Software without restriction, including without limitation the rights
7  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8  * copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20  * SOFTWARE.
21  *
22  * Authors:
23  *   Florian octo Forster <octo at collectd.org>
24  **/
25
26 #if HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #if !defined(__GNUC__) || !__GNUC__
31 #define __attribute__(x) /**/
32 #endif
33
34 #include "collectd/lcc_features.h"
35 #include "collectd/server.h"
36
37 #include <arpa/inet.h>
38 #include <endian.h>
39 #include <errno.h>
40 #include <inttypes.h>
41 #include <math.h>
42 #include <net/if.h>
43 #include <netdb.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <sys/socket.h>
47 #include <sys/types.h>
48 #include <unistd.h>
49
50 #include <stdio.h>
51 #define DEBUG(...) printf(__VA_ARGS__)
52
53 static _Bool is_multicast(struct addrinfo const *ai) {
54   if (ai->ai_family == AF_INET) {
55     struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
56     return IN_MULTICAST(ntohl(addr->sin_addr.s_addr));
57   } else if (ai->ai_family == AF_INET6) {
58     struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
59     return IN6_IS_ADDR_MULTICAST(&addr->sin6_addr);
60   }
61   return 0;
62 }
63
64 static int server_multicast_join(lcc_listener_t *srv,
65                                  struct sockaddr_storage *group, int loop_back,
66                                  int ttl) {
67   if (group->ss_family == AF_INET) {
68     struct sockaddr_in *sa = (struct sockaddr_in *)group;
69
70     int status = setsockopt(srv->conn, IPPROTO_IP, IP_MULTICAST_LOOP,
71                             &loop_back, sizeof(loop_back));
72     if (status == -1) {
73       DEBUG("setsockopt(IP_MULTICAST_LOOP, %d) = %d\n", loop_back, errno);
74       return errno;
75     }
76
77     status =
78         setsockopt(srv->conn, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
79     if (status == -1)
80       return errno;
81
82 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
83     struct ip_mreqn mreq = {
84         .imr_address.s_addr = INADDR_ANY,
85         .imr_multiaddr.s_addr = sa->sin_addr.s_addr,
86         .imr_ifindex = if_nametoindex(srv->interface),
87     };
88 #else
89     struct ip_mreq mreq = {
90         .imr_address.s_addr = INADDR_ANY, .imr_multiaddr.s_addr = sa->s_addr,
91     };
92 #endif
93     status = setsockopt(srv->conn, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq,
94                         sizeof(mreq));
95     if (status == -1)
96       return errno;
97   } else if (group->ss_family == AF_INET6) {
98     struct sockaddr_in6 *sa = (struct sockaddr_in6 *)group;
99
100     int status = setsockopt(srv->conn, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
101                             &loop_back, sizeof(loop_back));
102     if (status == -1)
103       return errno;
104
105     status = setsockopt(srv->conn, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl,
106                         sizeof(ttl));
107     if (status == -1)
108       return errno;
109
110     struct ipv6_mreq mreq6 = {
111         .ipv6mr_interface = if_nametoindex(srv->interface),
112     };
113     memcpy(&mreq6.ipv6mr_multiaddr, &sa->sin6_addr, sizeof(struct in6_addr));
114
115     status = setsockopt(srv->conn, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6,
116                         sizeof(mreq6));
117     if (status == -1)
118       return errno;
119   } else {
120     return EINVAL;
121   }
122
123   return 0;
124 }
125
126 static int server_bind_socket(lcc_listener_t *srv, struct addrinfo const *ai) {
127   /* allow multiple sockets to use the same PORT number */
128   if (setsockopt(srv->conn, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) ==
129       -1) {
130     return errno;
131   }
132
133   if (bind(srv->conn, ai->ai_addr, ai->ai_addrlen) == -1) {
134     return -1;
135   }
136
137   if (is_multicast(ai)) {
138     int status = server_multicast_join(srv, (void *)ai->ai_addr, /* loop = */ 1,
139                                        /* ttl = */ 16);
140     if (status != 0)
141       return status;
142   }
143
144   return 0;
145 }
146
147 static int server_open(lcc_listener_t *srv) {
148   struct addrinfo *res = NULL;
149   int status = getaddrinfo(srv->node ? srv->node : "::",
150                            srv->service ? srv->service : LCC_DEFAULT_PORT,
151                            &(struct addrinfo){
152                                .ai_flags = AI_ADDRCONFIG,
153                                .ai_family = AF_UNSPEC,
154                                .ai_socktype = SOCK_DGRAM,
155                            },
156                            &res);
157   if (status != 0)
158     return status;
159
160   for (struct addrinfo *ai = res; ai != NULL; ai = ai->ai_next) {
161     srv->conn = socket(ai->ai_family, ai->ai_socktype, 0);
162     if (srv->conn == -1)
163       continue;
164
165     status = server_bind_socket(srv, ai);
166     if (status != 0) {
167       close(srv->conn);
168       srv->conn = -1;
169       continue;
170     }
171
172     break;
173   }
174
175   freeaddrinfo(res);
176
177   if (srv->conn >= 0)
178     return 0;
179   return status != 0 ? status : -1;
180 }
181
182 int lcc_listen_and_write(lcc_listener_t srv) {
183   _Bool close_socket = 0;
184
185   if (srv.conn < 0) {
186     int status = server_open(&srv);
187     if (status != 0)
188       return status;
189     close_socket = 1;
190   }
191
192   if (srv.buffer_size == 0)
193     /* TODO(octo): this should be a define. */
194     srv.buffer_size = 1452;
195
196   int ret = 0;
197   while (42) {
198     char buffer[srv.buffer_size];
199     ssize_t len = recv(srv.conn, buffer, sizeof(buffer), /* flags = */ 0);
200     if (len == -1) {
201       ret = errno;
202       break;
203     } else if (len == 0) {
204       break;
205     }
206
207     /* TODO(octo): implement parse(). */
208     (void)lcc_network_parse(buffer, (size_t)len, srv.writer);
209   }
210
211   if (close_socket) {
212     close(srv.conn);
213     srv.conn = -1;
214   }
215
216   return ret;
217 }
218
219 typedef struct {
220   uint8_t *data;
221   size_t len;
222 } buffer_t;
223
224 static int buffer_next(buffer_t *b, void *out, size_t n) {
225   if (b->len < n) {
226     return -1;
227   }
228   memmove(out, b->data, n);
229
230   b->data += n;
231   b->len -= n;
232
233   return 0;
234 }
235
236 static int buffer_uint16(buffer_t *b, uint16_t *out) {
237   uint16_t tmp;
238   if (buffer_next(b, &tmp, sizeof(tmp)) != 0)
239     return -1;
240
241   *out = be16toh(tmp);
242   return 0;
243 }
244
245 #define TYPE_HOST 0x0000
246 #define TYPE_TIME 0x0001
247 #define TYPE_TIME_HR 0x0008
248 #define TYPE_PLUGIN 0x0002
249 #define TYPE_PLUGIN_INSTANCE 0x0003
250 #define TYPE_TYPE 0x0004
251 #define TYPE_TYPE_INSTANCE 0x0005
252 #define TYPE_VALUES 0x0006
253 #define TYPE_INTERVAL 0x0007
254 #define TYPE_INTERVAL_HR 0x0009
255
256 static int parse_int(void *payload, size_t payload_size, uint64_t *out) {
257   uint64_t tmp;
258
259   if (payload_size != sizeof(tmp))
260     return EINVAL;
261
262   memmove(&tmp, payload, sizeof(tmp));
263   *out = be64toh(tmp);
264   return 0;
265 }
266
267 static int parse_string(void *payload, size_t payload_size, char *out,
268                         size_t out_size) {
269   char *in = payload;
270
271   if ((payload_size < 1) || (in[payload_size - 1] != 0) ||
272       (payload_size > out_size))
273     return EINVAL;
274
275   strncpy(out, in, out_size);
276   return 0;
277 }
278
279 static int parse_identifier(uint16_t type, void *payload, size_t payload_size,
280                             lcc_value_list_t *state) {
281   char buf[LCC_NAME_LEN];
282
283   if (parse_string(payload, payload_size, buf, sizeof(buf)) != 0)
284     return EINVAL;
285
286   switch (type) {
287   case TYPE_HOST:
288     memmove(state->identifier.host, buf, LCC_NAME_LEN);
289     break;
290   case TYPE_PLUGIN:
291     memmove(state->identifier.plugin, buf, LCC_NAME_LEN);
292     break;
293   case TYPE_PLUGIN_INSTANCE:
294     memmove(state->identifier.plugin_instance, buf, LCC_NAME_LEN);
295     break;
296   case TYPE_TYPE:
297     memmove(state->identifier.type, buf, LCC_NAME_LEN);
298     break;
299   case TYPE_TYPE_INSTANCE:
300     memmove(state->identifier.type_instance, buf, LCC_NAME_LEN);
301     break;
302   default:
303     return EINVAL;
304   }
305
306   return 0;
307 }
308
309 static int parse_time(uint16_t type, void *payload, size_t payload_size,
310                       lcc_value_list_t *state) {
311   uint64_t tmp = 0;
312   if (parse_int(payload, payload_size, &tmp))
313     return EINVAL;
314
315   double t = (double)tmp;
316   switch (type) {
317   case TYPE_INTERVAL:
318     state->interval = t;
319     break;
320   case TYPE_INTERVAL_HR:
321     state->interval = t / 1073741824.0;
322     break;
323   case TYPE_TIME:
324     state->time = t;
325     break;
326   case TYPE_TIME_HR:
327     state->time = t / 1073741824.0;
328     break;
329   default:
330     return EINVAL;
331   }
332
333   return 0;
334 }
335
336 static double ntohd(double val) /* {{{ */
337 {
338   static int config = 0;
339
340   union {
341     uint8_t byte[8];
342     double floating;
343   } in = {
344       .floating = val,
345   };
346   union {
347     uint8_t byte[8];
348     double floating;
349   } out = {
350       .byte = {0},
351   };
352
353   if (config == 0) {
354     double d = 8.642135e130;
355     uint8_t b[8];
356
357     memcpy(b, &d, sizeof(b));
358
359     if ((b[0] == 0x2f) && (b[1] == 0x25) && (b[2] == 0xc0) && (b[3] == 0xc7) &&
360         (b[4] == 0x43) && (b[5] == 0x2b) && (b[6] == 0x1f) && (b[7] == 0x5b))
361       config = 1; /* need nothing */
362     else if ((b[7] == 0x2f) && (b[6] == 0x25) && (b[5] == 0xc0) &&
363              (b[4] == 0xc7) && (b[3] == 0x43) && (b[2] == 0x2b) &&
364              (b[1] == 0x1f) && (b[0] == 0x5b))
365       config = 2; /* endian flip */
366     else if ((b[4] == 0x2f) && (b[5] == 0x25) && (b[6] == 0xc0) &&
367              (b[7] == 0xc7) && (b[0] == 0x43) && (b[1] == 0x2b) &&
368              (b[2] == 0x1f) && (b[3] == 0x5b))
369       config = 3; /* int swap */
370     else
371       config = 4;
372   }
373
374   if (memcmp((char[]){0, 0, 0, 0, 0, 0, 0xf8, 0x7f}, in.byte, 8) == 0) {
375     return NAN;
376   } else if (config == 1) {
377     return val;
378   } else if (config == 2) {
379     in.floating = val;
380     out.byte[0] = in.byte[7];
381     out.byte[1] = in.byte[6];
382     out.byte[2] = in.byte[5];
383     out.byte[3] = in.byte[4];
384     out.byte[4] = in.byte[3];
385     out.byte[5] = in.byte[2];
386     out.byte[6] = in.byte[1];
387     out.byte[7] = in.byte[0];
388     return (out.floating);
389   } else if (config == 3) {
390     in.floating = val;
391     out.byte[0] = in.byte[4];
392     out.byte[1] = in.byte[5];
393     out.byte[2] = in.byte[6];
394     out.byte[3] = in.byte[7];
395     out.byte[4] = in.byte[0];
396     out.byte[5] = in.byte[1];
397     out.byte[6] = in.byte[2];
398     out.byte[7] = in.byte[3];
399     return out.floating;
400   } else {
401     /* If in doubt, just copy the value back to the caller. */
402     return val;
403   }
404 } /* }}} double ntohd */
405
406 static int parse_values(void *payload, size_t payload_size,
407                         lcc_value_list_t *state) {
408   buffer_t *b = &(buffer_t){
409       .data = payload, .len = payload_size,
410   };
411
412   uint16_t n;
413   if (buffer_uint16(b, &n))
414     return EINVAL;
415
416   if (((size_t)n * 9) != b->len)
417     return EINVAL;
418
419   state->values_len = (size_t)n;
420   state->values = calloc(sizeof(*state->values), state->values_len);
421   state->values_types = calloc(sizeof(*state->values_types), state->values_len);
422   if ((state->values == NULL) || (state->values_types == NULL)) {
423     free(state->values);
424     free(state->values_types);
425     return ENOMEM;
426   }
427
428   for (uint16_t i = 0; i < n; i++) {
429     uint8_t tmp;
430     if (buffer_next(b, &tmp, sizeof(tmp)))
431       return EINVAL;
432     state->values_types[i] = (int)tmp;
433   }
434
435   for (uint16_t i = 0; i < n; i++) {
436     uint64_t tmp;
437     if (buffer_next(b, &tmp, sizeof(tmp)))
438       return EINVAL;
439
440     if (state->values_types[i] == LCC_TYPE_GAUGE) {
441       union {
442         uint64_t i;
443         double d;
444       } conv = {.i = tmp};
445       state->values[i].gauge = ntohd(conv.d);
446       continue;
447     }
448
449     tmp = be64toh(tmp);
450     switch (state->values_types[i]) {
451     case LCC_TYPE_COUNTER:
452       state->values[i].counter = (counter_t)tmp;
453       break;
454     case LCC_TYPE_DERIVE:
455       state->values[i].derive = (derive_t)tmp;
456       break;
457     case LCC_TYPE_ABSOLUTE:
458       state->values[i].absolute = (absolute_t)tmp;
459       break;
460     default:
461       return EINVAL;
462     }
463   }
464
465   return 0;
466 }
467
468 int lcc_network_parse(void *data, size_t data_size, lcc_value_list_writer_t w) {
469   buffer_t *b = &(buffer_t){
470       .data = data, .len = data_size,
471   };
472
473   lcc_value_list_t state = {0};
474
475   while (b->len > 0) {
476     uint16_t type = 0, sz = 0;
477     if (buffer_uint16(b, &type) || buffer_uint16(b, &sz)) {
478       DEBUG("lcc_network_parse(): reading type and/or length failed.\n");
479       return EINVAL;
480     }
481
482     if ((sz < 5) || (((size_t)sz - 4) > b->len)) {
483       DEBUG("lcc_network_parse(): invalid 'sz' field: sz = %" PRIu16
484             ", b->len = %zu\n",
485             sz, b->len);
486       return EINVAL;
487     }
488     sz -= 4;
489
490     uint8_t payload[sz];
491     if (buffer_next(b, payload, sizeof(payload)))
492       return EINVAL;
493
494     switch (type) {
495     case TYPE_HOST:
496     case TYPE_PLUGIN:
497     case TYPE_PLUGIN_INSTANCE:
498     case TYPE_TYPE:
499     case TYPE_TYPE_INSTANCE: {
500       if (parse_identifier(type, payload, sizeof(payload), &state)) {
501         DEBUG("lcc_network_parse(): parse_identifier failed.\n");
502         return EINVAL;
503       }
504       break;
505     }
506
507     case TYPE_INTERVAL:
508     case TYPE_INTERVAL_HR:
509     case TYPE_TIME:
510     case TYPE_TIME_HR: {
511       if (parse_time(type, payload, sizeof(payload), &state)) {
512         DEBUG("lcc_network_parse(): parse_time failed.\n");
513         return EINVAL;
514       }
515       break;
516     }
517
518     case TYPE_VALUES: {
519       lcc_value_list_t vl = state;
520       if (parse_values(payload, sizeof(payload), &vl)) {
521         DEBUG("lcc_network_parse(): parse_values failed.\n");
522         return EINVAL;
523       }
524
525       /* TODO(octo): skip if current_security_level < required_security_level */
526
527       int status = w(&vl);
528
529       free(vl.values);
530       free(vl.values_types);
531
532       if (status != 0)
533         return status;
534       break;
535     }
536
537     default: {
538       DEBUG("lcc_network_parse(): ignoring unknown type %" PRIu16 "\n", type);
539       return EINVAL;
540     }
541     }
542   }
543
544   return 0;
545 }