Fix port numbers in IAX2 and iax2prov (bug #2261)
[asterisk/asterisk.git] / channels / iax2-provision.c
1 /*
2  * IAX Provisioning Protocol 
3  *
4  * Asterisk Interface
5  *
6  * Copyright (C) 2004 Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  *
13  */
14
15 #include <asterisk/config.h>
16 #include <asterisk/logger.h>
17 #include <asterisk/cli.h>
18 #include <asterisk/lock.h>
19 #include <asterisk/frame.h>
20 #include <asterisk/options.h>
21 #include <asterisk/md5.h>
22 #include <asterisk/astdb.h>
23 #include <netinet/in.h>
24 #include <netinet/in_systm.h>
25 #include <netinet/ip.h>
26 #include <sys/socket.h>
27 #include <asterisk/utils.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <stdio.h>
32 #include <netdb.h>
33 #include "iax2.h"
34 #include "iax2-provision.h"
35 #include "iax2-parser.h"
36
37 #ifndef IPTOS_MINCOST
38 #define IPTOS_MINCOST 0x02
39 #endif
40
41 static int provinit = 0;
42
43 struct iax_template {
44         int dead;
45         char name[80];
46         char src[80];
47         struct iax_template *next;
48         char user[20];
49         char pass[20];
50         char lang[10];
51         unsigned short port;
52         unsigned int server;
53         unsigned short serverport;
54         unsigned int altserver;
55         unsigned int flags;
56         unsigned int format;
57         int tos;        
58 } *templates;
59
60 static struct iax_flag {
61         char *name;
62         int value;
63 } iax_flags[] = {
64         { "register", PROV_FLAG_REGISTER },
65         { "secure", PROV_FLAG_SECURE },
66         { "heartbeat", PROV_FLAG_HEARTBEAT },
67         { "debug", PROV_FLAG_DEBUG },
68 };
69
70 char *iax_provflags2str(char *buf, int buflen, unsigned int flags)
71 {
72         int x;
73         if (!buf || buflen < 1) {
74                 return(NULL);
75         }
76         buf[0] = '\0';
77         for (x=0;x<sizeof(iax_flags) / sizeof(iax_flags[0]); x++) {
78                 if (flags & iax_flags[x].value){
79                         strncat(buf, iax_flags[x].name, buflen - strlen(buf) - 1);
80                         strncat(buf, ",", buflen - strlen(buf) - 1);
81                 }
82         }
83         if (strlen(buf)) 
84                 buf[strlen(buf) - 1] = '\0';
85         else
86                 strncpy(buf, "none", buflen - 1);
87         return buf;
88 }
89
90 static unsigned int iax_str2flags(const char *buf)
91 {
92         int x;
93         int len;
94         int found;
95         unsigned int flags = 0;
96         char *e;
97         while(buf && *buf) {
98                 e = strchr(buf, ',');
99                 if (e)
100                         len = e - buf;
101                 else
102                         len = 0;
103                 found = 0;
104                 for (x=0;x<sizeof(iax_flags) / sizeof(iax_flags[0]); x++) {
105                         if ((len && !strncasecmp(iax_flags[x].name, buf, len)) ||
106                             (!len && !strcasecmp(iax_flags[x].name, buf))) {
107                                 flags |= iax_flags[x].value;
108                                 break;
109                         }
110                 }
111                 if (e) {
112                         buf = e + 1;
113                         while(*buf && (*buf < 33))
114                                 buf++;
115                 } else
116                         break;
117         }
118         return flags;
119 }
120 AST_MUTEX_DEFINE_STATIC(provlock);
121
122 static struct iax_template *iax_template_find(const char *s, int allowdead)
123 {
124         struct iax_template *cur;
125         cur = templates;
126         while(cur) {
127                 if (!strcasecmp(s, cur->name)) {
128                         if (!allowdead && cur->dead)
129                                 cur = NULL;
130                         break;
131                 }
132                 cur = cur->next;
133         }
134         return cur;
135 }
136
137 char *iax_prov_complete_template(char *line, char *word, int pos, int state)
138 {
139         struct iax_template *c;
140         int which=0;
141         char *ret;
142         ast_mutex_lock(&provlock);
143         c = templates;
144         while(c) {
145                 if (!strncasecmp(word, c->name, strlen(word))) {
146                         if (++which > state)
147                                 break;
148                 }
149                 c = c->next;
150         }
151         if (c) {
152                 ret = strdup(c->name);
153         } else
154                 ret = NULL;
155         ast_mutex_unlock(&provlock);
156         return ret;
157 }
158
159 static unsigned int prov_ver_calc(struct iax_ie_data *provdata)
160 {
161         struct MD5Context md5;
162         unsigned int tmp[4];
163         MD5Init(&md5);
164         MD5Update(&md5, provdata->buf, provdata->pos);
165         MD5Final((unsigned char *)tmp, &md5);
166         return tmp[0] ^ tmp[1] ^ tmp[2] ^ tmp[3];
167 }
168
169 int iax_provision_build(struct iax_ie_data *provdata, unsigned int *signature, const char *template, int force)
170 {
171         struct iax_template *cur;
172         unsigned int sig;
173         char tmp[40];
174         memset(provdata, 0, sizeof(*provdata));
175         ast_mutex_lock(&provlock);
176         cur = iax_template_find(template, 1);
177         /* If no match, try searching for '*' */
178         if (!cur)
179                 cur = iax_template_find("*", 1);
180         if (cur) {
181                 /* found it -- add information elements as appropriate */
182                 if (force || strlen(cur->user))
183                         iax_ie_append_str(provdata, PROV_IE_USER, cur->user);
184                 if (force || strlen(cur->pass))
185                         iax_ie_append_str(provdata, PROV_IE_PASS, cur->pass);
186                 if (force || strlen(cur->lang))
187                         iax_ie_append_str(provdata, PROV_IE_LANG, cur->lang);
188                 if (force || cur->port)
189                         iax_ie_append_short(provdata, PROV_IE_PORTNO, cur->port);
190                 if (force || cur->server)
191                         iax_ie_append_int(provdata, PROV_IE_SERVERIP, cur->server);
192                 if (force || cur->serverport)
193                         iax_ie_append_short(provdata, PROV_IE_SERVERPORT, cur->serverport);
194                 if (force || cur->altserver)
195                         iax_ie_append_int(provdata, PROV_IE_ALTSERVER, cur->altserver);
196                 if (force || cur->flags)
197                         iax_ie_append_int(provdata, PROV_IE_FLAGS, cur->flags);
198                 if (force || cur->format)
199                         iax_ie_append_int(provdata, PROV_IE_FORMAT, cur->format);
200                 if (force || cur->tos)
201                         iax_ie_append_byte(provdata, PROV_IE_TOS, cur->tos);
202                 
203                 /* Calculate checksum of message so far */
204                 sig = prov_ver_calc(provdata);
205                 if (signature)
206                         *signature = sig;
207                 /* Store signature */
208                 iax_ie_append_int(provdata, PROV_IE_PROVVER, sig);
209                 /* Cache signature for later verification so we need not recalculate all this */
210                 snprintf(tmp, sizeof(tmp), "v0x%08x", sig);
211                 ast_db_put("iax/provisioning/cache", template, tmp);
212         } else
213                 ast_db_put("iax/provisioning/cache", template, "u");
214         ast_mutex_unlock(&provlock);
215         return cur ? 0 : -1;
216 }
217
218 int iax_provision_version(unsigned int *version, const char *template, int force)
219 {
220         char tmp[80] = "";
221         struct iax_ie_data ied;
222         int ret=0;
223         memset(&ied, 0, sizeof(ied));
224
225         ast_mutex_lock(&provlock);
226         ast_db_get("iax/provisioning/cache", template, tmp, sizeof(tmp));
227         if (sscanf(tmp, "v%x", version) != 1) {
228                 if (strcmp(tmp, "u")) {
229                         ret = iax_provision_build(&ied, version, template, force);
230                         if (ret)
231                                 ast_log(LOG_DEBUG, "Unable to create provisioning packet for '%s'\n", template);
232                 } else
233                         ret = -1;
234         } else if (option_debug)
235                 ast_log(LOG_DEBUG, "Retrieved cached version '%s' = '%08x'\n", tmp, *version);
236         ast_mutex_unlock(&provlock);
237         return ret;
238 }
239
240 static int iax_template_parse(struct iax_template *cur, struct ast_config *cfg, char *s, char *def)
241 {
242         struct ast_variable *v;
243         int foundportno = 0;
244         int foundserverportno = 0;
245         int x;
246         struct in_addr ia;
247         struct hostent *hp;
248         struct ast_hostent h;
249         struct iax_template *src, tmp;
250         char *t;
251         if (def) {
252                 t = ast_variable_retrieve(cfg, s ,"template");
253                 src = NULL;
254                 if (t && strlen(t)) {
255                         src = iax_template_find(t, 0);
256                         if (!src)
257                                 ast_log(LOG_WARNING, "Unable to find base template '%s' for creating '%s'.  Trying '%s'\n", t, s, def);
258                         else
259                                 def = t;
260                 } 
261                 if (!src) {
262                         src = iax_template_find(def, 0);
263                         if (!src)
264                                 ast_log(LOG_WARNING, "Unable to locate default base template '%s' for creating '%s', omitting.", def, s);
265                 }
266                 if (!src)
267                         return -1;
268                 ast_mutex_lock(&provlock);      
269                 /* Backup old data */
270                 memcpy(&tmp, cur, sizeof(tmp));
271                 /* Restore from src */
272                 memcpy(cur, src, sizeof(tmp));
273                 /* Restore important headers */
274                 memcpy(cur->name, tmp.name, sizeof(cur->name));
275                 cur->dead = tmp.dead;
276                 cur->next = tmp.next;
277                 ast_mutex_unlock(&provlock);    
278         }
279         if (def)
280                 strncpy(cur->src, def, sizeof(cur->src) - 1);
281         else
282                 cur->src[0] = '\0';
283         v = ast_variable_browse(cfg, s);
284         while(v) {
285                 if (!strcasecmp(v->name, "port") || !strcasecmp(v->name, "serverport")) {
286                         if ((sscanf(v->value, "%i", &x) == 1) && (x > 0) && (x < 65535)) {
287                                 if (!strcasecmp(v->name, "port")) {
288                                         cur->port = x;
289                                         foundportno = 1;
290                                 } else {
291                                         cur->serverport = x;
292                                         foundserverportno = 1;
293                                 }
294                         } else
295                                 ast_log(LOG_WARNING, "Ignoring invalid %s '%s' for '%s' at line %d\n", v->name, v->value, s, v->lineno);
296                 } else if (!strcasecmp(v->name, "server") || !strcasecmp(v->name, "altserver")) {
297                         hp = ast_gethostbyname(v->value, &h);
298                         if (hp) {
299                                 memcpy(&ia, hp->h_addr, sizeof(ia));
300                                 if (!strcasecmp(v->name, "server"))
301                                         cur->server = ntohl(ia.s_addr);
302                                 else
303                                         cur->altserver = ntohl(ia.s_addr);
304                         } else 
305                                 ast_log(LOG_WARNING, "Ignoring invalid %s '%s' for '%s' at line %d\n", v->name, v->value, s, v->lineno);
306                 } else if (!strcasecmp(v->name, "codec")) {
307                         if ((x = ast_getformatbyname(v->value)) > 0) {
308                                 cur->format = x;
309                         } else
310                                 ast_log(LOG_WARNING, "Ignoring invalid codec '%s' for '%s' at line %d\n", v->value, s, v->lineno);
311                 } else if (!strcasecmp(v->name, "tos")) {
312                         if (sscanf(v->value, "%i", &x) == 1)
313                                 cur->tos = x & 0xff;
314                         else if (!strcasecmp(v->value, "lowdelay"))
315                                 cur->tos = IPTOS_LOWDELAY;
316                         else if (!strcasecmp(v->value, "throughput"))
317                                 cur->tos = IPTOS_THROUGHPUT;
318                         else if (!strcasecmp(v->value, "reliability"))
319                                 cur->tos = IPTOS_RELIABILITY;
320                         else if (!strcasecmp(v->value, "mincost"))
321                                 cur->tos = IPTOS_MINCOST;
322                         else if (!strcasecmp(v->value, "none"))
323                                 cur->tos = 0;
324                         else
325                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
326                 } else if (!strcasecmp(v->name, "user")) {
327                         strncpy(cur->user, v->value, sizeof(cur->user) - 1);
328                         if (strcmp(cur->user, v->value))
329                                 ast_log(LOG_WARNING, "Truncating username from '%s' to '%s' for '%s' at line %d\n", v->value, cur->user, s, v->lineno);
330                 } else if (!strcasecmp(v->name, "pass")) {
331                         strncpy(cur->pass, v->value, sizeof(cur->pass) - 1);
332                         if (strcmp(cur->pass, v->value))
333                                 ast_log(LOG_WARNING, "Truncating password from '%s' to '%s' for '%s' at line %d\n", v->value, cur->pass, s, v->lineno);
334                 } else if (!strcasecmp(v->name, "language")) {
335                         strncpy(cur->lang, v->value, sizeof(cur->lang) - 1);
336                         if (strcmp(cur->lang, v->value))
337                                 ast_log(LOG_WARNING, "Truncating language from '%s' to '%s' for '%s' at line %d\n", v->value, cur->lang, s, v->lineno);
338                 } else if (!strcasecmp(v->name, "flags")) {
339                         cur->flags = iax_str2flags(v->value);
340                 } else if (!strncasecmp(v->name, "flags", 5) && strchr(v->name, '+')) {
341                         cur->flags |= iax_str2flags(v->value);
342                 } else if (!strncasecmp(v->name, "flags", 5) && strchr(v->name, '-')) {
343                         cur->flags &= ~iax_str2flags(v->value);
344                 } else if (strcasecmp(v->name, "template")) {
345                         ast_log(LOG_WARNING, "Unknown keyword '%s' in definition of '%s' at line %d\n", v->name, s, v->lineno);
346                 }
347                 v = v->next;
348         }
349         if (!foundportno)
350                 cur->port = IAX_DEFAULT_PORTNO;
351         if (!foundserverportno)
352                 cur->serverport = IAX_DEFAULT_PORTNO;
353         return 0;
354 }
355
356 static int iax_process_template(struct ast_config *cfg, char *s, char *def)
357 {
358         /* Find an already existing one if there */
359         struct iax_template *cur;
360         int mallocd = 0;
361         cur = templates;
362         while(cur) {
363                 if (!strcasecmp(cur->name, s))
364                         break;
365                 cur = cur->next;
366         }
367         if (!cur) {
368                 mallocd = 1;
369                 cur = malloc(sizeof(struct iax_template));
370                 if (!cur) {
371                         ast_log(LOG_WARNING, "Out of memory!\n");
372                         return -1;
373                 }
374                 /* Initialize entry */
375                 memset(cur, 0, sizeof(*cur));
376                 strncpy(cur->name, s, sizeof(cur->name) - 1);
377                 cur->dead = 1;
378         }
379         if (!iax_template_parse(cur, cfg, s, def))
380                 cur->dead = 0;
381
382         /* Link if we're mallocd */
383         if (mallocd) {
384                 ast_mutex_lock(&provlock);
385                 cur->next = templates;
386                 templates = cur;
387                 ast_mutex_unlock(&provlock);
388         }
389         return 0;
390 }
391
392 static char show_provisioning_usage[] = 
393 "Usage: iax show provisioning [template]\n"
394 "       Lists all known IAX provisioning templates or a\n"
395 "       specific one if specified.\n";
396
397 static const char *ifthere(const char *s)
398 {
399         if (strlen(s))
400                 return s;
401         else
402                 return "<unspecified>";
403 }
404
405 static const char *iax_server(char *a, int alen, unsigned int addr)
406 {
407         struct in_addr ia;
408         if (!addr)
409                 return "<unspecified>";
410         ia.s_addr = htonl(addr);
411         return ast_inet_ntoa(a, alen, ia);
412 }
413
414
415 static int iax_show_provisioning(int fd, int argc, char *argv[])
416 {
417         struct iax_template *cur;
418         char iabuf[80]; /* Has to be big enough for 'flags' too */
419         int found = 0;
420         if ((argc != 3) && (argc != 4))
421                 return RESULT_SHOWUSAGE;
422         ast_mutex_lock(&provlock);
423         for (cur = templates;cur;cur = cur->next) {
424                 if ((argc == 3) || (!strcasecmp(argv[3], cur->name)))  {
425                         if (found) ast_cli(fd, "\n");
426                         ast_cli(fd, "== %s ==\n", cur->name);
427                         ast_cli(fd, "Base Templ:   %s\n", strlen(cur->src) ? cur->src : "<none>");
428                         ast_cli(fd, "Username:     %s\n", ifthere(cur->user));
429                         ast_cli(fd, "Secret:       %s\n", ifthere(cur->pass));
430                         ast_cli(fd, "Language:     %s\n", ifthere(cur->lang));
431                         ast_cli(fd, "Bind Port:    %d\n", cur->port);
432                         ast_cli(fd, "Server:       %s\n", iax_server(iabuf, sizeof(iabuf), cur->server));
433                         ast_cli(fd, "Server Port:  %d\n", cur->serverport);
434                         ast_cli(fd, "Alternate:    %s\n", iax_server(iabuf, sizeof(iabuf), cur->altserver));
435                         ast_cli(fd, "Flags:        %s\n", iax_provflags2str(iabuf, sizeof(iabuf), cur->flags));
436                         ast_cli(fd, "Format:       %s\n", ast_getformatname(cur->format));
437                         ast_cli(fd, "TOS:          %d\n", cur->tos);
438                         found++;
439                 }
440         }
441         ast_mutex_unlock(&provlock);
442         if (!found) {
443                 if (argc == 3)
444                         ast_cli(fd, "No provisioning templates found\n");
445                 else
446                         ast_cli(fd, "No provisioning template matching '%s' found\n", argv[3]);
447         }
448         return RESULT_SUCCESS;
449 }
450
451 static struct ast_cli_entry  cli_show_provisioning = 
452         { { "iax2", "show", "provisioning", NULL }, iax_show_provisioning, "Show iax provisioning", show_provisioning_usage, iax_prov_complete_template };
453
454 static int iax_provision_init(void)
455 {
456         ast_cli_register(&cli_show_provisioning);
457         provinit = 1;
458         return 0;
459 }
460
461 int iax_provision_unload(void)
462 {
463         provinit = 0;
464         ast_cli_unregister(&cli_show_provisioning);
465         return 0;
466 }
467
468 int iax_provision_reload(void)
469 {
470         struct ast_config *cfg;
471         struct iax_template *cur, *prev, *next;
472         char *cat;
473         int found = 0;
474         if (!provinit)
475                 iax_provision_init();
476         /* Mark all as dead.  No need for locking */
477         cur = templates;
478         while(cur) {
479                 cur->dead = 1;
480                 cur = cur->next;
481         }
482         cfg = ast_load("iaxprov.conf");
483         if (cfg) {
484                 /* Load as appropriate */
485                 cat = ast_category_browse(cfg, NULL);
486                 while(cat) {
487                         if (strcasecmp(cat, "general")) {
488                                 iax_process_template(cfg, cat, found ? "default" : NULL);
489                                 found++;
490                                 if (option_verbose > 2)
491                                         ast_verbose(VERBOSE_PREFIX_3 "Loaded provisioning template '%s'\n", cat);
492                         }
493                         cat = ast_category_browse(cfg, cat);
494                 }
495         } else
496                 ast_log(LOG_NOTICE, "No IAX provisioning configuration found, IAX provisioning disabled.\n");
497         ast_mutex_lock(&provlock);
498         /* Drop dead entries while locked */
499         prev = NULL;
500         cur = templates;
501         while(cur) {
502                 next = cur->next;
503                 if (cur->dead) {
504                         if (prev)
505                                 prev->next = next;
506                         else
507                                 templates = next;
508                         free(cur);
509                 } else 
510                         prev = cur;
511                 cur = next;
512         }
513         ast_mutex_unlock(&provlock);
514         /* Purge cached signature DB entries */
515         ast_db_deltree("iax/provisioning/cache", NULL);
516         return 0;
517         
518 }