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