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