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