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