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