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