Merge pull request #2618 from ajssmith/amqp1_dev1_branch
[collectd.git] / src / teamspeak2.c
1 /**
2  * collectd - src/teamspeak2.c
3  * Copyright (C) 2008  Stefan Hacker
4  * Copyright (C) 2008  Florian Forster
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; only version 2 of the License is applicable.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Stefan Hacker <d0t at dbclan dot de>
21  *   Florian Forster <octo at collectd.org>
22  **/
23
24 #include "collectd.h"
25
26 #include "common.h"
27 #include "plugin.h"
28
29 #include <arpa/inet.h>
30 #include <netdb.h>
31 #include <netinet/in.h>
32 #include <sys/types.h>
33
34 /*
35  * Defines
36  */
37 /* Default host and port */
38 #define DEFAULT_HOST "127.0.0.1"
39 #define DEFAULT_PORT "51234"
40
41 /*
42  * Variables
43  */
44 /* Server linked list structure */
45 typedef struct vserver_list_s {
46   int port;
47   struct vserver_list_s *next;
48 } vserver_list_t;
49 static vserver_list_t *server_list;
50
51 /* Host data */
52 static char *config_host;
53 static char *config_port;
54
55 static FILE *global_read_fh;
56 static FILE *global_write_fh;
57
58 /* Config data */
59 static const char *config_keys[] = {"Host", "Port", "Server"};
60 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
61
62 /*
63  * Functions
64  */
65 static int tss2_add_vserver(int vserver_port) {
66   /*
67    * Adds a new vserver to the linked list
68    */
69   vserver_list_t *entry;
70
71   /* Check port range */
72   if ((vserver_port <= 0) || (vserver_port > 65535)) {
73     ERROR("teamspeak2 plugin: VServer port is invalid: %i", vserver_port);
74     return -1;
75   }
76
77   /* Allocate memory */
78   entry = calloc(1, sizeof(*entry));
79   if (entry == NULL) {
80     ERROR("teamspeak2 plugin: calloc failed.");
81     return -1;
82   }
83
84   /* Save data */
85   entry->port = vserver_port;
86
87   /* Insert to list */
88   if (server_list == NULL) {
89     /* Add the server as the first element */
90     server_list = entry;
91   } else {
92     vserver_list_t *prev;
93
94     /* Add the server to the end of the list */
95     prev = server_list;
96     while (prev->next != NULL)
97       prev = prev->next;
98     prev->next = entry;
99   }
100
101   INFO("teamspeak2 plugin: Registered new vserver: %i", vserver_port);
102
103   return 0;
104 } /* int tss2_add_vserver */
105
106 static void tss2_submit_gauge(const char *plugin_instance, const char *type,
107                               const char *type_instance, gauge_t value) {
108   /*
109    * Submits a gauge value to the collectd daemon
110    */
111   value_list_t vl = VALUE_LIST_INIT;
112
113   vl.values = &(value_t){.gauge = value};
114   vl.values_len = 1;
115   sstrncpy(vl.plugin, "teamspeak2", sizeof(vl.plugin));
116
117   if (plugin_instance != NULL)
118     sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
119
120   sstrncpy(vl.type, type, sizeof(vl.type));
121
122   if (type_instance != NULL)
123     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
124
125   plugin_dispatch_values(&vl);
126 } /* void tss2_submit_gauge */
127
128 static void tss2_submit_io(const char *plugin_instance, const char *type,
129                            derive_t rx, derive_t tx) {
130   /*
131    * Submits the io rx/tx tuple to the collectd daemon
132    */
133   value_list_t vl = VALUE_LIST_INIT;
134   value_t values[] = {
135       {.derive = rx}, {.derive = tx},
136   };
137
138   vl.values = values;
139   vl.values_len = STATIC_ARRAY_SIZE(values);
140   sstrncpy(vl.plugin, "teamspeak2", sizeof(vl.plugin));
141
142   if (plugin_instance != NULL)
143     sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
144
145   sstrncpy(vl.type, type, sizeof(vl.type));
146
147   plugin_dispatch_values(&vl);
148 } /* void tss2_submit_gauge */
149
150 static void tss2_close_socket(void) {
151   /*
152    * Closes all sockets
153    */
154   if (global_write_fh != NULL) {
155     fputs("quit\r\n", global_write_fh);
156   }
157
158   if (global_read_fh != NULL) {
159     fclose(global_read_fh);
160     global_read_fh = NULL;
161   }
162
163   if (global_write_fh != NULL) {
164     fclose(global_write_fh);
165     global_write_fh = NULL;
166   }
167 } /* void tss2_close_socket */
168
169 static int tss2_get_socket(FILE **ret_read_fh, FILE **ret_write_fh) {
170   /*
171    * Returns connected file objects or establishes the connection
172    * if it's not already present
173    */
174   struct addrinfo *ai_head;
175   int sd = -1;
176   int status;
177
178   /* Check if we already got opened connections */
179   if ((global_read_fh != NULL) && (global_write_fh != NULL)) {
180     /* If so, use them */
181     if (ret_read_fh != NULL)
182       *ret_read_fh = global_read_fh;
183     if (ret_write_fh != NULL)
184       *ret_write_fh = global_write_fh;
185     return 0;
186   }
187
188   /* Get all addrs for this hostname */
189   struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
190                               .ai_flags = AI_ADDRCONFIG,
191                               .ai_socktype = SOCK_STREAM};
192
193   status = getaddrinfo((config_host != NULL) ? config_host : DEFAULT_HOST,
194                        (config_port != NULL) ? config_port : DEFAULT_PORT,
195                        &ai_hints, &ai_head);
196   if (status != 0) {
197     ERROR("teamspeak2 plugin: getaddrinfo failed: %s", gai_strerror(status));
198     return -1;
199   }
200
201   /* Try all given hosts until we can connect to one */
202   for (struct addrinfo *ai_ptr = ai_head; ai_ptr != NULL;
203        ai_ptr = ai_ptr->ai_next) {
204     /* Create socket */
205     sd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
206     if (sd < 0) {
207       WARNING("teamspeak2 plugin: socket failed: %s", STRERRNO);
208       continue;
209     }
210
211     /* Try to connect */
212     status = connect(sd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
213     if (status != 0) {
214       WARNING("teamspeak2 plugin: connect failed: %s", STRERRNO);
215       close(sd);
216       sd = -1;
217       continue;
218     }
219
220     /*
221      * Success, we can break. Don't need more than one connection
222      */
223     break;
224   } /* for (ai_ptr) */
225
226   freeaddrinfo(ai_head);
227
228   /* Check if we really got connected */
229   if (sd < 0)
230     return -1;
231
232   /* Create file objects from sockets */
233   global_read_fh = fdopen(sd, "r");
234   if (global_read_fh == NULL) {
235     ERROR("teamspeak2 plugin: fdopen failed: %s", STRERRNO);
236     close(sd);
237     return -1;
238   }
239
240   global_write_fh = fdopen(sd, "w");
241   if (global_write_fh == NULL) {
242     ERROR("teamspeak2 plugin: fdopen failed: %s", STRERRNO);
243     tss2_close_socket();
244     return -1;
245   }
246
247   { /* Check that the server correctly identifies itself. */
248     char buffer[4096];
249     char *buffer_ptr;
250
251     buffer_ptr = fgets(buffer, sizeof(buffer), global_read_fh);
252     if (buffer_ptr == NULL) {
253       WARNING("teamspeak2 plugin: Unexpected EOF received "
254               "from remote host %s:%s.",
255               config_host ? config_host : DEFAULT_HOST,
256               config_port ? config_port : DEFAULT_PORT);
257     }
258     buffer[sizeof(buffer) - 1] = 0;
259
260     if (memcmp("[TS]\r\n", buffer, 6) != 0) {
261       ERROR("teamspeak2 plugin: Unexpected response when connecting "
262             "to server. Expected ``[TS]'', got ``%s''.",
263             buffer);
264       tss2_close_socket();
265       return -1;
266     }
267     DEBUG("teamspeak2 plugin: Server send correct banner, connected!");
268   }
269
270   /* Copy the new filehandles to the given pointers */
271   if (ret_read_fh != NULL)
272     *ret_read_fh = global_read_fh;
273   if (ret_write_fh != NULL)
274     *ret_write_fh = global_write_fh;
275   return 0;
276 } /* int tss2_get_socket */
277
278 static int tss2_send_request(FILE *fh, const char *request) {
279   /*
280    * This function puts a request to the server socket
281    */
282   int status;
283
284   status = fputs(request, fh);
285   if (status < 0) {
286     ERROR("teamspeak2 plugin: fputs failed.");
287     tss2_close_socket();
288     return -1;
289   }
290   fflush(fh);
291
292   return 0;
293 } /* int tss2_send_request */
294
295 static int tss2_receive_line(FILE *fh, char *buffer, int buffer_size) {
296   /*
297    * Receive a single line from the given file object
298    */
299   char *temp;
300
301   /*
302    * fgets is blocking but much easier then doing anything else
303    * TODO: Non-blocking Version would be safer
304    */
305   temp = fgets(buffer, buffer_size, fh);
306   if (temp == NULL) {
307     ERROR("teamspeak2 plugin: fgets failed: %s", STRERRNO);
308     tss2_close_socket();
309     return -1;
310   }
311
312   buffer[buffer_size - 1] = 0;
313   return 0;
314 } /* int tss2_receive_line */
315
316 static int tss2_select_vserver(FILE *read_fh, FILE *write_fh,
317                                vserver_list_t *vserver) {
318   /*
319    * Tell the server to select the given vserver
320    */
321   char command[128];
322   char response[128];
323   int status;
324
325   /* Send request */
326   snprintf(command, sizeof(command), "sel %i\r\n", vserver->port);
327
328   status = tss2_send_request(write_fh, command);
329   if (status != 0) {
330     ERROR("teamspeak2 plugin: tss2_send_request (%s) failed.", command);
331     return -1;
332   }
333
334   /* Get answer */
335   status = tss2_receive_line(read_fh, response, sizeof(response));
336   if (status != 0) {
337     ERROR("teamspeak2 plugin: tss2_receive_line failed.");
338     return -1;
339   }
340   response[sizeof(response) - 1] = 0;
341
342   /* Check answer */
343   if ((strncasecmp("OK", response, 2) == 0) &&
344       ((response[2] == 0) || (response[2] == '\n') || (response[2] == '\r')))
345     return 0;
346
347   ERROR("teamspeak2 plugin: Command ``%s'' failed. "
348         "Response received from server was: ``%s''.",
349         command, response);
350   return -1;
351 } /* int tss2_select_vserver */
352
353 static int tss2_vserver_gapl(FILE *read_fh, FILE *write_fh,
354                              gauge_t *ret_value) {
355   /*
356    * Reads the vserver's average packet loss and submits it to collectd.
357    * Be sure to run the tss2_read_vserver function before calling this so
358    * the vserver is selected correctly.
359    */
360   gauge_t packet_loss = NAN;
361   int status;
362
363   status = tss2_send_request(write_fh, "gapl\r\n");
364   if (status != 0) {
365     ERROR("teamspeak2 plugin: tss2_send_request (gapl) failed.");
366     return -1;
367   }
368
369   while (42) {
370     char buffer[4096];
371     char *value;
372     char *endptr = NULL;
373
374     status = tss2_receive_line(read_fh, buffer, sizeof(buffer));
375     if (status != 0) {
376       /* Set to NULL just to make sure no one uses these FHs anymore. */
377       read_fh = NULL;
378       write_fh = NULL;
379       ERROR("teamspeak2 plugin: tss2_receive_line failed.");
380       return -1;
381     }
382     buffer[sizeof(buffer) - 1] = 0;
383
384     if (strncmp("average_packet_loss=", buffer,
385                 strlen("average_packet_loss=")) == 0) {
386       /* Got average packet loss, now interpret it */
387       value = &buffer[20];
388       /* Replace , with . */
389       while (*value != 0) {
390         if (*value == ',') {
391           *value = '.';
392           break;
393         }
394         value++;
395       }
396
397       value = &buffer[20];
398
399       packet_loss = strtod(value, &endptr);
400       if (value == endptr) {
401         /* Failed */
402         WARNING("teamspeak2 plugin: Could not read average package "
403                 "loss from string: %s",
404                 buffer);
405         continue;
406       }
407     } else if (strncasecmp("OK", buffer, 2) == 0) {
408       break;
409     } else if (strncasecmp("ERROR", buffer, 5) == 0) {
410       ERROR("teamspeak2 plugin: Server returned an error: %s", buffer);
411       return -1;
412     } else {
413       WARNING("teamspeak2 plugin: Server returned unexpected string: %s",
414               buffer);
415     }
416   }
417
418   *ret_value = packet_loss;
419   return 0;
420 } /* int tss2_vserver_gapl */
421
422 static int tss2_read_vserver(vserver_list_t *vserver) {
423   /*
424    * Poll information for the given vserver and submit it to collect.
425    * If vserver is NULL the global server information will be queried.
426    */
427   int status;
428
429   gauge_t users = NAN;
430   gauge_t channels = NAN;
431   gauge_t servers = NAN;
432   derive_t rx_octets = 0;
433   derive_t tx_octets = 0;
434   derive_t rx_packets = 0;
435   derive_t tx_packets = 0;
436   gauge_t packet_loss = NAN;
437   int valid = 0;
438
439   char plugin_instance[DATA_MAX_NAME_LEN] = {0};
440
441   FILE *read_fh;
442   FILE *write_fh;
443
444   /* Get the send/receive sockets */
445   status = tss2_get_socket(&read_fh, &write_fh);
446   if (status != 0) {
447     ERROR("teamspeak2 plugin: tss2_get_socket failed.");
448     return -1;
449   }
450
451   if (vserver == NULL) {
452     /* Request global information */
453     status = tss2_send_request(write_fh, "gi\r\n");
454   } else {
455     /* Request server information */
456     snprintf(plugin_instance, sizeof(plugin_instance), "vserver%i",
457              vserver->port);
458
459     /* Select the server */
460     status = tss2_select_vserver(read_fh, write_fh, vserver);
461     if (status != 0)
462       return status;
463
464     status = tss2_send_request(write_fh, "si\r\n");
465   }
466
467   if (status != 0) {
468     ERROR("teamspeak2 plugin: tss2_send_request failed.");
469     return -1;
470   }
471
472   /* Loop until break */
473   while (42) {
474     char buffer[4096];
475     char *key;
476     char *value;
477     char *endptr = NULL;
478
479     /* Read one line of the server's answer */
480     status = tss2_receive_line(read_fh, buffer, sizeof(buffer));
481     if (status != 0) {
482       /* Set to NULL just to make sure no one uses these FHs anymore. */
483       read_fh = NULL;
484       write_fh = NULL;
485       ERROR("teamspeak2 plugin: tss2_receive_line failed.");
486       break;
487     }
488
489     if (strncasecmp("ERROR", buffer, 5) == 0) {
490       ERROR("teamspeak2 plugin: Server returned an error: %s", buffer);
491       break;
492     } else if (strncasecmp("OK", buffer, 2) == 0) {
493       break;
494     }
495
496     /* Split line into key and value */
497     key = strchr(buffer, '_');
498     if (key == NULL) {
499       DEBUG("teamspeak2 plugin: Cannot parse line: %s", buffer);
500       continue;
501     }
502     key++;
503
504     /* Evaluate assignment */
505     value = strchr(key, '=');
506     if (value == NULL) {
507       DEBUG("teamspeak2 plugin: Cannot parse line: %s", buffer);
508       continue;
509     }
510     *value = 0;
511     value++;
512
513     /* Check for known key and save the given value */
514     /* global info: users_online,
515      * server info: currentusers. */
516     if ((strcmp("currentusers", key) == 0) ||
517         (strcmp("users_online", key) == 0)) {
518       users = strtod(value, &endptr);
519       if (value != endptr)
520         valid |= 0x01;
521     }
522     /* global info: channels,
523      * server info: currentchannels. */
524     else if ((strcmp("currentchannels", key) == 0) ||
525              (strcmp("channels", key) == 0)) {
526       channels = strtod(value, &endptr);
527       if (value != endptr)
528         valid |= 0x40;
529     }
530     /* global only */
531     else if (strcmp("servers", key) == 0) {
532       servers = strtod(value, &endptr);
533       if (value != endptr)
534         valid |= 0x80;
535     } else if (strcmp("bytesreceived", key) == 0) {
536       rx_octets = strtoll(value, &endptr, 0);
537       if (value != endptr)
538         valid |= 0x02;
539     } else if (strcmp("bytessend", key) == 0) {
540       tx_octets = strtoll(value, &endptr, 0);
541       if (value != endptr)
542         valid |= 0x04;
543     } else if (strcmp("packetsreceived", key) == 0) {
544       rx_packets = strtoll(value, &endptr, 0);
545       if (value != endptr)
546         valid |= 0x08;
547     } else if (strcmp("packetssend", key) == 0) {
548       tx_packets = strtoll(value, &endptr, 0);
549       if (value != endptr)
550         valid |= 0x10;
551     } else if ((strncmp("allow_codec_", key, strlen("allow_codec_")) == 0) ||
552                (strncmp("bwinlast", key, strlen("bwinlast")) == 0) ||
553                (strncmp("bwoutlast", key, strlen("bwoutlast")) == 0) ||
554                (strncmp("webpost_", key, strlen("webpost_")) == 0) ||
555                (strcmp("adminemail", key) == 0) ||
556                (strcmp("clan_server", key) == 0) ||
557                (strcmp("countrynumber", key) == 0) ||
558                (strcmp("id", key) == 0) || (strcmp("ispname", key) == 0) ||
559                (strcmp("linkurl", key) == 0) ||
560                (strcmp("maxusers", key) == 0) || (strcmp("name", key) == 0) ||
561                (strcmp("password", key) == 0) ||
562                (strcmp("platform", key) == 0) ||
563                (strcmp("server_platform", key) == 0) ||
564                (strcmp("server_uptime", key) == 0) ||
565                (strcmp("server_version", key) == 0) ||
566                (strcmp("udpport", key) == 0) || (strcmp("uptime", key) == 0) ||
567                (strcmp("users_maximal", key) == 0) ||
568                (strcmp("welcomemessage", key) == 0))
569       /* ignore */;
570     else {
571       INFO("teamspeak2 plugin: Unknown key-value-pair: "
572            "key = %s; value = %s;",
573            key, value);
574     }
575   } /* while (42) */
576
577   /* Collect vserver packet loss rates only if the loop above did not exit
578    * with an error. */
579   if ((status == 0) && (vserver != NULL)) {
580     status = tss2_vserver_gapl(read_fh, write_fh, &packet_loss);
581     if (status == 0) {
582       valid |= 0x20;
583     } else {
584       WARNING("teamspeak2 plugin: Reading package loss "
585               "for vserver %i failed.",
586               vserver->port);
587     }
588   }
589
590   if ((valid & 0x01) == 0x01)
591     tss2_submit_gauge(plugin_instance, "users", NULL, users);
592
593   if ((valid & 0x06) == 0x06)
594     tss2_submit_io(plugin_instance, "io_octets", rx_octets, tx_octets);
595
596   if ((valid & 0x18) == 0x18)
597     tss2_submit_io(plugin_instance, "io_packets", rx_packets, tx_packets);
598
599   if ((valid & 0x20) == 0x20)
600     tss2_submit_gauge(plugin_instance, "percent", "packet_loss", packet_loss);
601
602   if ((valid & 0x40) == 0x40)
603     tss2_submit_gauge(plugin_instance, "gauge", "channels", channels);
604
605   if ((valid & 0x80) == 0x80)
606     tss2_submit_gauge(plugin_instance, "gauge", "servers", servers);
607
608   if (valid == 0)
609     return -1;
610   return 0;
611 } /* int tss2_read_vserver */
612
613 static int tss2_config(const char *key, const char *value) {
614   /*
615    * Interpret configuration values
616    */
617   if (strcasecmp("Host", key) == 0) {
618     char *temp;
619
620     temp = strdup(value);
621     if (temp == NULL) {
622       ERROR("teamspeak2 plugin: strdup failed.");
623       return 1;
624     }
625     sfree(config_host);
626     config_host = temp;
627   } else if (strcasecmp("Port", key) == 0) {
628     char *temp;
629
630     temp = strdup(value);
631     if (temp == NULL) {
632       ERROR("teamspeak2 plugin: strdup failed.");
633       return 1;
634     }
635     sfree(config_port);
636     config_port = temp;
637   } else if (strcasecmp("Server", key) == 0) {
638     /* Server variable found */
639     int status;
640
641     status = tss2_add_vserver(atoi(value));
642     if (status != 0)
643       return 1;
644   } else {
645     /* Unknown variable found */
646     return -1;
647   }
648
649   return 0;
650 } /* int tss2_config */
651
652 static int tss2_read(void) {
653   /*
654    * Poll function which collects global and vserver information
655    * and submits it to collectd
656    */
657   int success = 0;
658   int status;
659
660   /* Handle global server variables */
661   status = tss2_read_vserver(NULL);
662   if (status == 0) {
663     success++;
664   } else {
665     WARNING("teamspeak2 plugin: Reading global server variables failed.");
666   }
667
668   /* Handle vservers */
669   for (vserver_list_t *vserver = server_list; vserver != NULL;
670        vserver = vserver->next) {
671     status = tss2_read_vserver(vserver);
672     if (status == 0) {
673       success++;
674     } else {
675       WARNING("teamspeak2 plugin: Reading statistics "
676               "for vserver %i failed.",
677               vserver->port);
678       continue;
679     }
680   }
681
682   if (success == 0)
683     return -1;
684   return 0;
685 } /* int tss2_read */
686
687 static int tss2_shutdown(void) {
688   /*
689    * Shutdown handler
690    */
691   vserver_list_t *entry;
692
693   tss2_close_socket();
694
695   entry = server_list;
696   server_list = NULL;
697   while (entry != NULL) {
698     vserver_list_t *next;
699
700     next = entry->next;
701     sfree(entry);
702     entry = next;
703   }
704
705   /* Get rid of the configuration */
706   sfree(config_host);
707   sfree(config_port);
708
709   return 0;
710 } /* int tss2_shutdown */
711
712 void module_register(void) {
713   /*
714    * Mandatory module_register function
715    */
716   plugin_register_config("teamspeak2", tss2_config, config_keys,
717                          config_keys_num);
718   plugin_register_read("teamspeak2", tss2_read);
719   plugin_register_shutdown("teamspeak2", tss2_shutdown);
720 } /* void module_register */