res_pjsip res_pjsip_mwi: Misc fixes and cleanups.
[asterisk/asterisk.git] / res / res_phoneprov.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, Digium, Inc.
5  * Copyright (C) 2014, Fairview 5 Engineering, LLC
6  *
7  * Mark Spencer <markster@digium.com>
8  * Matthew Brooks <mbrooks@digium.com>
9  * Terry Wilson <twilson@digium.com>
10  * George Joseph <george.joseph@fairview5.com>
11  *
12  * See http://www.asterisk.org for more information about
13  * the Asterisk project. Please do not directly contact
14  * any of the maintainers of this project for assistance;
15  * the project provides a web site, mailing lists and IRC
16  * channels for your use.
17  *
18  * This program is free software, distributed under the terms of
19  * the GNU General Public License Version 2. See the LICENSE file
20  * at the top of the source tree.
21  */
22
23 /*! \file
24  *
25  * \brief Phone provisioning application for the asterisk internal http server
26  *
27  * \author Matthew Brooks <mbrooks@digium.com>
28  * \author Terry Wilson <twilson@digium.com>
29  * \author George Joseph <george.joseph@fairview5.com>
30   */
31
32 /*! \li \ref res_phoneprov.c uses the configuration file \ref phoneprov.conf and \ref users.conf and \ref sip.conf
33  * \addtogroup configuration_file Configuration Files
34  */
35
36 /*! 
37  * \page phoneprov.conf phoneprov.conf
38  * \verbinclude phoneprov.conf.sample
39  */
40
41 /*** MODULEINFO
42         <support_level>extended</support_level>
43  ***/
44
45 #define AST_API_MODULE
46
47 #include "asterisk.h"
48
49 #include <sys/ioctl.h>
50 #include <sys/socket.h>
51 #include <net/if.h>
52 #ifdef SOLARIS
53 #include <sys/sockio.h>
54 #endif
55 ASTERISK_REGISTER_FILE()
56
57 #include "asterisk/channel.h"
58 #include "asterisk/file.h"
59 #include "asterisk/paths.h"
60 #include "asterisk/pbx.h"
61 #include "asterisk/cli.h"
62 #include "asterisk/module.h"
63 #include "asterisk/http.h"
64 #include "asterisk/utils.h"
65 #include "asterisk/app.h"
66 #include "asterisk/strings.h"
67 #include "asterisk/stringfields.h"
68 #include "asterisk/options.h"
69 #include "asterisk/config.h"
70 #include "asterisk/acl.h"
71 #include "asterisk/astobj2.h"
72 #include "asterisk/ast_version.h"
73 #include "asterisk/phoneprov.h"
74
75 #ifdef LOW_MEMORY
76 #define MAX_PROVIDER_BUCKETS 1
77 #define MAX_PROFILE_BUCKETS 1
78 #define MAX_ROUTE_BUCKETS 1
79 #define MAX_USER_BUCKETS 1
80 #else
81 #define MAX_PROVIDER_BUCKETS 17
82 #define MAX_PROFILE_BUCKETS 17
83 #define MAX_ROUTE_BUCKETS 563
84 #define MAX_USER_BUCKETS 563
85 #endif /* LOW_MEMORY */
86
87 #define VAR_BUF_SIZE 4096
88
89 /*** DOCUMENTATION
90         <function name="PP_EACH_EXTENSION" language="en_US">
91                 <synopsis>
92                         Execute specified template for each extension.
93                 </synopsis>
94                 <syntax>
95                         <parameter name="mac" required="true" />
96                         <parameter name="template_file" required="true" />
97                 </syntax>
98                 <description>
99                         <para>Output the specified template for each extension associated with the specified MAC address.</para>
100                 </description>
101         </function>
102         <function name="PP_EACH_USER" language="en_US">
103                 <synopsis>
104                         Generate a string for each phoneprov user.
105                 </synopsis>
106                 <syntax>
107                         <parameter name="string" required="true" />
108                         <parameter name="exclude_mac" required="true" />
109                 </syntax>
110                 <description>
111                         <para>Pass in a string, with phoneprov variables you want substituted in the format of
112                         %{VARNAME}, and you will get the string rendered for each user in phoneprov
113                         excluding ones with MAC address <replaceable>exclude_mac</replaceable>. Probably not
114                         useful outside of res_phoneprov.</para>
115                         <para>Example: ${PP_EACH_USER(&lt;item&gt;&lt;fn&gt;%{DISPLAY_NAME}&lt;/fn&gt;&lt;/item&gt;|${MAC})</para>
116                 </description>
117         </function>
118  ***/
119
120 /*!
121  * \brief Creates a hash function for a structure string field.
122  * \param fname The name to use for the function
123  * \param stype The structure type
124  * \param field The field in the structure to hash
125  *
126  * SIMPLE_HASH_FN(mystruct, myfield) will produce a function
127  * named mystruct_hash_fn which hashes mystruct->myfield.
128  */
129 #define SIMPLE_HASH_FN(fname, stype, field) \
130 static int fname(const void *obj, const int flags) \
131 { \
132         const struct stype *provider = obj; \
133         const char *key; \
134         switch (flags & OBJ_SEARCH_MASK) { \
135         case OBJ_SEARCH_KEY: \
136                 key = obj; \
137                 break; \
138         case OBJ_SEARCH_OBJECT: \
139                 provider = obj; \
140                 key = provider->field; \
141                 break; \
142         default: \
143                 ast_assert(0); \
144                 return 0; \
145         } \
146         return ast_str_hash(key); \
147 }
148
149 /*!
150  * \brief Creates a compare function for a structure string field.
151  * \param fname The name to use for the function
152  * \param stype The structure type
153  * \param field The field in the structure to compare
154  *
155  * SIMPLE_CMP_FN(mystruct, myfield) will produce a function
156  * named mystruct_cmp_fn which compares mystruct->myfield.
157  */
158 #define SIMPLE_CMP_FN(fname, stype, field) \
159 static int fname(void *obj, void *arg, int flags) \
160 { \
161         const struct stype *object_left = obj, *object_right = arg; \
162         const char *right_key = arg; \
163         int cmp; \
164         switch (flags & OBJ_SEARCH_MASK) { \
165         case OBJ_SEARCH_OBJECT: \
166                 right_key = object_right->field; \
167         case OBJ_SEARCH_KEY: \
168                 cmp = strcmp(object_left->field, right_key); \
169                 break; \
170         case OBJ_SEARCH_PARTIAL_KEY: \
171                 cmp = strncmp(object_left->field, right_key, strlen(right_key)); \
172                 break; \
173         default: \
174                 cmp = 0; \
175                 break; \
176         } \
177         if (cmp) { \
178                 return 0; \
179         } \
180         return CMP_MATCH; \
181 }
182
183 static const char *variable_lookup[] = {
184         [AST_PHONEPROV_STD_MAC] = "MAC",
185         [AST_PHONEPROV_STD_PROFILE] = "PROFILE",
186         [AST_PHONEPROV_STD_USERNAME] = "USERNAME",
187         [AST_PHONEPROV_STD_DISPLAY_NAME] = "DISPLAY_NAME",
188         [AST_PHONEPROV_STD_SECRET] = "SECRET",
189         [AST_PHONEPROV_STD_LABEL] = "LABEL",
190         [AST_PHONEPROV_STD_CALLERID] = "CALLERID",
191         [AST_PHONEPROV_STD_TIMEZONE] = "TIMEZONE",
192         [AST_PHONEPROV_STD_LINENUMBER] = "LINE",
193         [AST_PHONEPROV_STD_LINEKEYS] = "LINEKEYS",
194         [AST_PHONEPROV_STD_SERVER] = "SERVER",
195         [AST_PHONEPROV_STD_SERVER_PORT] = "SERVER_PORT",
196         [AST_PHONEPROV_STD_SERVER_IFACE] = "SERVER_IFACE",
197         [AST_PHONEPROV_STD_VOICEMAIL_EXTEN] = "VOICEMAIL_EXTEN",
198         [AST_PHONEPROV_STD_EXTENSION_LENGTH] = "EXTENSION_LENGTH",
199         [AST_PHONEPROV_STD_TZOFFSET] = "TZOFFSET",
200         [AST_PHONEPROV_STD_DST_ENABLE] = "DST_ENABLE",
201         [AST_PHONEPROV_STD_DST_START_MONTH] = "DST_START_MONTH",
202         [AST_PHONEPROV_STD_DST_START_MDAY] = "DST_START_MDAY",
203         [AST_PHONEPROV_STD_DST_START_HOUR] = "DST_START_HOUR",
204         [AST_PHONEPROV_STD_DST_END_MONTH] = "DST_END_MONTH",
205         [AST_PHONEPROV_STD_DST_END_MDAY] = "DST_END_MDAY",
206         [AST_PHONEPROV_STD_DST_END_HOUR] = "DST_END_HOUR",
207 };
208
209 /* Translate the standard variables to their users.conf equivalents. */
210 static const char *pp_user_lookup[] = {
211         [AST_PHONEPROV_STD_MAC] = "macaddress",
212         [AST_PHONEPROV_STD_PROFILE] = "profile",
213         [AST_PHONEPROV_STD_USERNAME] = "username",
214         [AST_PHONEPROV_STD_DISPLAY_NAME] = "fullname",
215         [AST_PHONEPROV_STD_SECRET] = "secret",
216         [AST_PHONEPROV_STD_LABEL] = "label",
217         [AST_PHONEPROV_STD_CALLERID] = "cid_number",
218         [AST_PHONEPROV_STD_TIMEZONE] = "timezone",
219         [AST_PHONEPROV_STD_LINENUMBER] = "linenumber",
220         [AST_PHONEPROV_STD_LINEKEYS] = "linekeys",
221         [AST_PHONEPROV_STD_SERVER] = NULL,
222         [AST_PHONEPROV_STD_SERVER_PORT] = NULL,
223         [AST_PHONEPROV_STD_SERVER_IFACE] = NULL,
224         [AST_PHONEPROV_STD_VOICEMAIL_EXTEN] = "vmexten",
225         [AST_PHONEPROV_STD_EXTENSION_LENGTH] = "localextenlength",
226         [AST_PHONEPROV_STD_TZOFFSET] = NULL,
227         [AST_PHONEPROV_STD_DST_ENABLE] = NULL,
228         [AST_PHONEPROV_STD_DST_START_MONTH] = NULL,
229         [AST_PHONEPROV_STD_DST_START_MDAY] = NULL,
230         [AST_PHONEPROV_STD_DST_START_HOUR] = NULL,
231         [AST_PHONEPROV_STD_DST_END_MONTH] = NULL,
232         [AST_PHONEPROV_STD_DST_END_MDAY] = NULL,
233         [AST_PHONEPROV_STD_DST_END_HOUR] = NULL,
234 };
235
236 /* Translate the standard variables to their phoneprov.conf [general] equivalents. */
237 static const char *pp_general_lookup[] = {
238         [AST_PHONEPROV_STD_MAC] = NULL,
239         [AST_PHONEPROV_STD_PROFILE] = "default_profile",
240         [AST_PHONEPROV_STD_USERNAME] = NULL,
241         [AST_PHONEPROV_STD_DISPLAY_NAME] = NULL,
242         [AST_PHONEPROV_STD_SECRET] = NULL,
243         [AST_PHONEPROV_STD_LABEL] = NULL,
244         [AST_PHONEPROV_STD_CALLERID] = NULL,
245         [AST_PHONEPROV_STD_TIMEZONE] = NULL,
246         [AST_PHONEPROV_STD_LINENUMBER] = NULL,
247         [AST_PHONEPROV_STD_LINEKEYS] = NULL,
248         [AST_PHONEPROV_STD_SERVER] = "serveraddr",
249         [AST_PHONEPROV_STD_SERVER_PORT] = "serverport",
250         [AST_PHONEPROV_STD_SERVER_IFACE] = "serveriface",
251         [AST_PHONEPROV_STD_VOICEMAIL_EXTEN] = NULL,
252         [AST_PHONEPROV_STD_EXTENSION_LENGTH] = NULL,
253         [AST_PHONEPROV_STD_TZOFFSET] = NULL,
254         [AST_PHONEPROV_STD_DST_ENABLE] = NULL,
255         [AST_PHONEPROV_STD_DST_START_MONTH] = NULL,
256         [AST_PHONEPROV_STD_DST_START_MDAY] = NULL,
257         [AST_PHONEPROV_STD_DST_START_HOUR] = NULL,
258         [AST_PHONEPROV_STD_DST_END_MONTH] = NULL,
259         [AST_PHONEPROV_STD_DST_END_MDAY] = NULL,
260         [AST_PHONEPROV_STD_DST_END_HOUR] = NULL,
261 };
262
263 /*! \brief for use in lookup_iface */
264 static struct in_addr __ourip = { .s_addr = 0x00000000, };
265
266 /*! \brief structure to hold config providers */
267 struct phoneprov_provider {
268         AST_DECLARE_STRING_FIELDS(
269                 AST_STRING_FIELD(provider_name);
270         );
271         ast_phoneprov_load_users_cb load_users;
272 };
273 struct ao2_container *providers;
274 SIMPLE_HASH_FN(phoneprov_provider_hash_fn, phoneprov_provider, provider_name)
275 SIMPLE_CMP_FN(phoneprov_provider_cmp_fn, phoneprov_provider, provider_name)
276
277 /*! \brief structure to hold file data */
278 struct phoneprov_file {
279         AST_DECLARE_STRING_FIELDS(
280                 AST_STRING_FIELD(format);       /*!< After variable substitution, becomes route->uri */
281                 AST_STRING_FIELD(template); /*!< Template/physical file location */
282                 AST_STRING_FIELD(mime_type);/*!< Mime-type of the file */
283         );
284         AST_LIST_ENTRY(phoneprov_file) entry;
285 };
286
287 /*! \brief structure to hold extensions */
288 struct extension {
289         AST_DECLARE_STRING_FIELDS(
290                 AST_STRING_FIELD(name);
291         );
292         int index;
293         struct varshead *headp; /*!< List of variables to substitute into templates */
294         AST_LIST_ENTRY(extension) entry;
295 };
296
297 /*! \brief structure to hold phone profiles read from phoneprov.conf */
298 struct phone_profile {
299         AST_DECLARE_STRING_FIELDS(
300                 AST_STRING_FIELD(name); /*!< Name of phone profile */
301                 AST_STRING_FIELD(default_mime_type);    /*!< Default mime type if it isn't provided */
302                 AST_STRING_FIELD(staticdir);    /*!< Subdirectory that static files are stored in */
303         );
304         struct varshead *headp; /*!< List of variables set with 'setvar' in phoneprov.conf */
305         AST_LIST_HEAD_NOLOCK(, phoneprov_file) static_files;    /*!< List of static files */
306         AST_LIST_HEAD_NOLOCK(, phoneprov_file) dynamic_files;   /*!< List of dynamic files */
307 };
308 struct ao2_container *profiles;
309 SIMPLE_HASH_FN(phone_profile_hash_fn, phone_profile, name)
310 SIMPLE_CMP_FN(phone_profile_cmp_fn, phone_profile, name)
311
312 /*! \brief structure to hold users read from users.conf */
313 struct user {
314         AST_DECLARE_STRING_FIELDS(
315                 AST_STRING_FIELD(macaddress);   /*!< Mac address of user's phone */
316                 AST_STRING_FIELD(provider_name);        /*!< Name of the provider who registered this mac */
317         );
318         struct phone_profile *profile;  /*!< Profile the phone belongs to */
319         AST_LIST_HEAD_NOLOCK(, extension) extensions;
320 };
321 struct ao2_container *users;
322 SIMPLE_HASH_FN(user_hash_fn, user, macaddress)
323 SIMPLE_CMP_FN(user_cmp_fn, user, macaddress)
324
325 /*! \brief structure to hold http routes (valid URIs, and the files they link to) */
326 struct http_route {
327         AST_DECLARE_STRING_FIELDS(
328                 AST_STRING_FIELD(uri);  /*!< The URI requested */
329         );
330         struct phoneprov_file *file;    /*!< The file that links to the URI */
331         struct user *user;      /*!< The user that has variables to substitute into the file
332                                                  * NULL in the case of a static route */
333         struct phone_profile *profile;
334 };
335 struct ao2_container *http_routes;
336 SIMPLE_HASH_FN(http_route_hash_fn, http_route, uri)
337 SIMPLE_CMP_FN(http_route_cmp_fn, http_route, uri)
338
339 #define SIPUSERS_PROVIDER_NAME "sipusers"
340
341 /* iface is the interface (e.g. eth0); address is the return value */
342 static int lookup_iface(const char *iface, struct in_addr *address)
343 {
344         int mysock, res = 0;
345         struct ifreq ifr;
346         struct sockaddr_in *sin;
347
348         memset(&ifr, 0, sizeof(ifr));
349         ast_copy_string(ifr.ifr_name, iface, sizeof(ifr.ifr_name));
350
351         mysock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
352         if (mysock < 0) {
353                 ast_log(LOG_ERROR, "Failed to create socket: %s\n", strerror(errno));
354                 return -1;
355         }
356
357         res = ioctl(mysock, SIOCGIFADDR, &ifr);
358
359         close(mysock);
360
361         if (res < 0) {
362                 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
363                 memcpy(address, &__ourip, sizeof(__ourip));
364                 return -1;
365         } else {
366                 sin = (struct sockaddr_in *)&ifr.ifr_addr;
367                 memcpy(address, &sin->sin_addr, sizeof(*address));
368                 return 0;
369         }
370 }
371
372 static struct phoneprov_provider *find_provider(char *name)
373 {
374         return ao2_find(providers, name, OBJ_SEARCH_KEY);
375 }
376
377 /*! \brief Delete all providers */
378 static void delete_providers(void)
379 {
380         if (!providers) {
381                 return;
382         }
383
384         ao2_callback(providers, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
385 }
386
387 static void provider_destructor(void *obj)
388 {
389         struct phoneprov_provider *provider = obj;
390         ast_string_field_free_memory(provider);
391 }
392
393 static void delete_file(struct phoneprov_file *file)
394 {
395         ast_string_field_free_memory(file);
396         ast_free(file);
397 }
398
399 /*! \brief Read a TEXT file into a string and return the length */
400 static int load_file(const char *filename, char **ret)
401 {
402         int len = 0;
403         FILE *f;
404
405         if (!(f = fopen(filename, "r"))) {
406                 *ret = NULL;
407                 return -1;
408         }
409
410         fseek(f, 0, SEEK_END);
411         len = ftell(f);
412         fseek(f, 0, SEEK_SET);
413         if (!(*ret = ast_malloc(len + 1))) {
414                 fclose(f);
415                 return -2;
416         }
417
418         if (len != fread(*ret, sizeof(char), len, f)) {
419                 fclose(f);
420                 ast_free(*ret);
421                 *ret = NULL;
422                 return -3;
423         }
424
425         fclose(f);
426
427         (*ret)[len] = '\0';
428
429         return len;
430 }
431
432 /*! \brief Set all timezone-related variables based on a zone (i.e. America/New_York)
433         \param headp pointer to list of user variables
434         \param zone A time zone. NULL sets variables based on timezone of the machine
435 */
436 static void set_timezone_variables(struct varshead *headp, const char *zone)
437 {
438         time_t utc_time;
439         int dstenable;
440         time_t dststart;
441         time_t dstend;
442         struct ast_tm tm_info;
443         int tzoffset;
444         char buffer[21];
445         struct timeval when;
446
447         time(&utc_time);
448         ast_get_dst_info(&utc_time, &dstenable, &dststart, &dstend, &tzoffset, zone);
449         snprintf(buffer, sizeof(buffer), "%d", tzoffset);
450         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("TZOFFSET", buffer));
451
452         if (!dstenable) {
453                 return;
454         }
455
456         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_ENABLE", "1"));
457
458         when.tv_sec = dststart;
459         ast_localtime(&when, &tm_info, zone);
460
461         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mon+1);
462         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_START_MONTH", buffer));
463
464         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mday);
465         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_START_MDAY", buffer));
466
467         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_hour);
468         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_START_HOUR", buffer));
469
470         when.tv_sec = dstend;
471         ast_localtime(&when, &tm_info, zone);
472
473         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mon + 1);
474         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_END_MONTH", buffer));
475
476         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mday);
477         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_END_MDAY", buffer));
478
479         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_hour);
480         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_END_HOUR", buffer));
481 }
482
483 static struct http_route *unref_route(struct http_route *route)
484 {
485         ao2_cleanup(route);
486
487         return NULL;
488 }
489
490 static void route_destructor(void *obj)
491 {
492         struct http_route *route = obj;
493
494         ast_string_field_free_memory(route);
495 }
496
497 /*! \brief Delete all http routes, freeing their memory */
498 static void delete_routes(void)
499 {
500         if (!http_routes) {
501                 return;
502         }
503
504         ao2_callback(http_routes, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
505 }
506
507 /*! \brief Build a route structure and add it to the list of available http routes
508         \param pp_file File to link to the route
509         \param user User to link to the route (NULL means static route)
510         \param uri URI of the route
511 */
512 static void build_route(struct phoneprov_file *pp_file, struct phone_profile *profile, struct user *user, char *uri)
513 {
514         struct http_route *route;
515
516         if (!(route = ao2_alloc(sizeof(*route), route_destructor))) {
517                 return;
518         }
519
520         if (ast_string_field_init(route, 32)) {
521                 ast_log(LOG_ERROR, "Couldn't create string fields for %s\n", pp_file->format);
522                 route = unref_route(route);
523                 return;
524         }
525
526         ast_string_field_set(route, uri, S_OR(uri, pp_file->format));
527         route->user = user;
528         route->file = pp_file;
529         route->profile = profile;
530
531         ao2_link(http_routes, route);
532
533         route = unref_route(route);
534 }
535
536 static struct phone_profile *unref_profile(struct phone_profile *prof)
537 {
538         ao2_cleanup(prof);
539
540         return NULL;
541 }
542
543 /*! \brief Return a phone profile looked up by name */
544 static struct phone_profile *find_profile(const char *name)
545 {
546         return ao2_find(profiles, name, OBJ_SEARCH_KEY);
547 }
548
549 static void profile_destructor(void *obj)
550 {
551         struct phone_profile *profile = obj;
552         struct phoneprov_file *file;
553         struct ast_var_t *var;
554
555         while ((file = AST_LIST_REMOVE_HEAD(&profile->static_files, entry))) {
556                 delete_file(file);
557         }
558
559         while ((file = AST_LIST_REMOVE_HEAD(&profile->dynamic_files, entry))) {
560                 delete_file(file);
561         }
562
563         while ((var = AST_LIST_REMOVE_HEAD(profile->headp, entries))) {
564                 ast_var_delete(var);
565         }
566
567         ast_free(profile->headp);
568         ast_string_field_free_memory(profile);
569 }
570
571 /*! \brief Delete all phone profiles, freeing their memory */
572 static void delete_profiles(void)
573 {
574         if (!profiles) {
575                 return;
576         }
577
578         ao2_callback(profiles, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
579 }
580
581 /*! \brief Build a phone profile and add it to the list of phone profiles
582         \param name the name of the profile
583         \param v ast_variable from parsing phoneprov.conf
584 */
585 static void build_profile(const char *name, struct ast_variable *v)
586 {
587         struct phone_profile *profile;
588
589         if (!(profile = ao2_alloc(sizeof(*profile), profile_destructor))) {
590                 return;
591         }
592
593         if (ast_string_field_init(profile, 32)) {
594                 profile = unref_profile(profile);
595                 return;
596         }
597
598         if (!(profile->headp = ast_var_list_create())) {
599                 profile = unref_profile(profile);
600                 return;
601         }
602
603         AST_LIST_HEAD_INIT_NOLOCK(&profile->static_files);
604         AST_LIST_HEAD_INIT_NOLOCK(&profile->dynamic_files);
605
606         ast_string_field_set(profile, name, name);
607         for (; v; v = v->next) {
608                 if (!strcasecmp(v->name, "mime_type")) {
609                         ast_string_field_set(profile, default_mime_type, v->value);
610                 } else if (!strcasecmp(v->name, "setvar")) {
611                         char *value_copy = ast_strdupa(v->value);
612
613                         AST_DECLARE_APP_ARGS(args,
614                                 AST_APP_ARG(varname);
615                                 AST_APP_ARG(varval);
616                         );
617
618                         AST_NONSTANDARD_APP_ARGS(args, value_copy, '=');
619                         do {
620                                 if (ast_strlen_zero(args.varname) || ast_strlen_zero(args.varval))
621                                         break;
622                                 args.varname = ast_strip(args.varname);
623                                 args.varval = ast_strip(args.varval);
624                                 if (ast_strlen_zero(args.varname) || ast_strlen_zero(args.varval))
625                                         break;
626                                 AST_VAR_LIST_INSERT_TAIL(profile->headp, ast_var_assign(args.varname, args.varval));
627                         } while (0);
628                 } else if (!strcasecmp(v->name, "staticdir")) {
629                         ast_string_field_set(profile, staticdir, v->value);
630                 } else {
631                         struct phoneprov_file *pp_file;
632                         char *file_extension;
633                         char *value_copy = ast_strdupa(v->value);
634
635                         AST_DECLARE_APP_ARGS(args,
636                                 AST_APP_ARG(filename);
637                                 AST_APP_ARG(mimetype);
638                         );
639
640                         if (!(pp_file = ast_calloc_with_stringfields(1, struct phoneprov_file, 32))) {
641                                 profile = unref_profile(profile);
642                                 return;
643                         }
644
645                         if ((file_extension = strrchr(pp_file->format, '.')))
646                                 file_extension++;
647
648                         AST_STANDARD_APP_ARGS(args, value_copy);
649
650                         /* Mime type order of preference
651                          * 1) Specific mime-type defined for file in profile
652                          * 2) Mime determined by extension
653                          * 3) Default mime type specified in profile
654                          * 4) text/plain
655                          */
656                         ast_string_field_set(pp_file, mime_type, S_OR(args.mimetype,
657                                 (S_OR(S_OR(ast_http_ftype2mtype(file_extension), profile->default_mime_type), "text/plain"))));
658
659                         if (!strcasecmp(v->name, "static_file")) {
660                                 ast_string_field_set(pp_file, format, args.filename);
661                                 ast_string_field_build(pp_file, template, "%s%s", profile->staticdir, args.filename);
662                                 AST_LIST_INSERT_TAIL(&profile->static_files, pp_file, entry);
663                                 /* Add a route for the static files, as their filenames won't change per-user */
664                                 build_route(pp_file, profile, NULL, NULL);
665                         } else {
666                                 ast_string_field_set(pp_file, format, v->name);
667                                 ast_string_field_set(pp_file, template, args.filename);
668                                 AST_LIST_INSERT_TAIL(&profile->dynamic_files, pp_file, entry);
669                         }
670                 }
671         }
672
673         ao2_link(profiles, profile);
674
675         profile = unref_profile(profile);
676 }
677
678 static struct extension *delete_extension(struct extension *exten)
679 {
680         ast_var_list_destroy(exten->headp);
681         ast_string_field_free_memory(exten);
682         ast_free(exten);
683
684         return NULL;
685 }
686
687 static struct extension *build_extension(const char *name, struct varshead *vars)
688 {
689         struct extension *exten;
690         const char *tmp;
691
692         if (!(exten = ast_calloc_with_stringfields(1, struct extension, 32))) {
693                 return NULL;
694         }
695
696         ast_string_field_set(exten, name, name);
697
698         exten->headp = ast_var_list_clone(vars);
699         if (!exten->headp) {
700                 ast_log(LOG_ERROR, "Unable to clone variables for extension '%s'\n", name);
701                 delete_extension(exten);
702                 return NULL;
703         }
704
705         tmp = ast_var_find(exten->headp, variable_lookup[AST_PHONEPROV_STD_LINENUMBER]);
706         if (!tmp) {
707                 AST_VAR_LIST_INSERT_TAIL(exten->headp,
708                         ast_var_assign(variable_lookup[AST_PHONEPROV_STD_LINENUMBER], "1"));
709                 exten->index = 1;
710         } else {
711                 sscanf(tmp, "%d", &exten->index);
712         }
713
714         if (!ast_var_find(exten->headp, variable_lookup[AST_PHONEPROV_STD_LINEKEYS])) {
715                 AST_VAR_LIST_INSERT_TAIL(exten->headp,
716                         ast_var_assign(variable_lookup[AST_PHONEPROV_STD_LINEKEYS], "1"));
717         }
718
719         set_timezone_variables(exten->headp,
720                 ast_var_find(vars, variable_lookup[AST_PHONEPROV_STD_TIMEZONE]));
721
722         return exten;
723 }
724
725 static struct user *unref_user(struct user *user)
726 {
727         ao2_cleanup(user);
728
729         return NULL;
730 }
731
732 /*! \brief Return a user looked up by name */
733 static struct user *find_user(const char *macaddress)
734 {
735         return ao2_find(users, macaddress, OBJ_SEARCH_KEY);
736 }
737
738 static int routes_delete_cb(void *obj, void *arg, int flags)
739 {
740         struct http_route *route = obj;
741         struct user *user = route->user;
742         char *macaddress = arg;
743
744         if (user && !strcmp(user->macaddress, macaddress)) {
745                 return CMP_MATCH;
746         }
747         return 0;
748 }
749
750 /*! \brief Free all memory associated with a user */
751 static void user_destructor(void *obj)
752 {
753         struct user *user = obj;
754         struct extension *exten;
755
756         while ((exten = AST_LIST_REMOVE_HEAD(&user->extensions, entry))) {
757                 exten = delete_extension(exten);
758         }
759
760         if (user->profile) {
761                 user->profile = unref_profile(user->profile);
762         }
763
764         if (http_routes) {
765                 ao2_callback(http_routes, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, routes_delete_cb, (void *)user->macaddress);
766         }
767
768         ast_string_field_free_memory(user);
769 }
770
771 /*! \brief Delete all users */
772 static void delete_users(void)
773 {
774         if (!users) {
775                 return;
776         }
777
778         ao2_callback(users, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
779 }
780
781 /*! \brief Build and return a user structure based on gathered config data */
782 static struct user *build_user(const char *mac, struct phone_profile *profile, char *provider_name)
783 {
784         struct user *user;
785
786         if (!(user = ao2_alloc(sizeof(*user), user_destructor))) {
787                 return NULL;
788         }
789
790         if (ast_string_field_init(user, 64)) {
791                 user = unref_user(user);
792                 return NULL;
793         }
794
795         ast_string_field_set(user, macaddress, mac);
796         ast_string_field_set(user, provider_name, provider_name);
797         user->profile = profile;
798         ao2_ref(profile, 1);
799
800         return user;
801 }
802
803 /*! \brief Add an extension to a user ordered by index/linenumber */
804 static int add_user_extension(struct user *user, struct extension *exten)
805 {
806         struct ast_var_t *pvar, *var2;
807         struct ast_str *str = ast_str_create(16);
808
809         if (!str) {
810                 return -1;
811         }
812
813         /* Append profile variables here, and substitute variables on profile
814          * setvars, so that we can use user specific variables in them */
815         AST_VAR_LIST_TRAVERSE(user->profile->headp, pvar) {
816                 if (ast_var_find(exten->headp, pvar->name)) {
817                         continue;
818                 }
819
820                 ast_str_substitute_variables_varshead(&str, 0, exten->headp, pvar->value);
821                 if ((var2 = ast_var_assign(pvar->name, ast_str_buffer(str)))) {
822                         AST_VAR_LIST_INSERT_TAIL(exten->headp, var2);
823                 }
824         }
825         ast_free(str);
826
827         if (AST_LIST_EMPTY(&user->extensions)) {
828                 AST_LIST_INSERT_HEAD(&user->extensions, exten, entry);
829         } else {
830                 struct extension *exten_iter;
831
832                 AST_LIST_TRAVERSE_SAFE_BEGIN(&user->extensions, exten_iter, entry) {
833                         if (exten->index < exten_iter->index) {
834                                 AST_LIST_INSERT_BEFORE_CURRENT(exten, entry);
835                         } else if (exten->index == exten_iter->index) {
836                                 ast_log(LOG_WARNING, "Duplicate linenumber=%d for %s\n", exten->index, user->macaddress);
837                                 return -1;
838                         } else if (!AST_LIST_NEXT(exten_iter, entry)) {
839                                 AST_LIST_INSERT_TAIL(&user->extensions, exten, entry);
840                         }
841                 }
842                 AST_LIST_TRAVERSE_SAFE_END;
843         }
844
845         return 0;
846 }
847
848 /*! \brief Add an http route for dynamic files attached to the profile of the user */
849 static int build_user_routes(struct user *user)
850 {
851         struct phoneprov_file *pp_file;
852         struct ast_str *str;
853
854         if (!(str = ast_str_create(16))) {
855                 return -1;
856         }
857
858         AST_LIST_TRAVERSE(&user->profile->dynamic_files, pp_file, entry) {
859                 ast_str_substitute_variables_varshead(&str, 0, AST_LIST_FIRST(&user->extensions)->headp, pp_file->format);
860                 build_route(pp_file, user->profile, user, ast_str_buffer(str));
861         }
862
863         ast_free(str);
864         return 0;
865 }
866
867 /*! \brief Callback that is executed everytime an http request is received by this module */
868 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)
869 {
870         struct http_route *route;
871         struct ast_str *result;
872         char path[PATH_MAX];
873         char *file = NULL;
874         char *server;
875         int len;
876         int fd;
877         struct ast_str *http_header;
878
879         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
880                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
881                 return 0;
882         }
883
884         if (!(route = ao2_find(http_routes, uri, OBJ_SEARCH_KEY))) {
885                 goto out404;
886         }
887
888         snprintf(path, sizeof(path), "%s/phoneprov/%s", ast_config_AST_DATA_DIR, route->file->template);
889
890         if (!route->user) { /* Static file */
891
892                 fd = open(path, O_RDONLY);
893                 if (fd < 0) {
894                         goto out500;
895                 }
896
897                 len = lseek(fd, 0, SEEK_END);
898                 lseek(fd, 0, SEEK_SET);
899                 if (len < 0) {
900                         ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, len);
901                         close(fd);
902                         goto out500;
903                 }
904
905                 http_header = ast_str_create(80);
906                 ast_str_set(&http_header, 0, "Content-type: %s\r\n",
907                         route->file->mime_type);
908
909                 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 0);
910
911                 close(fd);
912                 route = unref_route(route);
913                 return 0;
914         } else { /* Dynamic file */
915                 struct ast_str *tmp;
916
917                 len = load_file(path, &file);
918                 if (len < 0) {
919                         ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, len);
920                         if (file) {
921                                 ast_free(file);
922                         }
923
924                         goto out500;
925                 }
926
927                 if (!file) {
928                         goto out500;
929                 }
930
931                 if (!(tmp = ast_str_create(len))) {
932                         if (file) {
933                                 ast_free(file);
934                         }
935
936                         goto out500;
937                 }
938
939                 /* Unless we are overridden by serveriface or serveraddr, we set the SERVER variable to
940                  * the IP address we are listening on that the phone contacted for this config file */
941
942                 server = ast_var_find(AST_LIST_FIRST(&route->user->extensions)->headp,
943                         variable_lookup[AST_PHONEPROV_STD_SERVER]);
944
945                 if (!server) {
946                         union {
947                                 struct sockaddr sa;
948                                 struct sockaddr_in sa_in;
949                         } name;
950                         socklen_t namelen = sizeof(name.sa);
951                         int res;
952
953                         if ((res = getsockname(ser->fd, &name.sa, &namelen))) {
954                                 ast_log(LOG_WARNING, "Could not get server IP, breakage likely.\n");
955                         } else {
956                                 struct extension *exten_iter;
957                                 const char *newserver = ast_inet_ntoa(name.sa_in.sin_addr);
958
959                                 AST_LIST_TRAVERSE(&route->user->extensions, exten_iter, entry) {
960                                         AST_VAR_LIST_INSERT_TAIL(exten_iter->headp,
961                                                 ast_var_assign(variable_lookup[AST_PHONEPROV_STD_SERVER], newserver));
962                                 }
963                         }
964                 }
965
966                 ast_str_substitute_variables_varshead(&tmp, 0, AST_LIST_FIRST(&route->user->extensions)->headp, file);
967
968                 ast_free(file);
969
970                 http_header = ast_str_create(80);
971                 ast_str_set(&http_header, 0, "Content-type: %s\r\n",
972                         route->file->mime_type);
973
974                 if (!(result = ast_str_create(512))) {
975                         ast_log(LOG_ERROR, "Could not create result string!\n");
976                         if (tmp) {
977                                 ast_free(tmp);
978                         }
979                         ast_free(http_header);
980                         goto out500;
981                 }
982                 ast_str_append(&result, 0, "%s", ast_str_buffer(tmp));
983
984                 ast_http_send(ser, method, 200, NULL, http_header, result, 0, 0);
985                 ast_free(tmp);
986
987                 route = unref_route(route);
988
989                 return 0;
990         }
991
992 out404:
993         ast_http_error(ser, 404, "Not Found", uri);
994         return 0;
995
996 out500:
997         route = unref_route(route);
998         ast_http_error(ser, 500, "Internal Error", "An internal error has occured.");
999         return 0;
1000 }
1001
1002 /*! \brief A dialplan function that can be used to print a string for each phoneprov user */
1003 static int pp_each_user_helper(struct ast_channel *chan, char *data, char *buf, struct ast_str **bufstr, int len)
1004 {
1005         char *tmp;
1006         struct ao2_iterator i;
1007         struct user *user;
1008         struct ast_str *str;
1009         AST_DECLARE_APP_ARGS(args,
1010                 AST_APP_ARG(string);
1011                 AST_APP_ARG(exclude_mac);
1012         );
1013         AST_STANDARD_APP_ARGS(args, data);
1014
1015         if (!(str = ast_str_create(16))) {
1016                 return -1;
1017         }
1018
1019         /* Fix data by turning %{ into ${ */
1020         while ((tmp = strstr(args.string, "%{")))
1021                 *tmp = '$';
1022
1023         i = ao2_iterator_init(users, 0);
1024         while ((user = ao2_iterator_next(&i))) {
1025                 if (!ast_strlen_zero(args.exclude_mac) && !strcasecmp(user->macaddress, args.exclude_mac)) {
1026                         continue;
1027                 }
1028                 ast_str_substitute_variables_varshead(&str, len, AST_LIST_FIRST(&user->extensions)->headp, args.string);
1029                 if (buf) {
1030                         size_t slen = len;
1031                         ast_build_string(&buf, &slen, "%s", ast_str_buffer(str));
1032                 } else {
1033                         ast_str_append(bufstr, len, "%s", ast_str_buffer(str));
1034                 }
1035                 user = unref_user(user);
1036         }
1037         ao2_iterator_destroy(&i);
1038
1039         ast_free(str);
1040         return 0;
1041 }
1042
1043 static int pp_each_user_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1044 {
1045         return pp_each_user_helper(chan, data, buf, NULL, len);
1046 }
1047
1048 static int pp_each_user_read2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
1049 {
1050         return pp_each_user_helper(chan, data, NULL, buf, len);
1051 }
1052
1053 static struct ast_custom_function pp_each_user_function = {
1054         .name = "PP_EACH_USER",
1055         .read = pp_each_user_read,
1056         .read2 = pp_each_user_read2,
1057 };
1058
1059 /*! \brief A dialplan function that can be used to output a template for each extension attached to a user */
1060 static int pp_each_extension_helper(struct ast_channel *chan, const char *cmd, char *data, char *buf, struct ast_str **bufstr, int len)
1061 {
1062         struct user *user;
1063         struct extension *exten;
1064         char path[PATH_MAX];
1065         char *file;
1066         int filelen;
1067         struct ast_str *str;
1068         AST_DECLARE_APP_ARGS(args,
1069                 AST_APP_ARG(mac);
1070                 AST_APP_ARG(template);
1071         );
1072
1073         AST_STANDARD_APP_ARGS(args, data);
1074
1075         if (ast_strlen_zero(args.mac) || ast_strlen_zero(args.template)) {
1076                 ast_log(LOG_WARNING, "PP_EACH_EXTENSION requries both a macaddress and template filename.\n");
1077                 return 0;
1078         }
1079
1080         if (!(user = find_user(args.mac))) {
1081                 ast_log(LOG_WARNING, "Could not find user with mac = '%s'\n", args.mac);
1082                 return 0;
1083         }
1084
1085         snprintf(path, sizeof(path), "%s/phoneprov/%s", ast_config_AST_DATA_DIR, args.template);
1086         filelen = load_file(path, &file);
1087         if (filelen < 0) {
1088                 ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, filelen);
1089                 if (file) {
1090                         ast_free(file);
1091                 }
1092                 return 0;
1093         }
1094
1095         if (!file) {
1096                 return 0;
1097         }
1098
1099         if (!(str = ast_str_create(filelen))) {
1100                 return 0;
1101         }
1102
1103         AST_LIST_TRAVERSE(&user->extensions, exten, entry) {
1104                 ast_str_substitute_variables_varshead(&str, 0, exten->headp, file);
1105                 if (buf) {
1106                         size_t slen = len;
1107                         ast_build_string(&buf, &slen, "%s", ast_str_buffer(str));
1108                 } else {
1109                         ast_str_append(bufstr, len, "%s", ast_str_buffer(str));
1110                 }
1111         }
1112
1113         ast_free(file);
1114         ast_free(str);
1115
1116         user = unref_user(user);
1117
1118         return 0;
1119 }
1120
1121 static int pp_each_extension_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1122 {
1123         return pp_each_extension_helper(chan, cmd, data, buf, NULL, len);
1124 }
1125
1126 static int pp_each_extension_read2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
1127 {
1128         return pp_each_extension_helper(chan, cmd, data, NULL, buf, len);
1129 }
1130
1131 static struct ast_custom_function pp_each_extension_function = {
1132         .name = "PP_EACH_EXTENSION",
1133         .read = pp_each_extension_read,
1134         .read2 = pp_each_extension_read2,
1135 };
1136
1137 #define FORMATS "%-20.20s %-40.40s  %-30.30s\n"
1138 #define FORMATD "%-20.20s %-20.20s %-40.40s  %-30.30s\n"
1139 static int route_list_cb(void *obj, void *arg, void *data, int flags)
1140 {
1141         int fd = *(int *)arg;
1142         struct http_route *route = obj;
1143
1144         if (data && route->user) {
1145                 ast_cli(fd, FORMATD, route->user->provider_name, route->profile->name, route->uri, route->file->template);
1146         }
1147         if (!data && !route->user) {
1148                 ast_cli(fd, FORMATS, route->profile->name, route->uri, route->file->template);
1149         }
1150
1151         return CMP_MATCH;
1152 }
1153
1154 /*! \brief CLI command to list static and dynamic routes */
1155 static char *handle_show_routes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1156 {
1157         int fd = a->fd;
1158         switch(cmd) {
1159         case CLI_INIT:
1160                 e->command = "phoneprov show routes";
1161                 e->usage =
1162                         "Usage: phoneprov show routes\n"
1163                         "       Lists all registered phoneprov http routes.\n";
1164                 return NULL;
1165         case CLI_GENERATE:
1166                 return NULL;
1167         }
1168
1169         /* This currently iterates over routes twice, but it is the only place I've needed
1170          * to really separate static an dynamic routes, so I've just left it this way. */
1171         ast_cli(a->fd, "Static routes\n\n");
1172         ast_cli(a->fd, FORMATS, "Profile", "Relative URI", "Physical location");
1173
1174         ao2_callback_data(http_routes, OBJ_NODATA | OBJ_MULTIPLE, route_list_cb, &fd, NULL);
1175
1176         ast_cli(a->fd, "\nDynamic routes\n\n");
1177         ast_cli(a->fd, FORMATD, "Provider", "Profile", "Relative URI", "Template");
1178
1179         ao2_callback_data(http_routes, OBJ_NODATA | OBJ_MULTIPLE, route_list_cb, &fd, (void *)1);
1180
1181         return CLI_SUCCESS;
1182 }
1183
1184 static struct ast_cli_entry pp_cli[] = {
1185         AST_CLI_DEFINE(handle_show_routes, "Show registered phoneprov http routes"),
1186 };
1187
1188 static struct ast_http_uri phoneprovuri = {
1189         .callback = phoneprov_callback,
1190         .description = "Asterisk HTTP Phone Provisioning Tool",
1191         .uri = "phoneprov",
1192         .has_subtree = 1,
1193         .data = NULL,
1194         .key = __FILE__,
1195 };
1196
1197 static struct varshead *get_defaults(void)
1198 {
1199         struct ast_config *phoneprov_cfg, *cfg = CONFIG_STATUS_FILEINVALID;
1200         const char *value;
1201         struct ast_variable *v;
1202         struct ast_var_t *var;
1203         struct ast_flags config_flags = { 0 };
1204         struct varshead *defaults = ast_var_list_create();
1205
1206         if (!defaults) {
1207                 ast_log(LOG_ERROR, "Unable to create default var list.\n");
1208                 return NULL;
1209         }
1210
1211         if (!(phoneprov_cfg = ast_config_load("phoneprov.conf", config_flags))
1212                 || phoneprov_cfg == CONFIG_STATUS_FILEINVALID) {
1213                 ast_log(LOG_ERROR, "Unable to load config phoneprov.conf\n");
1214                 ast_var_list_destroy(defaults);
1215                 return NULL;
1216         }
1217
1218         value = ast_variable_retrieve(phoneprov_cfg, "general", pp_general_lookup[AST_PHONEPROV_STD_SERVER]);
1219         if (!value) {
1220                 struct in_addr addr;
1221                 value = ast_variable_retrieve(phoneprov_cfg, "general", pp_general_lookup[AST_PHONEPROV_STD_SERVER_IFACE]);
1222                 if (value) {
1223                         lookup_iface(value, &addr);
1224                         value = ast_inet_ntoa(addr);
1225                 }
1226         }
1227         if (value) {
1228                 var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_SERVER], value);
1229                 AST_VAR_LIST_INSERT_TAIL(defaults, var);
1230         } else {
1231                 ast_log(LOG_WARNING, "Unable to find a valid server address or name.\n");
1232         }
1233
1234         value = ast_variable_retrieve(phoneprov_cfg, "general", pp_general_lookup[AST_PHONEPROV_STD_SERVER_PORT]);
1235         if (!value) {
1236                 if ((cfg = ast_config_load("sip.conf", config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1237                         value = ast_variable_retrieve(cfg, "general", "bindport");
1238                 }
1239         }
1240         var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_SERVER_PORT], S_OR(value, "5060"));
1241         if (cfg && cfg != CONFIG_STATUS_FILEINVALID) {
1242                 ast_config_destroy(cfg);
1243         }
1244         AST_VAR_LIST_INSERT_TAIL(defaults, var);
1245
1246         value = ast_variable_retrieve(phoneprov_cfg, "general", pp_general_lookup[AST_PHONEPROV_STD_PROFILE]);
1247         if (!value) {
1248                 ast_log(LOG_ERROR, "Unable to load default profile.\n");
1249                 ast_config_destroy(phoneprov_cfg);
1250                 ast_var_list_destroy(defaults);
1251                 return NULL;
1252         }
1253         var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_PROFILE], value);
1254         AST_VAR_LIST_INSERT_TAIL(defaults, var);
1255         ast_config_destroy(phoneprov_cfg);
1256
1257         if (!(cfg = ast_config_load("users.conf", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
1258                 ast_log(LOG_ERROR, "Unable to load users.conf\n");
1259                 ast_var_list_destroy(defaults);
1260                 return NULL;
1261         }
1262
1263         /* Go ahead and load global variables from users.conf so we can append to profiles */
1264         for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
1265                 if (!strcasecmp(v->name, pp_user_lookup[AST_PHONEPROV_STD_VOICEMAIL_EXTEN])) {
1266                         var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_VOICEMAIL_EXTEN], v->value);
1267                         AST_VAR_LIST_INSERT_TAIL(defaults, var);
1268                 }
1269                 if (!strcasecmp(v->name, pp_user_lookup[AST_PHONEPROV_STD_EXTENSION_LENGTH])) {
1270                         var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_EXTENSION_LENGTH], v->value);
1271                         AST_VAR_LIST_INSERT_TAIL(defaults, var);
1272                 }
1273         }
1274         ast_config_destroy(cfg);
1275
1276         return defaults;
1277 }
1278
1279 static int load_users(void)
1280 {
1281         struct ast_config *cfg;
1282         char *cat;
1283         const char *value;
1284         struct ast_flags config_flags = { 0 };
1285         struct varshead *defaults = get_defaults();
1286
1287         if (!defaults) {
1288                 ast_log(LOG_WARNING, "Unable to load default variables.\n");
1289                 return -1;
1290         }
1291
1292         if (!(cfg = ast_config_load("users.conf", config_flags))
1293                 || cfg == CONFIG_STATUS_FILEINVALID) {
1294                 ast_log(LOG_WARNING, "Unable to load users.conf\n");
1295                 ast_var_list_destroy(defaults);
1296                 return -1;
1297         }
1298
1299         cat = NULL;
1300         while ((cat = ast_category_browse(cfg, cat))) {
1301                 const char *tmp;
1302                 int i;
1303                 struct ast_var_t *varx;
1304                 struct ast_var_t *vard;
1305
1306                 if (strcasecmp(cat, "general") && strcasecmp(cat, "authentication")) {
1307                         struct varshead *variables = ast_var_list_create();
1308
1309                         if (!((tmp = ast_variable_retrieve(cfg, cat, "autoprov")) && ast_true(tmp))) {
1310                                 ast_var_list_destroy(variables);
1311                                 continue;
1312                         }
1313
1314                         /* Transfer the standard variables */
1315                         for (i = 0; i < AST_PHONEPROV_STD_VAR_LIST_LENGTH; i++) {
1316                                 if (pp_user_lookup[i]) {
1317                                         value = ast_variable_retrieve(cfg, cat, pp_user_lookup[i]);
1318                                         if (value) {
1319                                                 varx = ast_var_assign(variable_lookup[i],
1320                                                         value);
1321                                                 AST_VAR_LIST_INSERT_TAIL(variables, varx);
1322                                         }
1323                                 }
1324                         }
1325
1326                         if (!ast_var_find(variables, variable_lookup[AST_PHONEPROV_STD_MAC])) {
1327                                 ast_log(LOG_WARNING, "autoprov set for %s, but no mac address - skipping.\n", cat);
1328                                 ast_var_list_destroy(variables);
1329                                 continue;
1330                         }
1331
1332                         /* Apply defaults */
1333                         AST_VAR_LIST_TRAVERSE(defaults, vard) {
1334                                 if (ast_var_find(variables, vard->name)) {
1335                                         continue;
1336                                 }
1337                                 varx = ast_var_assign(vard->name, vard->value);
1338                                 AST_VAR_LIST_INSERT_TAIL(variables, varx);
1339                         }
1340
1341                         ast_phoneprov_add_extension(SIPUSERS_PROVIDER_NAME, variables);
1342                 }
1343         }
1344         ast_config_destroy(cfg);
1345         ast_var_list_destroy(defaults);
1346         return 0;
1347 }
1348
1349 static int load_common(void)
1350 {
1351         struct ast_config *phoneprov_cfg;
1352         struct ast_flags config_flags = { 0 };
1353         char *cat;
1354
1355         if (!(phoneprov_cfg = ast_config_load("phoneprov.conf", config_flags))
1356                 || phoneprov_cfg == CONFIG_STATUS_FILEINVALID) {
1357                 ast_log(LOG_ERROR, "Unable to load config phoneprov.conf\n");
1358                 return -1;
1359         }
1360
1361         cat = NULL;
1362         while ((cat = ast_category_browse(phoneprov_cfg, cat))) {
1363                 if (!strcasecmp(cat, "general")) {
1364                         continue;
1365                 }
1366                 build_profile(cat, ast_variable_browse(phoneprov_cfg, cat));
1367         }
1368         ast_config_destroy(phoneprov_cfg);
1369
1370         if (!ao2_container_count(profiles)) {
1371                 ast_log(LOG_ERROR, "There are no provisioning profiles in phoneprov.conf.\n");
1372                 return -1;
1373         }
1374
1375         return 0;
1376 }
1377
1378 static int unload_module(void)
1379 {
1380         ast_http_uri_unlink(&phoneprovuri);
1381         ast_custom_function_unregister(&pp_each_user_function);
1382         ast_custom_function_unregister(&pp_each_extension_function);
1383         ast_cli_unregister_multiple(pp_cli, ARRAY_LEN(pp_cli));
1384
1385         /* This cleans up the sip.conf/users.conf provider (called specifically for clarity) */
1386         ast_phoneprov_provider_unregister(SIPUSERS_PROVIDER_NAME);
1387
1388         /* This cleans up the framework which also cleans up the providers. */
1389         delete_profiles();
1390         ao2_cleanup(profiles);
1391         profiles = NULL;
1392         delete_routes();
1393         delete_users();
1394         ao2_cleanup(http_routes);
1395         http_routes = NULL;
1396         ao2_cleanup(users);
1397         users = NULL;
1398         delete_providers();
1399         ao2_cleanup(providers);
1400         providers = NULL;
1401
1402         return 0;
1403 }
1404
1405 /*!
1406  * \brief Load the module
1407  *
1408  * Module loading including tests for configuration or dependencies.
1409  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1410  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1411  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1412  * configuration file or other non-critical problem return
1413  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1414  */
1415 static int load_module(void)
1416 {
1417         profiles = ao2_container_alloc(MAX_PROFILE_BUCKETS, phone_profile_hash_fn, phone_profile_cmp_fn);
1418         if (!profiles) {
1419                 ast_log(LOG_ERROR, "Unable to allocate profiles container.\n");
1420                 return AST_MODULE_LOAD_DECLINE;
1421         }
1422
1423         http_routes = ao2_container_alloc(MAX_ROUTE_BUCKETS, http_route_hash_fn, http_route_cmp_fn);
1424         if (!http_routes) {
1425                 ast_log(LOG_ERROR, "Unable to allocate routes container.\n");
1426                 goto error;
1427         }
1428
1429         if (load_common()) {
1430                 ast_log(LOG_ERROR, "Unable to load provisioning profiles.\n");
1431                 goto error;
1432         }
1433
1434         users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_fn, user_cmp_fn);
1435         if (!users) {
1436                 ast_log(LOG_ERROR, "Unable to allocate users container.\n");
1437                 goto error;
1438         }
1439
1440         providers = ao2_container_alloc(MAX_PROVIDER_BUCKETS, phoneprov_provider_hash_fn, phoneprov_provider_cmp_fn);
1441         if (!providers) {
1442                 ast_log(LOG_ERROR, "Unable to allocate providers container.\n");
1443                 goto error;
1444         }
1445
1446         /* Register ourselves as the provider for sip.conf/users.conf */
1447         if (ast_phoneprov_provider_register(SIPUSERS_PROVIDER_NAME, load_users)) {
1448                 ast_log(LOG_WARNING, "Unable register sip/users config provider.  Others may succeed.\n");
1449         }
1450
1451         ast_http_uri_link(&phoneprovuri);
1452
1453         ast_custom_function_register(&pp_each_user_function);
1454         ast_custom_function_register(&pp_each_extension_function);
1455         ast_cli_register_multiple(pp_cli, ARRAY_LEN(pp_cli));
1456
1457         return AST_MODULE_LOAD_SUCCESS;
1458
1459 error:
1460         unload_module();
1461         return AST_MODULE_LOAD_DECLINE;
1462 }
1463
1464 static int reload(void)
1465 {
1466         struct ao2_iterator i;
1467         struct phoneprov_provider *provider;
1468
1469         /* Clean everything except the providers */
1470         delete_routes();
1471         delete_users();
1472         delete_profiles();
1473
1474         /* Reload the profiles */
1475         if (load_common()) {
1476                 ast_log(LOG_ERROR, "Unable to reload provisioning profiles.\n");
1477                 unload_module();
1478                 return AST_MODULE_LOAD_DECLINE;
1479         }
1480
1481         /* For each provider, reload the users */
1482         ao2_lock(providers);
1483         i = ao2_iterator_init(providers, 0);
1484         for(; (provider = ao2_iterator_next(&i)); ao2_ref(provider, -1)) {
1485                 if (provider->load_users()) {
1486                         ast_log(LOG_ERROR, "Unable to load provider '%s' users. Reload aborted.\n", provider->provider_name);
1487                         continue;
1488                 }
1489         }
1490         ao2_iterator_destroy(&i);
1491         ao2_unlock(providers);
1492
1493         return AST_MODULE_LOAD_SUCCESS;
1494 }
1495
1496 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "HTTP Phone Provisioning",
1497         .support_level = AST_MODULE_SUPPORT_EXTENDED,
1498         .load = load_module,
1499         .unload = unload_module,
1500         .reload = reload,
1501         .load_pri = AST_MODPRI_CHANNEL_DEPEND,
1502 );
1503
1504 /****  Public API for register/unregister, set defaults, and add extension. ****/
1505
1506 const char *ast_phoneprov_std_variable_lookup(enum ast_phoneprov_std_variables var)
1507 {
1508         if (var >= AST_PHONEPROV_STD_VAR_LIST_LENGTH) {
1509                 return NULL;
1510         }
1511
1512         return variable_lookup[var];
1513 }
1514
1515 int ast_phoneprov_provider_register(char *provider_name,
1516         ast_phoneprov_load_users_cb load_users)
1517 {
1518         struct phoneprov_provider *provider;
1519
1520         if (ast_strlen_zero(provider_name)) {
1521                 ast_log(LOG_ERROR, "Provider name can't be empty.\n");
1522                 return -1;
1523         }
1524
1525         if (!providers) {
1526                 ast_log(LOG_WARNING, "Provider '%s' cannot be registered: res_phoneprov not loaded.\n", provider_name);
1527                 return -1;
1528         }
1529
1530         provider = find_provider(provider_name);
1531         if (provider) {
1532                 ast_log(LOG_ERROR, "There is already a provider registered named '%s'.\n", provider_name);
1533                 ao2_ref(provider, -1);
1534                 return -1;
1535         }
1536
1537         provider = ao2_alloc(sizeof(struct phoneprov_provider), provider_destructor);
1538         if (!provider) {
1539                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory for provider '%s'.\n", provider_name);
1540                 return -1;
1541         }
1542
1543         if (ast_string_field_init(provider, 32)) {
1544                 ao2_ref(provider, -1);
1545                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory for provider '%s' stringfields.\n", provider_name);
1546                 return -1;
1547         }
1548
1549         ast_string_field_set(provider, provider_name, provider_name);
1550         provider->load_users = load_users;
1551
1552         ao2_link(providers, provider);
1553         ao2_ref(provider, -1);
1554
1555         if (provider->load_users()) {
1556                 ast_log(LOG_ERROR, "Unable to load provider '%s' users. Register aborted.\n", provider_name);
1557                 ast_phoneprov_provider_unregister(provider_name);
1558                 return -1;
1559         }
1560
1561         return 0;
1562 }
1563
1564 static int extensions_delete_cb(void *obj, void *arg, int flags)
1565 {
1566         char *provider_name = arg;
1567         struct user *user = obj;
1568         if (strcmp(user->provider_name, provider_name)) {
1569                 return 0;
1570         }
1571         return CMP_MATCH;
1572 }
1573
1574 static int extension_delete_cb(void *obj, void *arg, void *data, int flags)
1575 {
1576         struct user *user = obj;
1577         char *provider_name = data;
1578         char *macaddress = arg;
1579
1580         if (!strcmp(user->provider_name, provider_name) && !strcasecmp(user->macaddress, macaddress)) {
1581                 return CMP_MATCH;
1582         }
1583         return 0;
1584 }
1585
1586 void ast_phoneprov_delete_extension(char *provider_name, char *macaddress)
1587 {
1588         if (!users) {
1589                 return;
1590         }
1591
1592         ao2_callback_data(users, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
1593                 extension_delete_cb, macaddress, provider_name);
1594 }
1595
1596 void ast_phoneprov_delete_extensions(char *provider_name)
1597 {
1598         if (!users) {
1599                 return;
1600         }
1601
1602         ao2_callback(users, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, extensions_delete_cb, provider_name);
1603 }
1604
1605 void ast_phoneprov_provider_unregister(char *provider_name)
1606 {
1607         if (!providers) {
1608                 return;
1609         }
1610
1611         ast_phoneprov_delete_extensions(provider_name);
1612         ao2_find(providers, provider_name, OBJ_SEARCH_KEY | OBJ_NODATA | OBJ_UNLINK);
1613 }
1614
1615 int ast_phoneprov_add_extension(char *provider_name, struct varshead *vars)
1616 {
1617         RAII_VAR(struct phoneprov_provider *, provider, NULL, ao2_cleanup);
1618         RAII_VAR(struct user *, user, NULL, ao2_cleanup);
1619         RAII_VAR(struct phone_profile *, profile, NULL, ao2_cleanup);
1620         struct extension *exten;
1621         char *profile_name;
1622         char *mac;
1623         char *username;
1624
1625         if (ast_strlen_zero(provider_name)) {
1626                 ast_log(LOG_ERROR, "Provider name can't be empty.\n");
1627                 return -1;
1628         }
1629         if (!vars) {
1630                 ast_log(LOG_ERROR, "Variable list can't be empty.\n");
1631                 return -1;
1632         }
1633
1634         username = ast_var_find(vars, variable_lookup[AST_PHONEPROV_STD_USERNAME]);
1635         if (!username) {
1636                 ast_log(LOG_ERROR, "Extension name can't be empty.\n");
1637                 return -1;
1638         }
1639
1640         mac = ast_var_find(vars, variable_lookup[AST_PHONEPROV_STD_MAC]);
1641         if (!mac) {
1642                 ast_log(LOG_ERROR, "MAC Address can't be empty.\n");
1643                 return -1;
1644         }
1645
1646         provider = find_provider(provider_name);
1647         if (!provider) {
1648                 ast_log(LOG_ERROR, "Provider '%s' wasn't found in the registry.\n", provider_name);
1649                 return -1;
1650         }
1651
1652         profile_name = ast_var_find(vars,
1653                 variable_lookup[AST_PHONEPROV_STD_PROFILE]);
1654         if (!profile_name) {
1655                 ast_log(LOG_ERROR, "No profile could be found for user '%s' - skipping.\n", username);
1656                 return -1;
1657         }
1658         if (!(profile = find_profile(profile_name))) {
1659                 ast_log(LOG_ERROR, "Could not look up profile '%s' - skipping.\n", profile_name);
1660                 return -1;
1661         }
1662
1663         if (!(user = find_user(mac))) {
1664
1665                 if (!(user = build_user(mac, profile, provider_name))) {
1666                         ast_log(LOG_ERROR, "Could not create user for '%s' - skipping\n", mac);
1667                         return -1;
1668                 }
1669
1670                 if (!(exten = build_extension(username, vars))) {
1671                         ast_log(LOG_ERROR, "Could not create extension for '%s' - skipping\n", user->macaddress);
1672                         return -1;
1673                 }
1674
1675                 if (add_user_extension(user, exten)) {
1676                         ast_log(LOG_WARNING, "Could not add extension '%s' to user '%s'\n", exten->name, user->macaddress);
1677                         exten = delete_extension(exten);
1678                         return -1;
1679                 }
1680
1681                 if (build_user_routes(user)) {
1682                         ast_log(LOG_WARNING, "Could not create http routes for '%s' - skipping\n", user->macaddress);
1683                         return -1;
1684                 }
1685                 ao2_link(users, user);
1686
1687         } else {
1688                 if (strcmp(provider_name, user->provider_name)) {
1689                         ast_log(LOG_ERROR, "MAC address '%s' was already added by provider '%s' - skipping\n", user->macaddress, user->provider_name);
1690                         return -1;
1691                 }
1692
1693                 if (!(exten = build_extension(username, vars))) {
1694                         ast_log(LOG_ERROR, "Could not create extension for '%s' - skipping\n", user->macaddress);
1695                         return -1;
1696                 }
1697
1698                 if (add_user_extension(user, exten)) {
1699                         ast_log(LOG_WARNING, "Could not add extension '%s' to user '%s'\n", exten->name, user->macaddress);
1700                         exten = delete_extension(exten);
1701                         return -1;
1702                 }
1703         }
1704
1705         return 0;
1706 }