Introduce the "mt_debug" macro.
[routeros-api.git] / src / main.c
1 /**
2  * libmikrotik - src/main.c
3  * Copyright (C) 2009  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 #ifndef _ISOC99_SOURCE
23 # define _ISOC99_SOURCE
24 #endif
25
26 #ifndef _POSIX_C_SOURCE
27 # define _POSIX_C_SOURCE 200112L
28 #endif
29
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <stdint.h>
34 #include <inttypes.h>
35 #include <string.h>
36 #include <errno.h>
37 #include <assert.h>
38
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <netdb.h>
42
43 #include "routeros_api.h"
44
45 #if 1
46 # define mt_debug(...) fprintf (stdout, __VA_ARGS__)
47 #else
48 # define mt_debug(...) /**/
49 #endif
50
51 /* FIXME */
52 char *strdup (const char *);
53
54 /*
55  * Private structures
56  */
57 struct mt_connection_s
58 {
59         int fd;
60 };
61
62 struct mt_reply_s
63 {
64         unsigned int params_num;
65         char *status;
66         char **keys;
67         char **values;
68
69         mt_reply_t *next;
70 };
71
72 /*
73  * Private functions
74  */
75 static int read_exact (int fd, void *buffer, size_t buffer_size) /* {{{ */
76 {
77         char *buffer_ptr;
78         size_t have_bytes;
79
80         if ((fd < 0) || (buffer == NULL))
81                 return (EINVAL);
82
83         if (buffer_size == 0)
84                 return (0);
85
86         buffer_ptr = buffer;
87         have_bytes = 0;
88         while (have_bytes < buffer_size)
89         {
90                 size_t want_bytes;
91                 ssize_t status;
92
93                 want_bytes = buffer_size - have_bytes;
94                 errno = 0;
95                 status = read (fd, buffer_ptr, want_bytes);
96                 if (status < 0)
97                 {
98                         if (errno == EAGAIN)
99                                 continue;
100                         else
101                                 return (status);
102                 }
103
104                 assert (status <= want_bytes);
105                 have_bytes += status;
106                 buffer_ptr += status;
107         }
108
109         return (0);
110 } /* }}} int read_exact */
111
112 static mt_reply_t *reply_alloc (void) /* {{{ */
113 {
114         mt_reply_t *r;
115
116         r = malloc (sizeof (*r));
117         if (r == NULL)
118                 return (NULL);
119
120         memset (r, 0, sizeof (*r));
121         r->keys = NULL;
122         r->values = NULL;
123         r->next = NULL;
124
125         return (r);
126 } /* }}} mt_reply_s *reply_alloc */
127
128 static int reply_add_keyval (mt_reply_t *r, const char *key, /* {{{ */
129                 const char *val)
130 {
131         char **tmp;
132
133         tmp = realloc (r->keys, (r->params_num + 1) * sizeof (*tmp));
134         if (tmp == NULL)
135                 return (ENOMEM);
136         r->keys = tmp;
137
138         tmp = realloc (r->values, (r->params_num + 1) * sizeof (*tmp));
139         if (tmp == NULL)
140                 return (ENOMEM);
141         r->values = tmp;
142
143         r->keys[r->params_num] = strdup (key);
144         if (r->keys[r->params_num] == NULL)
145                 return (ENOMEM);
146
147         r->values[r->params_num] = strdup (val);
148         if (r->values[r->params_num] == NULL)
149         {
150                 free (r->keys[r->params_num]);
151                 r->keys[r->params_num] = NULL;
152                 return (ENOMEM);
153         }
154
155         r->params_num++;
156         return (0);
157 } /* }}} int reply_add_keyval */
158
159 static void reply_free (mt_reply_t *r) /* {{{ */
160 {
161         mt_reply_t *next;
162         unsigned int i;
163
164         if (r == NULL)
165                 return;
166
167         next = r->next;
168
169         for (i = 0; i < r->params_num; i++)
170         {
171                 free (r->keys[i]);
172                 free (r->values[i]);
173         }
174
175         free (r->keys);
176         free (r->values);
177
178         free (r);
179
180         reply_free (next);
181 } /* }}} void reply_free */
182
183 static int buffer_init (char **ret_buffer, size_t *ret_buffer_size) /* {{{ */
184 {
185         if ((ret_buffer == NULL) || (ret_buffer_size == NULL))
186                 return (EINVAL);
187
188         if (*ret_buffer_size < 1)
189                 return (EINVAL);
190
191         return (0);
192 } /* }}} int buffer_init */
193
194 static int buffer_add (char **ret_buffer, size_t *ret_buffer_size, /* {{{ */
195                 const char *string)
196 {
197         char *buffer;
198         size_t buffer_size;
199         size_t string_size;
200         size_t req_size;
201
202         if ((ret_buffer == NULL) || (ret_buffer_size == NULL) || (string == NULL))
203                 return (EINVAL);
204
205         buffer = *ret_buffer;
206         buffer_size = *ret_buffer_size;
207
208         string_size = strlen (string);
209         if (string_size == 0)
210                 return (EINVAL);
211
212         if (string_size >= 0x10000000)
213                 req_size = 5 + string_size;
214         else if (string_size >= 0x200000)
215                 req_size = 4 + string_size;
216         else if (string_size >= 0x4000)
217                 req_size = 3 + string_size;
218         else if (string_size >= 0x80)
219                 req_size = 2 + string_size;
220         else
221                 req_size = 1 + string_size;
222
223         if (*ret_buffer_size < req_size)
224                 return (ENOMEM);
225
226         if (string_size >= 0x10000000)
227         {
228                 buffer[0] = 0xF0;
229                 buffer[1] = (string_size >> 24) & 0xff;
230                 buffer[2] = (string_size >> 16) & 0xff;
231                 buffer[3] = (string_size >>  8) & 0xff;
232                 buffer[4] = (string_size      ) & 0xff;
233                 buffer += 5;
234                 buffer_size -= 5;
235         }
236         else if (string_size >= 0x200000)
237         {
238                 buffer[0] = (string_size >> 24) & 0x1f;
239                 buffer[0] |= 0xE0;
240                 buffer[1] = (string_size >> 16) & 0xff;
241                 buffer[2] = (string_size >>  8) & 0xff;
242                 buffer[3] = (string_size      ) & 0xff;
243                 buffer += 4;
244                 buffer_size -= 4;
245         }
246         else if (string_size >= 0x4000)
247         {
248                 buffer[0] = (string_size >> 16) & 0x3f;
249                 buffer[0] |= 0xC0;
250                 buffer[1] = (string_size >>  8) & 0xff;
251                 buffer[2] = (string_size      ) & 0xff;
252                 buffer += 3;
253                 buffer_size -= 3;
254         }
255         else if (string_size >= 0x80)
256         {
257                 buffer[0] = (string_size >>  8) & 0x7f;
258                 buffer[0] |= 0x80;
259                 buffer[1] = (string_size      ) & 0xff;
260                 buffer += 2;
261                 buffer_size -= 2;
262         }
263         else /* if (string_size <= 0x7f) */
264         {
265                 buffer[0] = (char) string_size;
266                 buffer += 1;
267                 buffer_size -= 1;
268         }
269
270         assert (buffer_size >= string_size);
271         memcpy (buffer, string, string_size);
272         buffer += string_size;
273         buffer_size -= string_size;
274
275         *ret_buffer = buffer;
276         *ret_buffer_size = buffer_size;
277
278         return (0);
279 } /* }}} int buffer_add */
280
281 static int buffer_end (char **ret_buffer, size_t *ret_buffer_size) /* {{{ */
282 {
283         if ((ret_buffer == NULL) || (ret_buffer_size == NULL))
284                 return (EINVAL);
285
286         if (*ret_buffer_size < 1)
287                 return (EINVAL);
288
289         /* Add empty word. */
290         (*ret_buffer)[0] = 0;
291         (*ret_buffer)++;
292         (*ret_buffer_size)--;
293
294         return (0);
295 } /* }}} int buffer_end */
296
297 static int send_command (mt_connection_t *c, /* {{{ */
298                 const char *command,
299                 size_t args_num, const char * const *args)
300 {
301         char buffer[4096];
302         char *buffer_ptr;
303         size_t buffer_size;
304
305         size_t i;
306         int status;
307
308         /* FIXME: For debugging only */
309         memset (buffer, 0, sizeof (buffer));
310
311         buffer_ptr = buffer;
312         buffer_size = sizeof (buffer);
313
314         status = buffer_init (&buffer_ptr, &buffer_size);
315         if (status != 0)
316                 return (status);
317
318         status = buffer_add (&buffer_ptr, &buffer_size, command);
319         if (status != 0)
320                 return (status);
321
322         for (i = 0; i < args_num; i++)
323         {
324                 if (args[i] == NULL)
325                         return (EINVAL);
326
327                 status = buffer_add (&buffer_ptr, &buffer_size, args[i]);
328                 if (status != 0)
329                         return (status);
330         }
331
332         status = buffer_end (&buffer_ptr, &buffer_size);
333         if (status != 0)
334                 return (status);
335
336         buffer_ptr = buffer;
337         buffer_size = sizeof (buffer) - buffer_size;
338         while (buffer_size > 0)
339         {
340                 ssize_t bytes_written;
341
342                 errno = 0;
343                 bytes_written = write (c->fd, buffer_ptr, buffer_size);
344                 if (bytes_written < 0)
345                 {
346                         if (errno == EAGAIN)
347                                 continue;
348                         else
349                                 return (errno);
350                 }
351                 assert (bytes_written <= buffer_size);
352
353                 buffer_ptr += bytes_written;
354                 buffer_size -= bytes_written;
355         } /* while (buffer_size > 0) */
356
357         return (0);
358 } /* }}} int send_command */
359
360 static int read_word (mt_connection_t *c, /* {{{ */
361                 char *buffer, size_t *buffer_size)
362 {
363         size_t req_size;
364         uint8_t word_length[5];
365         int status;
366
367         if ((buffer == NULL) || (*buffer_size < 1))
368                 return (EINVAL);
369
370         /* read one byte from the socket */
371         status = read_exact (c->fd, word_length, 1);
372         if (status != 0)
373                 return (status);
374
375         /* Calculate `req_size' */
376         if (((unsigned char) buffer[0]) == 0xF0) /* {{{ */
377         {
378                 status = read_exact (c->fd, &word_length[1], 4);
379                 if (status != 0)
380                         return (status);
381
382                 req_size = (buffer[1] << 24)
383                         | (buffer[2] << 16)
384                         | (buffer[3] << 8)
385                         | buffer[4];
386         }
387         else if ((buffer[0] & 0xE0) == 0xE0)
388         {
389                 status = read_exact (c->fd, &word_length[1], 3);
390                 if (status != 0)
391                         return (status);
392
393                 req_size = ((buffer[0] & 0x1F) << 24)
394                         | (buffer[1] << 16)
395                         | (buffer[2] << 8)
396                         | buffer[3];
397         }
398         else if ((buffer[0] & 0xC0) == 0xC0)
399         {
400                 status = read_exact (c->fd, &word_length[1], 2);
401                 if (status != 0)
402                         return (status);
403
404                 req_size = ((buffer[0] & 0x3F) << 16)
405                         | (buffer[1] << 8)
406                         | buffer[2];
407         }
408         else if ((buffer[0] & 0x80) == 0x80)
409         {
410                 status = read_exact (c->fd, &word_length[1], 1);
411                 if (status != 0)
412                         return (status);
413
414                 req_size = ((buffer[0] & 0x7F) << 8)
415                         | buffer[1];
416         }
417         else if ((buffer[0] & 0x80) == 0)
418         {
419                 req_size = (size_t) word_length[0];
420         }
421         else
422         {
423                 /* First nibble is `F' but second nibble is not `0'. */
424                 return (EPROTO);
425         } /* }}} */
426
427         if (*buffer_size < req_size)
428                 return (ENOMEM);
429
430         /* Empty word. This ends a `sentence' and must therefore be valid. */
431         if (req_size == 0)
432         {
433                 buffer[0] = 0;
434                 *buffer_size = 0;
435                 return (0);
436         }
437
438         status = read_exact (c->fd, buffer, req_size);
439         if (status != 0)
440                 return (status);
441         *buffer_size = req_size;
442
443         return (0);
444 } /* }}} int buffer_decode_next */
445
446 static mt_reply_t *receive_reply (mt_connection_t *c) /* {{{ */
447 {
448         char buffer[4096];
449         size_t buffer_size;
450         int status;
451
452         mt_reply_t *head;
453         mt_reply_t *tail;
454
455         head = NULL;
456         tail = NULL;
457
458         while (42)
459         {
460                 buffer_size = sizeof (buffer) - 1;
461                 status = read_word (c, buffer, &buffer_size);
462                 if (status != 0)
463                         break;
464                 assert (buffer_size < sizeof (buffer));
465                 buffer[buffer_size] = 0;
466
467                 /* Empty word means end of reply */
468                 if (buffer_size == 0)
469                         break;
470
471                 if (buffer[0] == '!') /* {{{ */
472                 {
473                         mt_reply_t *tmp;
474
475                         tmp = reply_alloc ();
476                         if (tmp == NULL)
477                         {
478                                 status = ENOMEM;
479                                 break;
480                         }
481
482                         tmp->status = strdup (&buffer[1]);
483                         if (tmp->status == NULL)
484                         {
485                                 reply_free (tmp);
486                                 status = ENOMEM;
487                                 break;
488                         }
489
490                         if (tail == NULL)
491                         {
492                                 head = tmp;
493                                 tail = tmp;
494                         }
495                         else
496                         {
497                                 tail->next = tmp;
498                                 tail = tmp;
499                         }
500                 } /* }}} if (buffer[0] == '!') */
501                 else if (buffer[0] == '=') /* {{{ */
502                 {
503                         char *key = &buffer[1];
504                         char *val;
505
506                         key = &buffer[1];
507                         val = strchr (key, '=');
508                         if (val == NULL)
509                         {
510                                 fprintf (stderr, "Ignoring misformed word: %s\n", buffer);
511                                 continue;
512                         }
513                         *val = 0;
514                         val++;
515
516                         reply_add_keyval (tail, key, val);
517                 } /* }}} if (buffer[0] == '=') */
518                 else
519                 {
520                         printf ("Ignoring unknown word: %s\n", buffer);
521                 }
522         } /* while (42) */
523         
524         if (status != 0)
525         {
526                 reply_free (head);
527                 return (NULL);
528         }
529
530         return (head);
531 } /* }}} mt_reply_t *receive_reply */
532
533 static int create_socket (const char *node, const char *service) /* {{{ */
534 {
535         struct addrinfo  ai_hint;
536         struct addrinfo *ai_list;
537         struct addrinfo *ai_ptr;
538         int status;
539
540         mt_debug ("create_socket (node = %s, service = %s);\n",
541                         node, service);
542
543         memset (&ai_hint, 0, sizeof (ai_hint));
544 #ifdef AI_ADDRCONFIG
545         ai_hint.ai_flags |= AI_ADDRCONFIG;
546 #endif
547         ai_hint.ai_family = AF_UNSPEC;
548         ai_hint.ai_socktype = SOCK_STREAM;
549
550         ai_list = NULL;
551         status = getaddrinfo (node, service, &ai_hint, &ai_list);
552         if (status != 0)
553                 return (-1);
554         assert (ai_list != NULL);
555
556         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
557         {
558                 int fd;
559                 int status;
560
561                 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
562                                 ai_ptr->ai_protocol);
563                 if (fd < 0)
564                 {
565                         mt_debug ("create_socket: socket(2) failed.\n");
566                         continue;
567                 }
568
569                 status = connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
570                 if (status != 0)
571                 {
572                         mt_debug ("create_socket: connect(2) failed.\n");
573                         close (fd);
574                         continue;
575                 }
576
577                 return (fd);
578         }
579
580         freeaddrinfo (ai_list);
581
582         return (-1);
583 } /* }}} int create_socket */
584
585 /*
586  * Public functions
587  */
588 mt_connection_t *mt_connect (const char *node, const char *service, /* {{{ */
589                 const char *username, const char *password)
590 {
591         int fd;
592         mt_connection_t *c;
593
594         if ((node == NULL) || (username == NULL) || (password == NULL))
595                 return (NULL);
596
597         fd = create_socket (node, (service != NULL) ? service : ROUTEROS_API_PORT);
598         if (fd < 0)
599                 return (NULL);
600
601         c = malloc (sizeof (*c));
602         if (c == NULL)
603         {
604                 close (fd);
605                 return (NULL);
606         }
607         memset (c, 0, sizeof (*c));
608
609         c->fd = fd;
610
611         return (c);
612 } /* }}} mt_connection_t *mt_connect */
613
614 int mt_disconnect (mt_connection_t *c) /* {{{ */
615 {
616         if (c == NULL)
617                 return (EINVAL);
618
619         if (c->fd >= 0)
620         {
621                 close (c->fd);
622                 c->fd = -1;
623         }
624
625         free (c);
626
627         return (0);
628 } /* }}} int mt_disconnect */
629
630 int mt_query (mt_connection_t *c, /* {{{ */
631                 const char *command,
632                 size_t args_num, const char * const *args,
633                 mt_reply_handler_t handler, void *user_data)
634 {
635         int status;
636         mt_reply_t *r;
637
638         status = send_command (c, command, args_num, args);
639         if (status != 0)
640                 return (status);
641
642         r = receive_reply (c);
643         if (r == NULL)
644                 return (EPROTO);
645
646         /* Call the callback function with the data we received. */
647         status = (*handler) (c, r, user_data);
648
649         /* Free the allocated memory ... */
650         reply_free (r);
651
652         /* ... and return. */
653         return (status);
654 } /* }}} int mt_query */
655
656 const mt_reply_t *mt_reply_next (const mt_reply_t *r) /* {{{ */
657 {
658         if (r == NULL)
659                 return (NULL);
660
661         return (r->next);
662 } /* }}} mt_reply_t *mt_reply_next */
663
664 int mt_reply_num (const mt_reply_t *r) /* {{{ */
665 {
666         int ret;
667         const mt_reply_t *ptr;
668
669         ret = 0;
670         for (ptr = r; ptr != NULL; ptr = ptr->next)
671                 ret++;
672
673         return (ret);
674 } /* }}} int mt_reply_num */
675
676 const char *mt_reply_param_key_by_index (const mt_reply_t *r, /* {{{ */
677                 unsigned int index)
678 {
679         if (r == NULL)
680                 return (NULL);
681
682         if (index >= r->params_num)
683                 return (NULL);
684
685         return (r->keys[index]);
686 } /* }}} char *mt_reply_param_key_by_index */
687
688 const char *mt_reply_param_val_by_index (const mt_reply_t *r, /* {{{ */
689                 unsigned int index)
690 {
691         if (r == NULL)
692                 return (NULL);
693
694         if (index >= r->params_num)
695                 return (NULL);
696
697         return (r->values[index]);
698 } /* }}} char *mt_reply_param_key_by_index */
699
700 const char *mt_reply_param_val_by_key (const mt_reply_t *r, /* {{{ */
701                 const char *key)
702 {
703         unsigned int i;
704
705         if ((r == NULL) || (key == NULL))
706                 return (NULL);
707
708         for (i = 0; i < r->params_num; i++)
709                 if (strcmp (r->keys[i], key) == 0)
710                         return (r->values[i]);
711
712         return (NULL);
713 } /* }}} char *mt_reply_param_val_by_key */
714
715 /* vim: set ts=2 sw=2 noet fdm=marker : */