Added a new module, res_phoneprov, which allows auto-provisioning of phones
[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  * \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
33 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 96773 $")
34
35 #include "asterisk/file.h"
36 #include "asterisk/paths.h"
37 #include "asterisk/pbx.h"
38 #include "asterisk/cli.h"
39 #include "asterisk/module.h"
40 #include "asterisk/http.h"
41 #include "asterisk/utils.h"
42 #include "asterisk/app.h"
43 #include "asterisk/strings.h"
44 #include "asterisk/stringfields.h"
45 #include "asterisk/options.h"
46 #include "asterisk/config.h"
47 #include "asterisk/acl.h"
48 #include "asterisk/astobj2.h"
49 #include "asterisk/version.h"
50
51 #ifdef LOW_MEMORY
52 #define MAX_PROFILE_BUCKETS 1
53 #define MAX_ROUTE_BUCKETS 1
54 #else
55 #define MAX_PROFILE_BUCKETS 17
56 #define MAX_ROUTE_BUCKETS 563
57 #endif /* LOW_MEMORY */
58
59 #define VAR_BUF_SIZE 4096
60
61 /*! \brief for use in lookup_iface */
62 struct my_ifreq {
63         char ifrn_name[IFNAMSIZ];       /* Interface name, e.g. "eth0", "ppp0", etc.  */
64         struct sockaddr_in ifru_addr;
65 };
66
67 /*! \brief for use in lookup_iface */
68 static struct in_addr __ourip = { .s_addr = 0x00000000, };
69
70 /* \note This enum and the pp_variable_list must be in the same order or
71  * bad things happen! */
72 enum pp_variables {
73         PP_MACADDRESS,
74         PP_USERNAME,
75         PP_FULLNAME,
76         PP_SECRET,
77         PP_LABEL,
78         PP_CALLERID,
79         PP_TIMEZONE,
80         PP_VAR_LIST_LENGTH,     /* This entry must always be the last in the list */
81 };
82
83 /*! \brief Lookup table to translate between users.conf property names and
84  * variables for use in phoneprov templates */
85 static const struct pp_variable_lookup {
86         enum pp_variables id;
87         const char * const user_var;
88         const char * const template_var;
89 } pp_variable_list[] = {
90         { PP_MACADDRESS, "macaddress", "MAC" },
91         { PP_USERNAME, "username", "USERNAME" },
92         { PP_FULLNAME, "fullname", "DISPLAY_NAME" },
93         { PP_SECRET, "secret", "SECRET" },
94         { PP_LABEL, "label", "LABEL" },
95         { PP_CALLERID, "cid_number", "CALLERID" },
96         { PP_TIMEZONE, "timezone", "TIMEZONE" },
97 };
98
99 /*! \brief structure to hold file data */
100 struct phoneprov_file {
101         AST_DECLARE_STRING_FIELDS(
102                 AST_STRING_FIELD(format);       /*!< After variable substitution, becomes route->uri */
103                 AST_STRING_FIELD(template); /*!< Template/physical file location */
104                 AST_STRING_FIELD(mime_type);/*!< Mime-type of the file */
105         );
106         AST_LIST_ENTRY(phoneprov_file) entry;
107 };
108
109 /*! \brief structure to hold phone profiles read from phoneprov.conf */
110 struct phone_profile {
111         AST_DECLARE_STRING_FIELDS(
112                 AST_STRING_FIELD(name); /*!< Name of phone profile */
113                 AST_STRING_FIELD(default_mime_type);    /*!< Default mime type if it isn't provided */
114                 AST_STRING_FIELD(staticdir);    /*!< Subdirectory that static files are stored in */
115         );
116         struct varshead *headp; /*!< List of variables set with 'setvar' in phoneprov.conf */
117         AST_LIST_HEAD_NOLOCK(, phoneprov_file) static_files;    /*!< List of static files */
118         AST_LIST_HEAD_NOLOCK(, phoneprov_file) dynamic_files;   /*!< List of dynamic files */
119 };
120
121 /*! \brief structure to hold users read from users.conf */
122 struct user {
123         AST_DECLARE_STRING_FIELDS(
124                 AST_STRING_FIELD(name); /*!< Name of user */
125                 AST_STRING_FIELD(macaddress);   /*!< Mac address of user's phone */
126         );
127         struct phone_profile *profile;  /*!< Profile the phone belongs to */
128         struct varshead *headp; /*!< List of variables to substitute into templates */
129         AST_LIST_ENTRY(user) entry;
130 };
131
132 /*! \brief structure to hold http routes (valid URIs, and the files they link to) */
133 struct http_route {
134         AST_DECLARE_STRING_FIELDS(
135                 AST_STRING_FIELD(uri);  /*!< The URI requested */
136         );
137         struct phoneprov_file *file;    /*!< The file that links to the URI */
138         struct user *user;      /*!< The user that has variables to substitute into the file
139                                                  * NULL in the case of a static route */
140 };
141
142 static struct ao2_container *profiles;
143 static struct ao2_container *http_routes;
144 AST_RWLIST_HEAD_STATIC(users, user);
145
146 /*! \brief Extensions whose mime types we think we know */
147 static struct {
148         char *ext;
149         char *mtype;
150 } mimetypes[] = {
151         { "png", "image/png" },
152         { "xml", "text/xml" },
153         { "jpg", "image/jpeg" },
154         { "js", "application/x-javascript" },
155         { "wav", "audio/x-wav" },
156         { "mp3", "audio/mpeg" },
157 };
158
159 char global_server[80] = "";    /*!< Server to substitute into templates */
160 char global_serverport[6] = "5060";     /*!< Server port to substitute into templates */
161 char global_default_profile[80] = "";   /*!< Default profile to use if one isn't specified */   
162
163 /*! \brief List of global variables currently available: VOICEMAIL_EXTEN, EXTENSION_LENGTH */
164 struct varshead global_variables;
165
166 /*! \brief Return mime type based on extension */
167 static char *ftype2mtype(const char *ftype)
168 {
169         int x;
170
171         if (ast_strlen_zero(ftype))
172                 return NULL;
173
174         for (x = 0;x < ARRAY_LEN(mimetypes);x++) {
175                 if (!strcasecmp(ftype, mimetypes[x].ext))
176                         return mimetypes[x].mtype;
177         }
178         
179         return NULL;
180 }
181
182 /* iface is the interface (e.g. eth0); address is the return value */
183 static int lookup_iface(const char *iface, struct in_addr *address)
184 {
185         int mysock, res = 0;
186         struct my_ifreq ifreq;
187
188         memset(&ifreq, 0, sizeof(ifreq));
189         ast_copy_string(ifreq.ifrn_name, iface, sizeof(ifreq.ifrn_name));
190
191         mysock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
192         if (mysock < 0) {
193                 ast_log(LOG_ERROR, "Failed to create socket: %s\n", strerror(errno));
194                 return -1;
195         }
196
197         res = ioctl(mysock, SIOCGIFADDR, &ifreq);
198
199         close(mysock);
200
201         if (res < 0) {
202                 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
203                 memcpy(address, &__ourip, sizeof(__ourip));
204                 return -1;
205         } else {
206                 memcpy(address, &ifreq.ifru_addr.sin_addr, sizeof(ifreq.ifru_addr.sin_addr));
207                 return 0;
208         }
209 }
210
211 static struct phone_profile *unref_profile(struct phone_profile *prof)
212 {
213         ao2_ref(prof, -1);
214
215         return NULL;
216 }
217
218 /*! \brief Return a phone profile looked up by name */
219 static struct phone_profile *find_profile(const char *name)
220 {
221         struct phone_profile tmp = {
222                 .name = name,
223         };
224
225         return ao2_find(profiles, &tmp, OBJ_POINTER);
226 }
227
228 static int profile_hash_fn(const void *obj, const int flags)
229 {
230         const struct phone_profile *profile = obj;
231         
232         return ast_str_hash(profile->name);
233 }
234
235 static int profile_cmp_fn(void *obj, void *arg, int flags)
236 {
237         const struct phone_profile *profile1 = obj, *profile2 = arg;
238
239         return !strcasecmp(profile1->name, profile2->name) ? CMP_MATCH : 0;
240 }
241
242 static void delete_file(struct phoneprov_file *file)
243 {
244         ast_string_field_free_memory(file);
245         free(file);
246 }
247
248 static void profile_destructor(void *obj)
249 {
250         struct phone_profile *profile = obj;
251         struct phoneprov_file *file;
252         struct ast_var_t *var;
253
254         while ((file = AST_LIST_REMOVE_HEAD(&profile->static_files, entry)))
255                 delete_file(file);
256
257         while ((file = AST_LIST_REMOVE_HEAD(&profile->dynamic_files, entry)))
258                 delete_file(file);
259
260         while ((var = AST_LIST_REMOVE_HEAD(profile->headp, entries)))
261                 ast_var_delete(var);
262
263         free(profile->headp);
264         ast_string_field_free_memory(profile);
265 }
266
267 static struct http_route *unref_route(struct http_route *route)
268 {
269         ao2_ref(route, -1);
270
271         return NULL;
272 }
273
274 static int routes_hash_fn(const void *obj, const int flags)
275 {
276         const struct http_route *route = obj;
277         
278         return ast_str_hash(route->uri);
279 }
280
281 static int routes_cmp_fn(void *obj, void *arg, int flags)
282 {
283         const struct http_route *route1 = obj, *route2 = arg;
284
285         return !strcmp(route1->uri, route2->uri) ? CMP_MATCH : 0;
286 }
287
288 static void route_destructor(void *obj)
289 {
290         struct http_route *route = obj;
291
292         ast_string_field_free_memory(route);
293 }
294
295 /*! \brief Read a TEXT file into a string and return the length */
296 static int load_file(const char *filename, char **ret)
297 {
298         int len = 0;
299         FILE *f;
300         
301         if (!(f = fopen(filename, "r"))) {
302                 *ret = NULL;
303                 return -1;
304         }
305
306         fseek(f, 0, SEEK_END);
307         len = ftell(f);
308         fseek(f, 0, SEEK_SET);
309         if (!(*ret = ast_malloc(len + 1)))
310                 return -2;
311
312         if (len != fread(*ret, sizeof(char), len, f)) {
313                 free(*ret);
314                 *ret = NULL;
315                 return -3;
316         }
317
318         fclose(f);
319
320         (*ret)[len] = '\0';
321
322         return len;
323 }
324
325 /*! \brief Callback that is executed everytime an http request is received by this module */
326 static struct ast_str *phoneprov_callback(struct server_instance *ser, const char *uri, struct ast_variable *vars, int *status, char **title, int *contentlength)
327 {
328         struct http_route *route;
329         struct http_route search_route = {
330                 .uri = uri,
331         };
332         struct ast_str *result = ast_str_create(512);
333         char path[PATH_MAX];
334         char *file = NULL;
335         int len;
336         int fd;
337         char buf[256];
338         struct timeval tv = ast_tvnow();
339         struct ast_tm tm;
340
341         if (!(route = ao2_find(http_routes, &search_route, OBJ_POINTER)))
342                 goto out404;
343
344         snprintf(path, sizeof(path), "%s/phoneprov/%s", ast_config_AST_DATA_DIR, route->file->template);
345
346         if (!route->user) { /* Static file */
347
348                 fd = open(path, O_RDONLY);
349                 if (fd < 0)
350                         goto out500;
351
352                 len = lseek(fd, 0, SEEK_END);
353                 lseek(fd, 0, SEEK_SET);
354                 if (len < 0) {
355                         ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, len);
356                         close(fd);
357                         goto out500;
358                 }
359
360                 ast_strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S %Z", ast_localtime(&tv, &tm, "GMT"));
361             fprintf(ser->f, "HTTP/1.1 200 OK\r\n"
362                         "Server: Asterisk/%s\r\n"
363                         "Date: %s\r\n"
364                         "Connection: close\r\n"
365                         "Cache-Control: no-cache, no-store\r\n"
366                         "Content-Length: %d\r\n"
367                         "Content-Type: %s\r\n\r\n",
368                         ast_get_version(), buf, len, route->file->mime_type);
369                 
370                 while ((len = read(fd, buf, sizeof(buf))) > 0)
371                         fwrite(buf, 1, len, ser->f);
372
373                 close(fd);
374                 route = unref_route(route);
375                 return NULL;
376         } else { /* Dynamic file */
377                 int bufsize;
378                 char *tmp;
379
380                 len = load_file(path, &file);
381                 if (len < 0) {
382                         ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, len);
383                         if (file)
384                                 ast_free(file);
385                         goto out500;
386                 }
387
388                 if (!file)
389                         goto out500;
390
391                 /* XXX This is a hack -- maybe sum length of all variables in route->user->headp and add that? */
392                 bufsize = len + VAR_BUF_SIZE;
393                 
394                 /* malloc() instead of alloca() here, just in case the file is bigger than
395                  * we have enough stack space for. */
396                 if (!(tmp = ast_calloc(1, bufsize))) {
397                         if (file)
398                                 ast_free(file);
399                         goto out500;
400                 }
401
402                 pbx_substitute_variables_varshead(route->user->headp, file, tmp, bufsize);
403         
404                 if (file)
405                         ast_free(file);
406
407                 ast_str_append(&result, 0,
408                         "Content-Type: %s\r\n"
409                         "Content-length: %d\r\n"
410                         "\r\n"
411                         "%s", route->file->mime_type, (int) strlen(tmp), tmp);
412
413                 if (tmp)
414                         ast_free(tmp);
415
416                 route = unref_route(route);
417
418                 return result;
419         }
420
421 out404:
422         *status = 404;
423         *title = strdup("Not Found");
424         *contentlength = 0;
425         return ast_http_error(404, "Not Found", NULL, "Nothing to see here.  Move along.");
426
427 out500:
428         route = unref_route(route);
429         *status = 500;
430         *title = strdup("Internal Server Error");
431         *contentlength = 0;
432         return ast_http_error(500, "Internal Error", NULL, "An internal error has occured.");
433 }
434
435 /*! \brief Build a route structure and add it to the list of available http routes
436         \param pp_file File to link to the route
437         \param user User to link to the route (NULL means static route)
438         \param uri URI of the route
439 */
440 static void build_route(struct phoneprov_file *pp_file, struct user *user, char *uri)
441 {
442         struct http_route *route;
443         
444         if (!(route = ao2_alloc(sizeof(*route), route_destructor)))
445                 return;
446
447         if (ast_string_field_init(route, 32)) {
448                 ast_log(LOG_ERROR, "Couldn't create string fields for %s\n", pp_file->format);
449                 route = unref_route(route);
450                 return;
451         }
452
453         ast_string_field_set(route, uri, S_OR(uri, pp_file->format));
454         route->user = user;
455         route->file = pp_file;
456
457         ao2_link(http_routes, route);
458
459         route = unref_route(route);
460 }
461
462 /*! \brief Build a phone profile and add it to the list of phone profiles
463         \param name the name of the profile
464         \param v ast_variable from parsing phoneprov.conf
465 */
466 static void build_profile(const char *name, struct ast_variable *v)
467 {
468         struct phone_profile *profile;
469         struct ast_var_t *var;
470
471         if (!(profile = ao2_alloc(sizeof(*profile), profile_destructor)))
472                 return;
473
474         if (ast_string_field_init(profile, 32)) {
475                 profile = unref_profile(profile);
476                 return;
477         }
478         
479         if (!(profile->headp = ast_calloc(1, sizeof(*profile->headp)))) {
480                 profile = unref_profile(profile);
481                 return;
482         }
483
484         AST_LIST_HEAD_INIT_NOLOCK(&profile->static_files);
485         AST_LIST_HEAD_INIT_NOLOCK(&profile->dynamic_files);
486
487         ast_string_field_set(profile, name, name);
488         for (; v; v = v->next) {
489                 if (!strcasecmp(v->name, "mime_type")) {
490                         ast_string_field_set(profile, default_mime_type, v->value);
491                 } else if (!strcasecmp(v->name, "setvar")) {
492                         struct ast_var_t *var;
493                         char *value_copy = ast_strdupa(v->value);
494
495                         AST_DECLARE_APP_ARGS(args,
496                                 AST_APP_ARG(varname);
497                                 AST_APP_ARG(varval);
498                         );
499                         
500                         AST_NONSTANDARD_APP_ARGS(args, value_copy, '=');
501                         do {
502                                 if (ast_strlen_zero(args.varname) || ast_strlen_zero(args.varval))
503                                         break;
504                                 args.varname = ast_strip(args.varname);
505                                 args.varval = ast_strip(args.varval);
506                                 if (ast_strlen_zero(args.varname) || ast_strlen_zero(args.varval))
507                                         break;
508                                 if ((var = ast_var_assign(args.varname, args.varval)))
509                                         AST_LIST_INSERT_TAIL(profile->headp, var, entries);
510                         } while (0);
511                 } else if (!strcasecmp(v->name, "staticdir")) {
512                         ast_string_field_set(profile, staticdir, v->value);
513                 } else {
514                         struct phoneprov_file *pp_file;
515                         char *file_extension;
516                         char *value_copy = ast_strdupa(v->value); 
517
518                         AST_DECLARE_APP_ARGS(args,
519                                 AST_APP_ARG(filename);
520                                 AST_APP_ARG(mimetype);
521                         );
522
523                         if (!(pp_file = ast_calloc(1, sizeof(*pp_file)))) {
524                                 profile = unref_profile(profile);
525                                 return;
526                         }
527                         if (ast_string_field_init(pp_file, 32)) {
528                                 ast_free(pp_file);
529                                 profile = unref_profile(profile);
530                                 return;
531                         }
532
533                         if ((file_extension = strrchr(pp_file->format, '.')))
534                                 file_extension++;
535
536                         AST_STANDARD_APP_ARGS(args, value_copy);
537
538                         /* Mime type order of preference
539                          * 1) Specific mime-type defined for file in profile
540                          * 2) Mime determined by extension
541                          * 3) Default mime type specified in profile
542                          * 4) text/plain
543                          */
544                         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"))));
545
546                         if (!strcasecmp(v->name, "static_file")) {
547                                 ast_string_field_set(pp_file, format, args.filename);
548                                 ast_string_field_build(pp_file, template, "%s%s", profile->staticdir, args.filename);
549                                 AST_LIST_INSERT_TAIL(&profile->static_files, pp_file, entry);
550                                 /* Add a route for the static files, as their filenames won't change per-user */
551                                 build_route(pp_file, NULL, NULL);
552                         } else {
553                                 ast_string_field_set(pp_file, format, v->name);
554                                 ast_string_field_set(pp_file, template, args.filename);
555                                 AST_LIST_INSERT_TAIL(&profile->dynamic_files, pp_file, entry);
556                         }
557                 }
558         }
559
560         /* Append the global variables to the variables list for this profile.
561          * This is for convenience later, when we need to provide a single
562          * variable list for use in substitution. */
563         AST_LIST_TRAVERSE(&global_variables, var, entries) {
564                 struct ast_var_t *new_var;
565                 if ((new_var = ast_var_assign(var->name, var->value)))
566                         AST_LIST_INSERT_TAIL(profile->headp, new_var, entries);
567         }
568
569         ao2_link(profiles, profile);
570
571         profile = unref_profile(profile);
572 }
573
574 /*! \brief Free all memory associated with a user */
575 static void delete_user(struct user *user)
576 {
577         struct ast_var_t *var;
578
579         while ((var = AST_LIST_REMOVE_HEAD(user->headp, entries)))
580                 ast_var_delete(var);
581
582         ast_free(user->headp);
583         ast_string_field_free_memory(user);
584         user->profile = unref_profile(user->profile);
585         free(user);
586 }
587
588 /*! \brief Destroy entire user list */
589 static void delete_users(void)
590 {
591         struct user *user;
592
593         AST_RWLIST_WRLOCK(&users);
594         while ((user = AST_LIST_REMOVE_HEAD(&users, entry)))
595                 delete_user(user);
596         AST_RWLIST_UNLOCK(&users);
597 }
598
599 /*! \brief Set all timezone-related variables based on a zone (i.e. America/New_York)
600         \param headp pointer to list of user variables
601         \param zone A time zone. NULL sets variables based on timezone of the machine
602 */
603 static void set_timezone_variables(struct varshead *headp, const char *zone)
604 {
605         time_t utc_time;
606         int dstenable;
607         time_t dststart;
608         time_t dstend;
609         struct ast_tm tm_info;
610         int tzoffset;
611         char buffer[21];
612         struct ast_var_t *var;
613         struct timeval tv;
614
615         time(&utc_time);
616         ast_get_dst_info(&utc_time, &dstenable, &dststart, &dstend, &tzoffset, zone);
617         snprintf(buffer, sizeof(buffer), "%d", tzoffset);
618         var = ast_var_assign("TZOFFSET", buffer);
619         if (var)
620                 AST_LIST_INSERT_TAIL(headp, var, entries); 
621
622         if (!dstenable)
623                 return;
624
625         if ((var = ast_var_assign("DST_ENABLE", "1")))
626                 AST_LIST_INSERT_TAIL(headp, var, entries);
627
628         tv.tv_sec = dststart; 
629         ast_localtime(&tv, &tm_info, zone);
630
631         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mon+1);
632         if ((var = ast_var_assign("DST_START_MONTH", buffer)))
633                 AST_LIST_INSERT_TAIL(headp, var, entries);
634
635         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mday);
636         if ((var = ast_var_assign("DST_START_MDAY", buffer)))
637                 AST_LIST_INSERT_TAIL(headp, var, entries);
638
639         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_hour);
640         if ((var = ast_var_assign("DST_START_HOUR", buffer)))
641                 AST_LIST_INSERT_TAIL(headp, var, entries);
642
643         tv.tv_sec = dstend;
644         ast_localtime(&tv, &tm_info, zone);
645
646         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mon + 1);
647         if ((var = ast_var_assign("DST_END_MONTH", buffer)))
648                 AST_LIST_INSERT_TAIL(headp, var, entries);
649
650         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mday);
651         if ((var = ast_var_assign("DST_END_MDAY", buffer)))
652                 AST_LIST_INSERT_TAIL(headp, var, entries);
653
654         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_hour);
655         if ((var = ast_var_assign("DST_END_HOUR", buffer)))
656                 AST_LIST_INSERT_TAIL(headp, var, entries);
657 }
658
659 /*! \brief Build and return a user structure based on gathered config data */
660 static struct user *build_user(struct ast_config *cfg, const char *name, const char *mac, struct phone_profile *profile)
661 {
662         struct user *user;
663         struct ast_var_t *var;
664         const char *tmp;
665         int i;
666         
667         if (!(user = ast_calloc(1, sizeof(*user)))) {
668                 profile = unref_profile(profile);
669                 return NULL;
670         }
671         
672         if (!(user->headp = ast_calloc(1, sizeof(*user->headp)))) {
673                 profile = unref_profile(profile);
674                 ast_free(user);
675                 return NULL;
676         }
677
678         if (ast_string_field_init(user, 32)) {
679                 profile = unref_profile(profile);
680                 delete_user(user);
681                 return NULL;
682         }
683
684         ast_string_field_set(user, name, name);
685         ast_string_field_set(user, macaddress, mac);
686         user->profile = profile; /* already ref counted by find_profile */
687
688         for (i = 0; i < PP_VAR_LIST_LENGTH; i++) {
689                 tmp = ast_variable_retrieve(cfg, name, pp_variable_list[i].user_var);
690
691                 if (i == PP_TIMEZONE) {
692                         /* perfectly ok if tmp is NULL, will set variables based on server's time zone */
693                         set_timezone_variables(user->headp, tmp);
694                 }
695
696                 if (tmp && (var = ast_var_assign(pp_variable_list[i].template_var, tmp)))
697                         AST_LIST_INSERT_TAIL(user->headp, var, entries);
698         }
699
700         if (!ast_strlen_zero(global_server)) {
701                 if ((var = ast_var_assign("SERVER", global_server)))
702                         AST_LIST_INSERT_TAIL(user->headp, var, entries);
703                 if (!ast_strlen_zero(global_serverport)) {
704                         if ((var = ast_var_assign("SERVER_PORT", global_serverport)))
705                                 AST_LIST_INSERT_TAIL(user->headp, var, entries);
706                 }
707         }
708
709         /* Append profile variables here, and substitute variables on profile
710          * setvars, so that we can use user specific variables in them */
711         AST_LIST_TRAVERSE(user->profile->headp, var, entries) {
712                 char expand_buf[VAR_BUF_SIZE] = {0,};
713                 struct ast_var_t *var2;
714
715                 pbx_substitute_variables_varshead(user->headp, var->value, expand_buf, sizeof(expand_buf));
716                 if ((var2 = ast_var_assign(var->name, expand_buf)))
717                         AST_LIST_INSERT_TAIL(user->headp, var2, entries);
718         }
719
720         return user;
721 }
722
723 /*! \brief Add an http route for dynamic files attached to the profile of the user */
724 static int build_user_routes(struct user *user)
725 {
726         struct phoneprov_file *pp_file;
727
728         AST_LIST_TRAVERSE(&user->profile->dynamic_files, pp_file, entry) {
729                 char expand_buf[VAR_BUF_SIZE] = { 0, };
730
731                 pbx_substitute_variables_varshead(user->headp, pp_file->format, expand_buf, sizeof(expand_buf));
732                 build_route(pp_file, user, expand_buf);
733         }
734
735         return 0;
736 }
737
738 /* \brief Parse config files and create appropriate structures */
739 static int set_config(void)
740 {
741         struct ast_config *phoneprov_cfg, *users_cfg;
742         char *cat;
743         struct ast_variable *v;
744         struct ast_flags config_flags = { 0 };
745
746         if (!(phoneprov_cfg = ast_config_load("phoneprov.conf", config_flags))) {
747                 ast_log(LOG_ERROR, "Unable to load config phoneprov.conf\n");
748                 return -1;
749         }
750
751         cat = NULL;
752         while ((cat = ast_category_browse(phoneprov_cfg, cat))) {
753                 if (!strcasecmp(cat, "general")) {
754                         for (v = ast_variable_browse(phoneprov_cfg, cat); v; v = v->next) {
755                                 if (!strcasecmp(v->name, "serveraddr"))
756                                         ast_copy_string(global_server, v->value, sizeof(global_server));
757                                 else if (!strcasecmp(v->name, "serveriface")) {
758                                         struct in_addr addr;
759                                         lookup_iface(v->value, &addr);
760                                         ast_copy_string(global_server, ast_inet_ntoa(addr), sizeof(global_server));
761                                 } else if (!strcasecmp(v->name, "serverport"))
762                                         ast_copy_string(global_serverport, v->value, sizeof(global_serverport));
763                                 else if (!strcasecmp(v->name, "default_profile"))
764                                         ast_copy_string(global_default_profile, v->value, sizeof(global_default_profile));
765                         }
766                         if (ast_strlen_zero(global_server))
767                                 ast_log(LOG_WARNING, "No serveraddr/serveriface set in phoneprov.conf.  Breakage likely.\n");
768                 } else 
769                         build_profile(cat, ast_variable_browse(phoneprov_cfg, cat));
770         }
771
772         ast_config_destroy(phoneprov_cfg);
773
774         if (!(users_cfg = ast_config_load("users.conf", config_flags))) {
775                 ast_log(LOG_WARNING, "Unable to load users.cfg\n");
776                 return 0;
777         }
778
779         cat = NULL;
780         while ((cat = ast_category_browse(users_cfg, cat))) {
781                 const char *tmp, *mac;
782                 struct user *user;
783                 struct phone_profile *profile;
784                 struct ast_var_t *var;
785
786                 if (!strcasecmp(cat, "general")) {
787                         for (v = ast_variable_browse(users_cfg, cat); v; v = v->next) {
788                                 if (!strcasecmp(v->name, "vmexten")) {
789                                         if ((var = ast_var_assign("VOICEMAIL_EXTEN", v->value)))
790                                                 AST_LIST_INSERT_TAIL(&global_variables, var, entries);
791                                 }
792                                 if (!strcasecmp(v->name, "localextenlength")) {
793                                         if ((var = ast_var_assign("EXTENSION_LENGTH", v->value)))
794                                                 AST_LIST_INSERT_TAIL(&global_variables, var, entries);
795                                 }
796                         }
797                 }
798                           
799                 if (!strcasecmp(cat, "authentication"))
800                         continue;
801
802                 if (!((tmp = ast_variable_retrieve(users_cfg, cat, "autoprov")) && ast_true(tmp)))      
803                         continue;
804
805                 if (!(mac = ast_variable_retrieve(users_cfg, cat, "macaddress"))) {
806                         ast_log(LOG_WARNING, "autoprov set for %s, but no mac address - skipping.\n", cat);
807                         continue;
808                 }
809
810                 tmp = S_OR(ast_variable_retrieve(users_cfg, cat, "profile"), global_default_profile);
811                 if (ast_strlen_zero(tmp)) {
812                         ast_log(LOG_WARNING, "No profile for user [%s] with mac '%s' - skipping\n", cat, mac);
813                         continue;
814                 }
815
816                 if (!(profile = find_profile(tmp))) {
817                         ast_log(LOG_WARNING, "Could not look up profile '%s' - skipping.\n", tmp);
818                         continue;
819                 }
820
821                 if (!(user = build_user(users_cfg, cat, mac, profile))) {
822                         ast_log(LOG_WARNING, "Could not create user %s - skipping.\n", cat);
823                         continue;
824                 }
825
826                 if (build_user_routes(user)) {
827                         ast_log(LOG_WARNING, "Could not create http routes for %s - skipping\n", user->name);
828                         delete_user(user);
829                         continue;
830                 }
831
832                 AST_RWLIST_WRLOCK(&users);
833                 AST_RWLIST_INSERT_TAIL(&users, user, entry);
834                 AST_RWLIST_UNLOCK(&users);
835         }
836
837         ast_config_destroy(users_cfg);
838
839         return 0;
840 }
841
842 /*! \brief Delete all http routes, freeing their memory */
843 static void delete_routes(void)
844 {
845         struct ao2_iterator i;
846         struct http_route *route;
847         
848         i = ao2_iterator_init(http_routes, 0);
849         while ((route = ao2_iterator_next(&i))) {
850                 ao2_unlink(http_routes, route);
851                 route = unref_route(route);
852         }
853 }
854
855 /*! \brief Delete all phone profiles, freeing their memory */
856 static void delete_profiles(void)
857 {
858         struct ao2_iterator i;
859         struct phone_profile *profile;
860
861         i = ao2_iterator_init(profiles, 0);
862         while ((profile = ao2_iterator_next(&i))) {
863                 ao2_unlink(profiles, profile);
864                 profile = unref_profile(profile);
865         }
866 }
867
868 /*! \brief A dialplan function that can be used to print a string for each phoneprov user */
869 static int pp_each_user_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
870 {
871         char *tmp, expand_buf[VAR_BUF_SIZE] = {0,};
872         struct user *user;
873         AST_DECLARE_APP_ARGS(args,
874                 AST_APP_ARG(string);
875                 AST_APP_ARG(exclude_mac);
876         );
877         AST_STANDARD_APP_ARGS(args, data);
878
879         /* Fix data by turning %{ into ${ */
880         while ((tmp = strstr(args.string, "%{")))
881                 *tmp = '$';
882
883         AST_RWLIST_RDLOCK(&users);
884         AST_RWLIST_TRAVERSE(&users, user, entry) {
885                 if (!ast_strlen_zero(args.exclude_mac) && !strcasecmp(user->macaddress, args.exclude_mac))
886                         continue;
887                 pbx_substitute_variables_varshead(user->headp, args.string, expand_buf, sizeof(expand_buf));
888                 ast_build_string(&buf, &len, expand_buf);
889         }
890         AST_RWLIST_UNLOCK(&users);
891
892         return 0;
893 }
894
895 static struct ast_custom_function pp_each_user_function = {
896         .name = "PP_EACH_USER",
897         .synopsis = "Generate a string for each phoneprov user",
898         .syntax = "PP_EACH_USER(<string>|<exclude_mac>)",
899         .desc =
900                 "Pass in a string, with phoneprov variables you want substituted in the format of\n"
901                 "%{VARNAME}, and you will get the string rendered for each user in phoneprov\n"
902                 "excluding ones with MAC address <exclude_mac>. Probably not useful outside of\n"
903                 "res_phoneprov.\n"
904                 "\nExample: ${PP_EACH_USER(<item><fn>%{DISPLAY_NAME}</fn></item>|${MAC})",
905         .read = pp_each_user_exec,
906 };
907
908 /*! \brief CLI command to list static and dynamic routes */
909 static char *handle_show_routes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
910 {
911 #define FORMAT "%-40.40s  %-30.30s\n"
912         struct ao2_iterator i;
913         struct http_route *route;
914         
915         switch(cmd) {
916         case CLI_INIT:
917                 e->command = "phoneprov show routes";
918                 e->usage =
919                         "Usage: phoneprov show routes\n"
920                         "       Lists all registered phoneprov http routes.\n";
921                 return NULL;
922         case CLI_GENERATE:
923                 return NULL;
924         }
925
926         /* This currently iterates over routes twice, but it is the only place I've needed
927          * to really separate static an dynamic routes, so I've just left it this way. */
928         ast_cli(a->fd, "Static routes\n\n");
929         ast_cli(a->fd, FORMAT, "Relative URI", "Physical location");
930         i = ao2_iterator_init(http_routes, 0);
931         while ((route = ao2_iterator_next(&i))) {
932                 if (!route->user)
933                         ast_cli(a->fd, FORMAT, route->uri, route->file->template);
934                 route = unref_route(route);
935         }
936
937         ast_cli(a->fd, "\nDynamic routes\n\n");
938         ast_cli(a->fd, FORMAT, "Relative URI", "Template");
939
940         i = ao2_iterator_init(http_routes, 0);
941         while ((route = ao2_iterator_next(&i))) {
942                 if (route->user)
943                         ast_cli(a->fd, FORMAT, route->uri, route->file->template);
944                 route = unref_route(route);
945         }
946
947         return CLI_SUCCESS;
948 }
949
950 static struct ast_cli_entry pp_cli[] = {
951         AST_CLI_DEFINE(handle_show_routes, "Show registered phoneprov http routes"),
952 };
953
954 static struct ast_http_uri phoneprovuri = {
955         .callback = phoneprov_callback,
956         .description = "Asterisk HTTP Phone Provisioning Tool",
957         .uri = "phoneprov",
958         .has_subtree = 1,
959 };
960
961 static int load_module(void)
962 {
963         profiles = ao2_container_alloc(MAX_PROFILE_BUCKETS, profile_hash_fn, profile_cmp_fn);
964
965         http_routes = ao2_container_alloc(MAX_ROUTE_BUCKETS, routes_hash_fn, routes_cmp_fn);
966
967         AST_LIST_HEAD_INIT_NOLOCK(&global_variables);
968         
969         ast_custom_function_register(&pp_each_user_function);
970         ast_cli_register_multiple(pp_cli, ARRAY_LEN(pp_cli));
971
972         set_config();
973         ast_http_uri_link(&phoneprovuri); 
974
975         return 0;
976 }
977
978 static int unload_module(void)
979 {
980         struct ast_var_t *var;
981
982         ast_http_uri_unlink(&phoneprovuri);
983         ast_custom_function_unregister(&pp_each_user_function);
984         ast_cli_unregister_multiple(pp_cli, ARRAY_LEN(pp_cli));
985
986         delete_routes();
987         delete_users();
988         delete_profiles();
989         ao2_ref(profiles, -1);
990         ao2_ref(http_routes, -1);
991
992         while ((var = AST_LIST_REMOVE_HEAD(&global_variables, entries)))
993                 ast_var_delete(var);
994
995         return 0;
996 }
997
998 static int reload(void) 
999 {
1000         delete_routes();
1001         delete_users();
1002         delete_profiles();
1003         set_config();
1004
1005         return 0;
1006 }
1007
1008 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "HTTP Phone Provisioning",
1009                 .load = load_module,
1010                 .unload = unload_module,
1011                 .reload = reload,
1012         );