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