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