Merged revisions 140488 via svnmerge from
[asterisk/asterisk.git] / res / res_phoneprov.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  * Matthew Brooks <mbrooks@digium.com>
8  * Terry Wilson <twilson@digium.com>
9  *
10  * See http://www.asterisk.org for more information about
11  * the Asterisk project. Please do not directly contact
12  * any of the maintainers of this project for assistance;
13  * the project provides a web site, mailing lists and IRC
14  * channels for your use.
15  *
16  * This program is free software, distributed under the terms of
17  * the GNU General Public License Version 2. See the LICENSE file
18  * at the top of the source tree.
19  */
20
21 /*! \file
22  *
23  * \brief Phone provisioning application for the asterisk internal http server
24  *
25  * \author Matthew Brooks <mbrooks@digium.com>
26  * \author Terry Wilson <twilson@digium.com>
27  */
28
29 #include "asterisk.h"
30
31 #include <sys/ioctl.h>
32 #include <sys/socket.h>
33 #include <net/if.h>
34 #ifdef SOLARIS
35 #include <sys/sockio.h>
36 #endif
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 96773 $")
38
39 #include "asterisk/channel.h"
40 #include "asterisk/file.h"
41 #include "asterisk/paths.h"
42 #include "asterisk/pbx.h"
43 #include "asterisk/cli.h"
44 #include "asterisk/module.h"
45 #include "asterisk/http.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/app.h"
48 #include "asterisk/strings.h"
49 #include "asterisk/stringfields.h"
50 #include "asterisk/options.h"
51 #include "asterisk/config.h"
52 #include "asterisk/acl.h"
53 #include "asterisk/astobj2.h"
54 #include "asterisk/ast_version.h"
55
56 #ifdef LOW_MEMORY
57 #define MAX_PROFILE_BUCKETS 1
58 #define MAX_ROUTE_BUCKETS 1
59 #define MAX_USER_BUCKETS 1
60 #else
61 #define MAX_PROFILE_BUCKETS 17
62 #define MAX_ROUTE_BUCKETS 563
63 #define MAX_USER_BUCKETS 563
64 #endif /* LOW_MEMORY */
65
66 #define VAR_BUF_SIZE 4096
67
68 /*! \brief for use in lookup_iface */
69 static struct in_addr __ourip = { .s_addr = 0x00000000, };
70
71 /* \note This enum and the pp_variable_list must be in the same order or
72  * bad things happen! */
73 enum pp_variables {
74         PP_MACADDRESS,
75         PP_USERNAME,
76         PP_FULLNAME,
77         PP_SECRET,
78         PP_LABEL,
79         PP_CALLERID,
80         PP_TIMEZONE,
81         PP_LINENUMBER,
82         PP_VAR_LIST_LENGTH,     /* This entry must always be the last in the list */
83 };
84
85 /*! \brief Lookup table to translate between users.conf property names and
86  * variables for use in phoneprov templates */
87 static const struct pp_variable_lookup {
88         enum pp_variables id;
89         const char * const user_var;
90         const char * const template_var;
91 } pp_variable_list[] = {
92         { PP_MACADDRESS, "macaddress", "MAC" },
93         { PP_USERNAME, "username", "USERNAME" },
94         { PP_FULLNAME, "fullname", "DISPLAY_NAME" },
95         { PP_SECRET, "secret", "SECRET" },
96         { PP_LABEL, "label", "LABEL" },
97         { PP_CALLERID, "cid_number", "CALLERID" },
98         { PP_TIMEZONE, "timezone", "TIMEZONE" },
99         { PP_LINENUMBER, "linenumber", "LINE" },
100 };
101
102 /*! \brief structure to hold file data */
103 struct phoneprov_file {
104         AST_DECLARE_STRING_FIELDS(
105                 AST_STRING_FIELD(format);       /*!< After variable substitution, becomes route->uri */
106                 AST_STRING_FIELD(template); /*!< Template/physical file location */
107                 AST_STRING_FIELD(mime_type);/*!< Mime-type of the file */
108         );
109         AST_LIST_ENTRY(phoneprov_file) entry;
110 };
111
112 /*! \brief structure to hold phone profiles read from phoneprov.conf */
113 struct phone_profile {
114         AST_DECLARE_STRING_FIELDS(
115                 AST_STRING_FIELD(name); /*!< Name of phone profile */
116                 AST_STRING_FIELD(default_mime_type);    /*!< Default mime type if it isn't provided */
117                 AST_STRING_FIELD(staticdir);    /*!< Subdirectory that static files are stored in */
118         );
119         struct varshead *headp; /*!< List of variables set with 'setvar' in phoneprov.conf */
120         AST_LIST_HEAD_NOLOCK(, phoneprov_file) static_files;    /*!< List of static files */
121         AST_LIST_HEAD_NOLOCK(, phoneprov_file) dynamic_files;   /*!< List of dynamic files */
122 };
123
124 struct extension {
125         AST_DECLARE_STRING_FIELDS(
126                 AST_STRING_FIELD(name);
127         );
128         int index;
129         struct varshead *headp; /*!< List of variables to substitute into templates */
130         AST_LIST_ENTRY(extension) entry;
131 };
132
133 /*! \brief structure to hold users read from users.conf */
134 struct user {
135         AST_DECLARE_STRING_FIELDS(
136                 AST_STRING_FIELD(macaddress);   /*!< Mac address of user's phone */
137         );
138         struct phone_profile *profile;  /*!< Profile the phone belongs to */
139         AST_LIST_HEAD_NOLOCK(, extension) extensions;
140 };
141
142 /*! \brief structure to hold http routes (valid URIs, and the files they link to) */
143 struct http_route {
144         AST_DECLARE_STRING_FIELDS(
145                 AST_STRING_FIELD(uri);  /*!< The URI requested */
146         );
147         struct phoneprov_file *file;    /*!< The file that links to the URI */
148         struct user *user;      /*!< The user that has variables to substitute into the file
149                                                  * NULL in the case of a static route */
150 };
151
152 static struct ao2_container *profiles;
153 static struct ao2_container *http_routes;
154 static struct ao2_container *users;
155
156 /*! \brief Extensions whose mime types we think we know */
157 static struct {
158         char *ext;
159         char *mtype;
160 } mimetypes[] = {
161         { "png", "image/png" },
162         { "xml", "text/xml" },
163         { "jpg", "image/jpeg" },
164         { "js", "application/x-javascript" },
165         { "wav", "audio/x-wav" },
166         { "mp3", "audio/mpeg" },
167 };
168
169 static char global_server[80] = "";     /*!< Server to substitute into templates */
170 static char global_serverport[6] = "";  /*!< Server port to substitute into templates */
171 static char global_default_profile[80] = "";    /*!< Default profile to use if one isn't specified */   
172
173 /*! \brief List of global variables currently available: VOICEMAIL_EXTEN, EXTENSION_LENGTH */
174 static struct varshead global_variables;
175 static ast_mutex_t globals_lock;
176
177 /*! \brief Return mime type based on extension */
178 static char *ftype2mtype(const char *ftype)
179 {
180         int x;
181
182         if (ast_strlen_zero(ftype))
183                 return NULL;
184
185         for (x = 0;x < ARRAY_LEN(mimetypes);x++) {
186                 if (!strcasecmp(ftype, mimetypes[x].ext))
187                         return mimetypes[x].mtype;
188         }
189         
190         return NULL;
191 }
192
193 /* iface is the interface (e.g. eth0); address is the return value */
194 static int lookup_iface(const char *iface, struct in_addr *address)
195 {
196         int mysock, res = 0;
197         struct ifreq ifr;
198         struct sockaddr_in *sin;
199
200         memset(&ifr, 0, sizeof(ifr));
201         ast_copy_string(ifr.ifr_name, iface, sizeof(ifr.ifr_name));
202
203         mysock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
204         if (mysock < 0) {
205                 ast_log(LOG_ERROR, "Failed to create socket: %s\n", strerror(errno));
206                 return -1;
207         }
208
209         res = ioctl(mysock, SIOCGIFADDR, &ifr);
210
211         close(mysock);
212
213         if (res < 0) {
214                 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
215                 memcpy(address, &__ourip, sizeof(__ourip));
216                 return -1;
217         } else {
218                 sin = (struct sockaddr_in *)&ifr.ifr_addr;
219                 memcpy(address, &sin->sin_addr, sizeof(*address));
220                 return 0;
221         }
222 }
223
224 static struct phone_profile *unref_profile(struct phone_profile *prof)
225 {
226         ao2_ref(prof, -1);
227
228         return NULL;
229 }
230
231 /*! \brief Return a phone profile looked up by name */
232 static struct phone_profile *find_profile(const char *name)
233 {
234         struct phone_profile tmp = {
235                 .name = name,
236         };
237
238         return ao2_find(profiles, &tmp, OBJ_POINTER);
239 }
240
241 static int profile_hash_fn(const void *obj, const int flags)
242 {
243         const struct phone_profile *profile = obj;
244         
245         return ast_str_hash(profile->name);
246 }
247
248 static int profile_cmp_fn(void *obj, void *arg, int flags)
249 {
250         const struct phone_profile *profile1 = obj, *profile2 = arg;
251
252         return !strcasecmp(profile1->name, profile2->name) ? CMP_MATCH | CMP_STOP : 0;
253 }
254
255 static void delete_file(struct phoneprov_file *file)
256 {
257         ast_string_field_free_memory(file);
258         free(file);
259 }
260
261 static void profile_destructor(void *obj)
262 {
263         struct phone_profile *profile = obj;
264         struct phoneprov_file *file;
265         struct ast_var_t *var;
266
267         while ((file = AST_LIST_REMOVE_HEAD(&profile->static_files, entry)))
268                 delete_file(file);
269
270         while ((file = AST_LIST_REMOVE_HEAD(&profile->dynamic_files, entry)))
271                 delete_file(file);
272
273         while ((var = AST_LIST_REMOVE_HEAD(profile->headp, entries)))
274                 ast_var_delete(var);
275
276         ast_free(profile->headp);
277         ast_string_field_free_memory(profile);
278 }
279
280 static struct http_route *unref_route(struct http_route *route)
281 {
282         ao2_ref(route, -1);
283
284         return NULL;
285 }
286
287 static int routes_hash_fn(const void *obj, const int flags)
288 {
289         const struct http_route *route = obj;
290         
291         return ast_str_hash(route->uri);
292 }
293
294 static int routes_cmp_fn(void *obj, void *arg, int flags)
295 {
296         const struct http_route *route1 = obj, *route2 = arg;
297
298         return !strcmp(route1->uri, route2->uri) ? CMP_MATCH | CMP_STOP : 0;
299 }
300
301 static void route_destructor(void *obj)
302 {
303         struct http_route *route = obj;
304
305         ast_string_field_free_memory(route);
306 }
307
308 /*! \brief Read a TEXT file into a string and return the length */
309 static int load_file(const char *filename, char **ret)
310 {
311         int len = 0;
312         FILE *f;
313         
314         if (!(f = fopen(filename, "r"))) {
315                 *ret = NULL;
316                 return -1;
317         }
318
319         fseek(f, 0, SEEK_END);
320         len = ftell(f);
321         fseek(f, 0, SEEK_SET);
322         if (!(*ret = ast_malloc(len + 1)))
323                 return -2;
324
325         if (len != fread(*ret, sizeof(char), len, f)) {
326                 free(*ret);
327                 *ret = NULL;
328                 return -3;
329         }
330
331         fclose(f);
332
333         (*ret)[len] = '\0';
334
335         return len;
336 }
337
338 /*! \brief Set all timezone-related variables based on a zone (i.e. America/New_York)
339         \param headp pointer to list of user variables
340         \param zone A time zone. NULL sets variables based on timezone of the machine
341 */
342 static void set_timezone_variables(struct varshead *headp, const char *zone)
343 {
344         time_t utc_time;
345         int dstenable;
346         time_t dststart;
347         time_t dstend;
348         struct ast_tm tm_info;
349         int tzoffset;
350         char buffer[21];
351         struct ast_var_t *var;
352         struct timeval when;
353
354         time(&utc_time);
355         ast_get_dst_info(&utc_time, &dstenable, &dststart, &dstend, &tzoffset, zone);
356         snprintf(buffer, sizeof(buffer), "%d", tzoffset);
357         var = ast_var_assign("TZOFFSET", buffer);
358         if (var)
359                 AST_LIST_INSERT_TAIL(headp, var, entries); 
360
361         if (!dstenable)
362                 return;
363
364         if ((var = ast_var_assign("DST_ENABLE", "1")))
365                 AST_LIST_INSERT_TAIL(headp, var, entries);
366
367         when.tv_sec = dststart; 
368         ast_localtime(&when, &tm_info, zone);
369
370         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mon+1);
371         if ((var = ast_var_assign("DST_START_MONTH", buffer)))
372                 AST_LIST_INSERT_TAIL(headp, var, entries);
373
374         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mday);
375         if ((var = ast_var_assign("DST_START_MDAY", buffer)))
376                 AST_LIST_INSERT_TAIL(headp, var, entries);
377
378         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_hour);
379         if ((var = ast_var_assign("DST_START_HOUR", buffer)))
380                 AST_LIST_INSERT_TAIL(headp, var, entries);
381
382         when.tv_sec = dstend;
383         ast_localtime(&when, &tm_info, zone);
384
385         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mon + 1);
386         if ((var = ast_var_assign("DST_END_MONTH", buffer)))
387                 AST_LIST_INSERT_TAIL(headp, var, entries);
388
389         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mday);
390         if ((var = ast_var_assign("DST_END_MDAY", buffer)))
391                 AST_LIST_INSERT_TAIL(headp, var, entries);
392
393         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_hour);
394         if ((var = ast_var_assign("DST_END_HOUR", buffer)))
395                 AST_LIST_INSERT_TAIL(headp, var, entries);
396 }
397
398 /*! \brief Callback that is executed everytime an http request is received by this module */
399 static struct ast_str *phoneprov_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *vars, struct ast_variable *headers, int *status, char **title, int *contentlength)
400 {
401         struct http_route *route;
402         struct http_route search_route = {
403                 .uri = uri,
404         };
405         struct ast_str *result = ast_str_create(512);
406         char path[PATH_MAX];
407         char *file = NULL;
408         int len;
409         int fd;
410         char buf[256];
411         struct timeval now = ast_tvnow();
412         struct ast_tm tm;
413
414         if (!(route = ao2_find(http_routes, &search_route, OBJ_POINTER))) {
415                 goto out404;
416         }
417
418         snprintf(path, sizeof(path), "%s/phoneprov/%s", ast_config_AST_DATA_DIR, route->file->template);
419
420         if (!route->user) { /* Static file */
421
422                 fd = open(path, O_RDONLY);
423                 if (fd < 0) {
424                         goto out500;
425                 }
426
427                 len = lseek(fd, 0, SEEK_END);
428                 lseek(fd, 0, SEEK_SET);
429                 if (len < 0) {
430                         ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, len);
431                         close(fd);
432                         goto out500;
433                 }
434
435                 ast_strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S %Z", ast_localtime(&now, &tm, "GMT"));
436                 fprintf(ser->f, "HTTP/1.1 200 OK\r\n"
437                         "Server: Asterisk/%s\r\n"
438                         "Date: %s\r\n"
439                         "Connection: close\r\n"
440                         "Cache-Control: no-cache, no-store\r\n"
441                         "Content-Length: %d\r\n"
442                         "Content-Type: %s\r\n\r\n",
443                         ast_get_version(), buf, len, route->file->mime_type);
444                 
445                 while ((len = read(fd, buf, sizeof(buf))) > 0) {
446                         fwrite(buf, 1, len, ser->f);
447                 }
448
449                 close(fd);
450                 route = unref_route(route);
451                 return NULL;
452         } else { /* Dynamic file */
453                 int bufsize;
454                 char *tmp;
455
456                 len = load_file(path, &file);
457                 if (len < 0) {
458                         ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, len);
459                         if (file) {
460                                 ast_free(file);
461                         }
462
463                         goto out500;
464                 }
465
466                 if (!file) {
467                         goto out500;
468                 }
469
470                 /* XXX This is a hack -- maybe sum length of all variables in route->user->headp and add that? */
471                 bufsize = len + VAR_BUF_SIZE;
472                 
473                 /* malloc() instead of alloca() here, just in case the file is bigger than
474                  * we have enough stack space for. */
475                 if (!(tmp = ast_calloc(1, bufsize))) {
476                         if (file) {
477                                 ast_free(file);
478                         }
479
480                         goto out500;
481                 }
482
483                 /* Unless we are overridden by serveriface or serveraddr, we set the SERVER variable to
484                  * the IP address we are listening on that the phone contacted for this config file */
485                 if (ast_strlen_zero(global_server)) {
486                         struct sockaddr name;
487                         socklen_t namelen = sizeof(name);
488                         int res;
489
490                         if ((res = getsockname(ser->fd, &name, &namelen))) {
491                                 ast_log(LOG_WARNING, "Could not get server IP, breakage likely.\n");
492                         } else {
493                                 struct ast_var_t *var;
494                                 struct extension *exten_iter;
495
496                                 if ((var = ast_var_assign("SERVER", ast_inet_ntoa(((struct sockaddr_in *)&name)->sin_addr)))) {
497                                         AST_LIST_TRAVERSE(&route->user->extensions, exten_iter, entry) {
498                                                 AST_LIST_INSERT_TAIL(exten_iter->headp, var, entries);
499                                         }
500                                 }
501                         }
502                 }
503
504                 pbx_substitute_variables_varshead(AST_LIST_FIRST(&route->user->extensions)->headp, file, tmp, bufsize);
505         
506                 if (file) {
507                         ast_free(file);
508                 }
509
510                 ast_str_append(&result, 0,
511                         "Content-Type: %s\r\n"
512                         "Content-length: %d\r\n"
513                         "\r\n"
514                         "%s", route->file->mime_type, (int) strlen(tmp), tmp);
515
516                 if (tmp) {
517                         ast_free(tmp);
518                 }
519
520                 route = unref_route(route);
521
522                 return result;
523         }
524
525 out404:
526         *status = 404;
527         *title = strdup("Not Found");
528         *contentlength = 0;
529         return ast_http_error(404, "Not Found", NULL, "Nothing to see here.  Move along.");
530
531 out500:
532         route = unref_route(route);
533         *status = 500;
534         *title = strdup("Internal Server Error");
535         *contentlength = 0;
536         return ast_http_error(500, "Internal Error", NULL, "An internal error has occured.");
537 }
538
539 /*! \brief Build a route structure and add it to the list of available http routes
540         \param pp_file File to link to the route
541         \param user User to link to the route (NULL means static route)
542         \param uri URI of the route
543 */
544 static void build_route(struct phoneprov_file *pp_file, struct user *user, char *uri)
545 {
546         struct http_route *route;
547         
548         if (!(route = ao2_alloc(sizeof(*route), route_destructor))) {
549                 return;
550         }
551
552         if (ast_string_field_init(route, 32)) {
553                 ast_log(LOG_ERROR, "Couldn't create string fields for %s\n", pp_file->format);
554                 route = unref_route(route);
555                 return;
556         }
557
558         ast_string_field_set(route, uri, S_OR(uri, pp_file->format));
559         route->user = user;
560         route->file = pp_file;
561
562         ao2_link(http_routes, route);
563
564         route = unref_route(route);
565 }
566
567 /*! \brief Build a phone profile and add it to the list of phone profiles
568         \param name the name of the profile
569         \param v ast_variable from parsing phoneprov.conf
570 */
571 static void build_profile(const char *name, struct ast_variable *v)
572 {
573         struct phone_profile *profile;
574         struct ast_var_t *var;
575
576         if (!(profile = ao2_alloc(sizeof(*profile), profile_destructor))) {
577                 return;
578         }
579
580         if (ast_string_field_init(profile, 32)) {
581                 profile = unref_profile(profile);
582                 return;
583         }
584         
585         if (!(profile->headp = ast_calloc(1, sizeof(*profile->headp)))) {
586                 profile = unref_profile(profile);
587                 return;
588         }
589
590         AST_LIST_HEAD_INIT_NOLOCK(&profile->static_files);
591         AST_LIST_HEAD_INIT_NOLOCK(&profile->dynamic_files);
592
593         ast_string_field_set(profile, name, name);
594         for (; v; v = v->next) {
595                 if (!strcasecmp(v->name, "mime_type")) {
596                         ast_string_field_set(profile, default_mime_type, v->value);
597                 } else if (!strcasecmp(v->name, "setvar")) {
598                         struct ast_var_t *variable;
599                         char *value_copy = ast_strdupa(v->value);
600
601                         AST_DECLARE_APP_ARGS(args,
602                                 AST_APP_ARG(varname);
603                                 AST_APP_ARG(varval);
604                         );
605                         
606                         AST_NONSTANDARD_APP_ARGS(args, value_copy, '=');
607                         do {
608                                 if (ast_strlen_zero(args.varname) || ast_strlen_zero(args.varval))
609                                         break;
610                                 args.varname = ast_strip(args.varname);
611                                 args.varval = ast_strip(args.varval);
612                                 if (ast_strlen_zero(args.varname) || ast_strlen_zero(args.varval))
613                                         break;
614                                 if ((variable = ast_var_assign(args.varname, args.varval)))
615                                         AST_LIST_INSERT_TAIL(profile->headp, variable, entries);
616                         } while (0);
617                 } else if (!strcasecmp(v->name, "staticdir")) {
618                         ast_string_field_set(profile, staticdir, v->value);
619                 } else {
620                         struct phoneprov_file *pp_file;
621                         char *file_extension;
622                         char *value_copy = ast_strdupa(v->value); 
623
624                         AST_DECLARE_APP_ARGS(args,
625                                 AST_APP_ARG(filename);
626                                 AST_APP_ARG(mimetype);
627                         );
628
629                         if (!(pp_file = ast_calloc(1, sizeof(*pp_file)))) {
630                                 profile = unref_profile(profile);
631                                 return;
632                         }
633                         if (ast_string_field_init(pp_file, 32)) {
634                                 ast_free(pp_file);
635                                 profile = unref_profile(profile);
636                                 return;
637                         }
638
639                         if ((file_extension = strrchr(pp_file->format, '.')))
640                                 file_extension++;
641
642                         AST_STANDARD_APP_ARGS(args, value_copy);
643
644                         /* Mime type order of preference
645                          * 1) Specific mime-type defined for file in profile
646                          * 2) Mime determined by extension
647                          * 3) Default mime type specified in profile
648                          * 4) text/plain
649                          */
650                         ast_string_field_set(pp_file, mime_type, S_OR(args.mimetype, (S_OR(S_OR(ftype2mtype(file_extension), profile->default_mime_type), "text/plain"))));
651
652                         if (!strcasecmp(v->name, "static_file")) {
653                                 ast_string_field_set(pp_file, format, args.filename);
654                                 ast_string_field_build(pp_file, template, "%s%s", profile->staticdir, args.filename);
655                                 AST_LIST_INSERT_TAIL(&profile->static_files, pp_file, entry);
656                                 /* Add a route for the static files, as their filenames won't change per-user */
657                                 build_route(pp_file, NULL, NULL);
658                         } else {
659                                 ast_string_field_set(pp_file, format, v->name);
660                                 ast_string_field_set(pp_file, template, args.filename);
661                                 AST_LIST_INSERT_TAIL(&profile->dynamic_files, pp_file, entry);
662                         }
663                 }
664         }
665
666         /* Append the global variables to the variables list for this profile.
667          * This is for convenience later, when we need to provide a single
668          * variable list for use in substitution. */
669         ast_mutex_lock(&globals_lock);
670         AST_LIST_TRAVERSE(&global_variables, var, entries) {
671                 struct ast_var_t *new_var;
672                 if ((new_var = ast_var_assign(var->name, var->value))) {
673                         AST_LIST_INSERT_TAIL(profile->headp, new_var, entries);
674                 }
675         }
676         ast_mutex_unlock(&globals_lock);
677
678         ao2_link(profiles, profile);
679
680         profile = unref_profile(profile);
681 }
682
683 static struct extension *delete_extension(struct extension *exten)
684 {
685         struct ast_var_t *var;
686         while ((var = AST_LIST_REMOVE_HEAD(exten->headp, entries))) {
687                 ast_var_delete(var);
688         }
689         ast_free(exten->headp);
690         ast_string_field_free_memory(exten);
691
692         ast_free(exten);
693
694         return NULL;
695 }
696
697 static struct extension *build_extension(struct ast_config *cfg, const char *name)
698 {
699         struct extension *exten;
700         struct ast_var_t *var;
701         const char *tmp;
702         int i;
703
704         if (!(exten = ast_calloc(1, sizeof(*exten)))) {
705                 return NULL;
706         }
707         
708         if (ast_string_field_init(exten, 32)) {
709                 ast_free(exten);
710                 exten = NULL;
711                 return NULL;
712         }
713         
714         ast_string_field_set(exten, name, name);
715         
716         if (!(exten->headp = ast_calloc(1, sizeof(*exten->headp)))) {
717                 ast_free(exten);
718                 exten = NULL;
719                 return NULL;
720         }
721
722         for (i = 0; i < PP_VAR_LIST_LENGTH; i++) {
723                 tmp = ast_variable_retrieve(cfg, name, pp_variable_list[i].user_var);
724
725                 /* If we didn't get a USERNAME variable, set it to the user->name */
726                 if (i == PP_USERNAME && !tmp) {
727                         if ((var = ast_var_assign(pp_variable_list[PP_USERNAME].template_var, exten->name))) {
728                                 AST_LIST_INSERT_TAIL(exten->headp, var, entries);
729                         }
730                         continue;
731                 } else if (i == PP_TIMEZONE) {
732                         /* perfectly ok if tmp is NULL, will set variables based on server's time zone */
733                         set_timezone_variables(exten->headp, tmp);
734                 } else if (i == PP_LINENUMBER) {
735                         if (!tmp) {
736                                 tmp = "1";
737                         }
738                         exten->index = atoi(tmp);
739                 }
740
741                 if (tmp && (var = ast_var_assign(pp_variable_list[i].template_var, tmp))) {
742                         AST_LIST_INSERT_TAIL(exten->headp, var, entries);
743                 }
744         }
745
746         if (!ast_strlen_zero(global_server)) {
747                 if ((var = ast_var_assign("SERVER", global_server)))
748                         AST_LIST_INSERT_TAIL(exten->headp, var, entries);
749         }
750
751         if (!ast_strlen_zero(global_serverport)) {
752                 if ((var = ast_var_assign("SERVER_PORT", global_serverport)))
753                         AST_LIST_INSERT_TAIL(exten->headp, var, entries);
754         }
755
756         return exten;
757 }
758
759 static struct user *unref_user(struct user *user)
760 {
761         ao2_ref(user, -1);
762
763         return NULL;
764 }
765
766 /*! \brief Return a user looked up by name */
767 static struct user *find_user(const char *macaddress)
768 {
769         struct user tmp = {
770                 .macaddress = macaddress,
771         };
772
773         return ao2_find(users, &tmp, OBJ_POINTER);
774 }
775
776 static int users_hash_fn(const void *obj, const int flags)
777 {
778         const struct user *user = obj;
779         
780         return ast_str_hash(user->macaddress);
781 }
782
783 static int users_cmp_fn(void *obj, void *arg, int flags)
784 {
785         const struct user *user1 = obj, *user2 = arg;
786
787         return !strcasecmp(user1->macaddress, user2->macaddress) ? CMP_MATCH | CMP_STOP : 0;
788 }
789
790 /*! \brief Free all memory associated with a user */
791 static void user_destructor(void *obj)
792 {
793         struct user *user = obj;
794         struct extension *exten;
795
796         while ((exten = AST_LIST_REMOVE_HEAD(&user->extensions, entry))) {
797                 exten = delete_extension(exten);
798         }
799
800         if (user->profile) {
801                 user->profile = unref_profile(user->profile);
802         }
803         
804         ast_string_field_free_memory(user);
805 }
806
807 /*! \brief Delete all users */
808 static void delete_users(void)
809 {
810         struct ao2_iterator i;
811         struct user *user;
812
813         i = ao2_iterator_init(users, 0);
814         while ((user = ao2_iterator_next(&i))) {
815                 ao2_unlink(users, user);
816                 user = unref_user(user);
817         }
818 }
819
820 /*! \brief Build and return a user structure based on gathered config data */
821 static struct user *build_user(const char *mac, struct phone_profile *profile)
822 {
823         struct user *user;
824
825                 
826         if (!(user = ao2_alloc(sizeof(*user), user_destructor))) {
827                 profile = unref_profile(profile);
828                 return NULL;
829         }
830         
831         if (ast_string_field_init(user, 32)) {
832                 profile = unref_profile(profile);
833                 user = unref_user(user);
834                 return NULL;
835         }
836
837         ast_string_field_set(user, macaddress, mac);
838         user->profile = profile; /* already ref counted by find_profile */
839
840         return user;
841 }
842
843 /*! \brief Add an extension to a user ordered by index/linenumber */
844 static int add_user_extension(struct user *user, struct extension *exten)
845 {
846         struct ast_var_t *var;
847
848         /* Append profile variables here, and substitute variables on profile
849          * setvars, so that we can use user specific variables in them */
850         AST_LIST_TRAVERSE(user->profile->headp, var, entries) {
851                 char expand_buf[VAR_BUF_SIZE] = {0,};
852                 struct ast_var_t *var2;
853
854                 pbx_substitute_variables_varshead(exten->headp, var->value, expand_buf, sizeof(expand_buf));
855                 if ((var2 = ast_var_assign(var->name, expand_buf)))
856                         AST_LIST_INSERT_TAIL(exten->headp, var2, entries);
857         }
858
859         if (AST_LIST_EMPTY(&user->extensions)) {
860                 AST_LIST_INSERT_HEAD(&user->extensions, exten, entry);
861         } else {
862                 struct extension *exten_iter;
863
864                 AST_LIST_TRAVERSE_SAFE_BEGIN(&user->extensions, exten_iter, entry) {
865                         if (exten->index < exten_iter->index) {
866                                 AST_LIST_INSERT_BEFORE_CURRENT(exten, entry);
867                         } else if (exten->index == exten_iter->index) {
868                                 ast_log(LOG_WARNING, "Duplicate linenumber=%d for %s\n", exten->index, user->macaddress);
869                                 return -1;
870                         } else if (!AST_LIST_NEXT(exten_iter, entry)) {
871                                 AST_LIST_INSERT_TAIL(&user->extensions, exten, entry);
872                         }
873                 }
874                 AST_LIST_TRAVERSE_SAFE_END;
875         }
876
877         return 0;
878 }
879
880 /*! \brief Add an http route for dynamic files attached to the profile of the user */
881 static int build_user_routes(struct user *user)
882 {
883         struct phoneprov_file *pp_file;
884
885         AST_LIST_TRAVERSE(&user->profile->dynamic_files, pp_file, entry) {
886                 char expand_buf[VAR_BUF_SIZE] = { 0, };
887
888                 pbx_substitute_variables_varshead(AST_LIST_FIRST(&user->extensions)->headp, pp_file->format, expand_buf, sizeof(expand_buf));
889                 build_route(pp_file, user, expand_buf);
890         }
891
892         return 0;
893 }
894
895 /* \brief Parse config files and create appropriate structures */
896 static int set_config(void)
897 {
898         struct ast_config *cfg, *phoneprov_cfg;
899         char *cat;
900         struct ast_variable *v;
901         struct ast_flags config_flags = { 0 };
902         struct ast_var_t *var;
903
904         /* Try to grab the port from sip.conf.  If we don't get it here, we'll set it
905          * to whatever is set in phoneprov.conf or default to 5060 */
906         if ((cfg = ast_config_load("sip.conf", config_flags))) {
907                 ast_copy_string(global_serverport, S_OR(ast_variable_retrieve(cfg, "general", "bindport"), "5060"), sizeof(global_serverport));
908                 ast_config_destroy(cfg);
909         }
910
911         if (!(cfg = ast_config_load("users.conf", config_flags))) {
912                 ast_log(LOG_WARNING, "Unable to load users.cfg\n");
913                 return 0;
914         }
915
916         /* Go ahead and load global variables from users.conf so we can append to profiles */
917         for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
918                 if (!strcasecmp(v->name, "vmexten")) {
919                         if ((var = ast_var_assign("VOICEMAIL_EXTEN", v->value))) {
920                                 ast_mutex_lock(&globals_lock);
921                                 AST_LIST_INSERT_TAIL(&global_variables, var, entries);
922                                 ast_mutex_unlock(&globals_lock);
923                         }
924                 }
925                 if (!strcasecmp(v->name, "localextenlength")) {
926                         if ((var = ast_var_assign("EXTENSION_LENGTH", v->value)))
927                                 ast_mutex_lock(&globals_lock);
928                                 AST_LIST_INSERT_TAIL(&global_variables, var, entries);
929                                 ast_mutex_unlock(&globals_lock);
930                 }
931         }
932
933         if (!(phoneprov_cfg = ast_config_load("phoneprov.conf", config_flags))) {
934                 ast_log(LOG_ERROR, "Unable to load config phoneprov.conf\n");
935                 return -1;
936         }
937
938         cat = NULL;
939         while ((cat = ast_category_browse(phoneprov_cfg, cat))) {
940                 if (!strcasecmp(cat, "general")) {
941                         for (v = ast_variable_browse(phoneprov_cfg, cat); v; v = v->next) {
942                                 if (!strcasecmp(v->name, "serveraddr"))
943                                         ast_copy_string(global_server, v->value, sizeof(global_server));
944                                 else if (!strcasecmp(v->name, "serveriface")) {
945                                         struct in_addr addr;
946                                         lookup_iface(v->value, &addr);
947                                         ast_copy_string(global_server, ast_inet_ntoa(addr), sizeof(global_server));
948                                 } else if (!strcasecmp(v->name, "serverport"))
949                                         ast_copy_string(global_serverport, v->value, sizeof(global_serverport));
950                                 else if (!strcasecmp(v->name, "default_profile"))
951                                         ast_copy_string(global_default_profile, v->value, sizeof(global_default_profile));
952                         }
953                 } else 
954                         build_profile(cat, ast_variable_browse(phoneprov_cfg, cat));
955         }
956
957         ast_config_destroy(phoneprov_cfg);
958
959         cat = NULL;
960         while ((cat = ast_category_browse(cfg, cat))) {
961                 const char *tmp, *mac;
962                 struct user *user;
963                 struct phone_profile *profile;
964                 struct extension *exten;
965
966                 if (!strcasecmp(cat, "general")) {
967                         continue;
968                 }
969                           
970                 if (!strcasecmp(cat, "authentication"))
971                         continue;
972
973                 if (!((tmp = ast_variable_retrieve(cfg, cat, "autoprov")) && ast_true(tmp)))    
974                         continue;
975
976                 if (!(mac = ast_variable_retrieve(cfg, cat, "macaddress"))) {
977                         ast_log(LOG_WARNING, "autoprov set for %s, but no mac address - skipping.\n", cat);
978                         continue;
979                 }
980
981                 tmp = S_OR(ast_variable_retrieve(cfg, cat, "profile"), global_default_profile);
982                 if (ast_strlen_zero(tmp)) {
983                         ast_log(LOG_WARNING, "No profile for user [%s] with mac '%s' - skipping\n", cat, mac);
984                         continue;
985                 }
986
987                 if (!(user = find_user(mac))) {
988                         if (!(profile = find_profile(tmp))) {
989                                 ast_log(LOG_WARNING, "Could not look up profile '%s' - skipping.\n", tmp);
990                                 continue;
991                         }
992
993                         if (!(user = build_user(mac, profile))) {
994                                 ast_log(LOG_WARNING, "Could not create user for '%s' - skipping\n", user->macaddress);
995                                 continue;
996                         }
997
998                         if (!(exten = build_extension(cfg, cat))) {
999                                 ast_log(LOG_WARNING, "Could not create extension for %s - skipping\n", user->macaddress);
1000                                 user = unref_user(user);
1001                                 continue;
1002                         }
1003
1004                         if (add_user_extension(user, exten)) {
1005                                 ast_log(LOG_WARNING, "Could not add extension '%s' to user '%s'\n", exten->name, user->macaddress);
1006                                 user = unref_user(user);
1007                                 exten = delete_extension(exten);
1008                                 continue;
1009                         }
1010
1011                         if (build_user_routes(user)) {
1012                                 ast_log(LOG_WARNING, "Could not create http routes for %s - skipping\n", user->macaddress);
1013                                 user = unref_user(user);
1014                                 continue;
1015                         }
1016
1017                         ao2_link(users, user);
1018                         user = unref_user(user);
1019                 } else {
1020                         if (!(exten = build_extension(cfg, cat))) {
1021                                 ast_log(LOG_WARNING, "Could not create extension for %s - skipping\n", user->macaddress);
1022                                 user = unref_user(user);
1023                                 continue;
1024                         }
1025
1026                         if (add_user_extension(user, exten)) {
1027                                 ast_log(LOG_WARNING, "Could not add extension '%s' to user '%s'\n", exten->name, user->macaddress);
1028                                 user = unref_user(user);
1029                                 exten = delete_extension(exten);
1030                                 continue;
1031                         }
1032
1033                         user = unref_user(user);
1034                 }
1035         }
1036
1037         ast_config_destroy(cfg);
1038
1039         return 0;
1040 }
1041
1042 /*! \brief Delete all http routes, freeing their memory */
1043 static void delete_routes(void)
1044 {
1045         struct ao2_iterator i;
1046         struct http_route *route;
1047         
1048         i = ao2_iterator_init(http_routes, 0);
1049         while ((route = ao2_iterator_next(&i))) {
1050                 ao2_unlink(http_routes, route);
1051                 route = unref_route(route);
1052         }
1053 }
1054
1055 /*! \brief Delete all phone profiles, freeing their memory */
1056 static void delete_profiles(void)
1057 {
1058         struct ao2_iterator i;
1059         struct phone_profile *profile;
1060
1061         i = ao2_iterator_init(profiles, 0);
1062         while ((profile = ao2_iterator_next(&i))) {
1063                 ao2_unlink(profiles, profile);
1064                 profile = unref_profile(profile);
1065         }
1066 }
1067
1068 /*! \brief A dialplan function that can be used to print a string for each phoneprov user */
1069 static int pp_each_user_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1070 {
1071         char *tmp, expand_buf[VAR_BUF_SIZE] = {0,};
1072         struct ao2_iterator i;
1073         struct user *user;
1074         AST_DECLARE_APP_ARGS(args,
1075                 AST_APP_ARG(string);
1076                 AST_APP_ARG(exclude_mac);
1077         );
1078         AST_STANDARD_APP_ARGS(args, data);
1079
1080         /* Fix data by turning %{ into ${ */
1081         while ((tmp = strstr(args.string, "%{")))
1082                 *tmp = '$';
1083
1084         i = ao2_iterator_init(users, 0);
1085         while ((user = ao2_iterator_next(&i))) {
1086                 if (!ast_strlen_zero(args.exclude_mac) && !strcasecmp(user->macaddress, args.exclude_mac)) {
1087                         continue;
1088                 }
1089                 pbx_substitute_variables_varshead(AST_LIST_FIRST(&user->extensions)->headp, args.string, expand_buf, sizeof(expand_buf));
1090                 ast_build_string(&buf, &len, "%s", expand_buf);
1091                 user = unref_user(user);
1092         }
1093
1094         return 0;
1095 }
1096
1097 static struct ast_custom_function pp_each_user_function = {
1098         .name = "PP_EACH_USER",
1099         .synopsis = "Generate a string for each phoneprov user",
1100         .syntax = "PP_EACH_USER(<string>|<exclude_mac>)",
1101         .desc =
1102                 "Pass in a string, with phoneprov variables you want substituted in the format of\n"
1103                 "%{VARNAME}, and you will get the string rendered for each user in phoneprov\n"
1104                 "excluding ones with MAC address <exclude_mac>. Probably not useful outside of\n"
1105                 "res_phoneprov.\n"
1106                 "\nExample: ${PP_EACH_USER(<item><fn>%{DISPLAY_NAME}</fn></item>|${MAC})",
1107         .read = pp_each_user_exec,
1108 };
1109
1110 /*! \brief A dialplan function that can be used to output a template for each extension attached to a user */
1111 static int pp_each_extension_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1112 {
1113         struct user *user;
1114         struct extension *exten;
1115         char path[PATH_MAX];
1116         char *file;
1117         int filelen;
1118         AST_DECLARE_APP_ARGS(args, 
1119                 AST_APP_ARG(mac);
1120                 AST_APP_ARG(template);
1121         );
1122         
1123         AST_STANDARD_APP_ARGS(args, data);
1124
1125         if (ast_strlen_zero(args.mac) || ast_strlen_zero(args.template)) {
1126                 ast_log(LOG_WARNING, "PP_EACH_EXTENSION requries both a macaddress and template filename.\n");
1127                 return 0;
1128         }
1129
1130         if (!(user = find_user(args.mac))) {
1131                 ast_log(LOG_WARNING, "Could not find user with mac = '%s'\n", args.mac);
1132                 return 0;
1133         }
1134
1135         snprintf(path, sizeof(path), "%s/phoneprov/%s", ast_config_AST_DATA_DIR, args.template);
1136         filelen = load_file(path, &file);
1137         if (filelen < 0) {
1138                 ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, filelen);
1139                 if (file) {
1140                         ast_free(file);
1141                 }
1142                 return 0;
1143         }
1144
1145         if (!file) {
1146                 return 0;
1147         }
1148
1149         AST_LIST_TRAVERSE(&user->extensions, exten, entry) {
1150                 char expand_buf[VAR_BUF_SIZE] = {0,};
1151                 pbx_substitute_variables_varshead(exten->headp, file, expand_buf, sizeof(expand_buf));
1152                 ast_build_string(&buf, &len, "%s", expand_buf);
1153         }
1154
1155         ast_free(file);
1156
1157         user = unref_user(user);
1158
1159         return 0;
1160 }
1161
1162 static struct ast_custom_function pp_each_extension_function = {
1163         .name = "PP_EACH_EXTENSION",
1164         .synopsis = "Execute specified template for each extension",
1165         .syntax = "PP_EACH_EXTENSION(<mac>|<template>)",
1166         .desc =
1167                 "Output the specified template for each extension associated with the specified\n"
1168                 "MAC address.",
1169         .read = pp_each_extension_exec,
1170 };
1171
1172 /*! \brief CLI command to list static and dynamic routes */
1173 static char *handle_show_routes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1174 {
1175 #define FORMAT "%-40.40s  %-30.30s\n"
1176         struct ao2_iterator i;
1177         struct http_route *route;
1178         
1179         switch(cmd) {
1180         case CLI_INIT:
1181                 e->command = "phoneprov show routes";
1182                 e->usage =
1183                         "Usage: phoneprov show routes\n"
1184                         "       Lists all registered phoneprov http routes.\n";
1185                 return NULL;
1186         case CLI_GENERATE:
1187                 return NULL;
1188         }
1189
1190         /* This currently iterates over routes twice, but it is the only place I've needed
1191          * to really separate static an dynamic routes, so I've just left it this way. */
1192         ast_cli(a->fd, "Static routes\n\n");
1193         ast_cli(a->fd, FORMAT, "Relative URI", "Physical location");
1194         i = ao2_iterator_init(http_routes, 0);
1195         while ((route = ao2_iterator_next(&i))) {
1196                 if (!route->user)
1197                         ast_cli(a->fd, FORMAT, route->uri, route->file->template);
1198                 route = unref_route(route);
1199         }
1200
1201         ast_cli(a->fd, "\nDynamic routes\n\n");
1202         ast_cli(a->fd, FORMAT, "Relative URI", "Template");
1203
1204         i = ao2_iterator_init(http_routes, 0);
1205         while ((route = ao2_iterator_next(&i))) {
1206                 if (route->user)
1207                         ast_cli(a->fd, FORMAT, route->uri, route->file->template);
1208                 route = unref_route(route);
1209         }
1210
1211         return CLI_SUCCESS;
1212 }
1213
1214 static struct ast_cli_entry pp_cli[] = {
1215         AST_CLI_DEFINE(handle_show_routes, "Show registered phoneprov http routes"),
1216 };
1217
1218 static struct ast_http_uri phoneprovuri = {
1219         .callback = phoneprov_callback,
1220         .description = "Asterisk HTTP Phone Provisioning Tool",
1221         .uri = "phoneprov",
1222         .has_subtree = 1,
1223         .supports_get = 1,
1224         .data = NULL,
1225         .key = __FILE__,
1226 };
1227
1228 static int load_module(void)
1229 {
1230         profiles = ao2_container_alloc(MAX_PROFILE_BUCKETS, profile_hash_fn, profile_cmp_fn);
1231
1232         http_routes = ao2_container_alloc(MAX_ROUTE_BUCKETS, routes_hash_fn, routes_cmp_fn);
1233
1234         users = ao2_container_alloc(MAX_USER_BUCKETS, users_hash_fn, users_cmp_fn);
1235
1236         AST_LIST_HEAD_INIT_NOLOCK(&global_variables);
1237         ast_mutex_init(&globals_lock);
1238         
1239         ast_custom_function_register(&pp_each_user_function);
1240         ast_custom_function_register(&pp_each_extension_function);
1241         ast_cli_register_multiple(pp_cli, ARRAY_LEN(pp_cli));
1242
1243         set_config();
1244         ast_http_uri_link(&phoneprovuri); 
1245
1246         return 0;
1247 }
1248
1249 static int unload_module(void)
1250 {
1251         struct ast_var_t *var;
1252
1253         ast_http_uri_unlink(&phoneprovuri);
1254         ast_custom_function_unregister(&pp_each_user_function);
1255         ast_custom_function_unregister(&pp_each_extension_function);
1256         ast_cli_unregister_multiple(pp_cli, ARRAY_LEN(pp_cli));
1257
1258         delete_routes();
1259         delete_users();
1260         delete_profiles();
1261         ao2_ref(profiles, -1);
1262         ao2_ref(http_routes, -1);
1263         ao2_ref(users, -1);
1264
1265         ast_mutex_lock(&globals_lock);
1266         while ((var = AST_LIST_REMOVE_HEAD(&global_variables, entries))) {
1267                 ast_var_delete(var);
1268         }
1269         ast_mutex_unlock(&globals_lock);
1270
1271         ast_mutex_destroy(&globals_lock);
1272
1273         return 0;
1274 }
1275
1276 static int reload(void) 
1277 {
1278         struct ast_var_t *var;
1279
1280         delete_routes();
1281         delete_users();
1282         delete_profiles();
1283
1284         ast_mutex_lock(&globals_lock);
1285         while ((var = AST_LIST_REMOVE_HEAD(&global_variables, entries))) {
1286                 ast_var_delete(var);
1287         }
1288         ast_mutex_unlock(&globals_lock);
1289
1290         set_config();
1291
1292         return 0;
1293 }
1294
1295 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "HTTP Phone Provisioning",
1296                 .load = load_module,
1297                 .unload = unload_module,
1298                 .reload = reload,
1299         );