res_pjsip: Allow configuration of endpoint identifier query order
[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_FILE_VERSION(__FILE__, "$Revision$")
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                 return -2;
415
416         if (len != fread(*ret, sizeof(char), len, f)) {
417                 ast_free(*ret);
418                 *ret = NULL;
419                 return -3;
420         }
421
422         fclose(f);
423
424         (*ret)[len] = '\0';
425
426         return len;
427 }
428
429 /*! \brief Set all timezone-related variables based on a zone (i.e. America/New_York)
430         \param headp pointer to list of user variables
431         \param zone A time zone. NULL sets variables based on timezone of the machine
432 */
433 static void set_timezone_variables(struct varshead *headp, const char *zone)
434 {
435         time_t utc_time;
436         int dstenable;
437         time_t dststart;
438         time_t dstend;
439         struct ast_tm tm_info;
440         int tzoffset;
441         char buffer[21];
442         struct timeval when;
443
444         time(&utc_time);
445         ast_get_dst_info(&utc_time, &dstenable, &dststart, &dstend, &tzoffset, zone);
446         snprintf(buffer, sizeof(buffer), "%d", tzoffset);
447         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("TZOFFSET", buffer));
448
449         if (!dstenable) {
450                 return;
451         }
452
453         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_ENABLE", "1"));
454
455         when.tv_sec = dststart;
456         ast_localtime(&when, &tm_info, zone);
457
458         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mon+1);
459         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_START_MONTH", buffer));
460
461         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mday);
462         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_START_MDAY", buffer));
463
464         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_hour);
465         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_START_HOUR", buffer));
466
467         when.tv_sec = dstend;
468         ast_localtime(&when, &tm_info, zone);
469
470         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mon + 1);
471         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_END_MONTH", buffer));
472
473         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_mday);
474         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_END_MDAY", buffer));
475
476         snprintf(buffer, sizeof(buffer), "%d", tm_info.tm_hour);
477         AST_VAR_LIST_INSERT_TAIL(headp, ast_var_assign("DST_END_HOUR", buffer));
478 }
479
480 static struct http_route *unref_route(struct http_route *route)
481 {
482         ao2_cleanup(route);
483
484         return NULL;
485 }
486
487 static void route_destructor(void *obj)
488 {
489         struct http_route *route = obj;
490
491         ast_string_field_free_memory(route);
492 }
493
494 /*! \brief Delete all http routes, freeing their memory */
495 static void delete_routes(void)
496 {
497         if (!http_routes) {
498                 return;
499         }
500
501         ao2_callback(http_routes, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
502 }
503
504 /*! \brief Build a route structure and add it to the list of available http routes
505         \param pp_file File to link to the route
506         \param user User to link to the route (NULL means static route)
507         \param uri URI of the route
508 */
509 static void build_route(struct phoneprov_file *pp_file, struct phone_profile *profile, struct user *user, char *uri)
510 {
511         struct http_route *route;
512
513         if (!(route = ao2_alloc(sizeof(*route), route_destructor))) {
514                 return;
515         }
516
517         if (ast_string_field_init(route, 32)) {
518                 ast_log(LOG_ERROR, "Couldn't create string fields for %s\n", pp_file->format);
519                 route = unref_route(route);
520                 return;
521         }
522
523         ast_string_field_set(route, uri, S_OR(uri, pp_file->format));
524         route->user = user;
525         route->file = pp_file;
526         route->profile = profile;
527
528         ao2_link(http_routes, route);
529
530         route = unref_route(route);
531 }
532
533 static struct phone_profile *unref_profile(struct phone_profile *prof)
534 {
535         ao2_cleanup(prof);
536
537         return NULL;
538 }
539
540 /*! \brief Return a phone profile looked up by name */
541 static struct phone_profile *find_profile(const char *name)
542 {
543         return ao2_find(profiles, name, OBJ_SEARCH_KEY);
544 }
545
546 static void profile_destructor(void *obj)
547 {
548         struct phone_profile *profile = obj;
549         struct phoneprov_file *file;
550         struct ast_var_t *var;
551
552         while ((file = AST_LIST_REMOVE_HEAD(&profile->static_files, entry))) {
553                 delete_file(file);
554         }
555
556         while ((file = AST_LIST_REMOVE_HEAD(&profile->dynamic_files, entry))) {
557                 delete_file(file);
558         }
559
560         while ((var = AST_LIST_REMOVE_HEAD(profile->headp, entries))) {
561                 ast_var_delete(var);
562         }
563
564         ast_free(profile->headp);
565         ast_string_field_free_memory(profile);
566 }
567
568 /*! \brief Delete all phone profiles, freeing their memory */
569 static void delete_profiles(void)
570 {
571         if (!profiles) {
572                 return;
573         }
574
575         ao2_callback(profiles, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
576 }
577
578 /*! \brief Build a phone profile and add it to the list of phone profiles
579         \param name the name of the profile
580         \param v ast_variable from parsing phoneprov.conf
581 */
582 static void build_profile(const char *name, struct ast_variable *v)
583 {
584         struct phone_profile *profile;
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_var_list_create())) {
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                         char *value_copy = ast_strdupa(v->value);
609
610                         AST_DECLARE_APP_ARGS(args,
611                                 AST_APP_ARG(varname);
612                                 AST_APP_ARG(varval);
613                         );
614
615                         AST_NONSTANDARD_APP_ARGS(args, value_copy, '=');
616                         do {
617                                 if (ast_strlen_zero(args.varname) || ast_strlen_zero(args.varval))
618                                         break;
619                                 args.varname = ast_strip(args.varname);
620                                 args.varval = ast_strip(args.varval);
621                                 if (ast_strlen_zero(args.varname) || ast_strlen_zero(args.varval))
622                                         break;
623                                 AST_VAR_LIST_INSERT_TAIL(profile->headp, ast_var_assign(args.varname, args.varval));
624                         } while (0);
625                 } else if (!strcasecmp(v->name, "staticdir")) {
626                         ast_string_field_set(profile, staticdir, v->value);
627                 } else {
628                         struct phoneprov_file *pp_file;
629                         char *file_extension;
630                         char *value_copy = ast_strdupa(v->value);
631
632                         AST_DECLARE_APP_ARGS(args,
633                                 AST_APP_ARG(filename);
634                                 AST_APP_ARG(mimetype);
635                         );
636
637                         if (!(pp_file = ast_calloc_with_stringfields(1, struct phoneprov_file, 32))) {
638                                 profile = unref_profile(profile);
639                                 return;
640                         }
641
642                         if ((file_extension = strrchr(pp_file->format, '.')))
643                                 file_extension++;
644
645                         AST_STANDARD_APP_ARGS(args, value_copy);
646
647                         /* Mime type order of preference
648                          * 1) Specific mime-type defined for file in profile
649                          * 2) Mime determined by extension
650                          * 3) Default mime type specified in profile
651                          * 4) text/plain
652                          */
653                         ast_string_field_set(pp_file, mime_type, S_OR(args.mimetype,
654                                 (S_OR(S_OR(ast_http_ftype2mtype(file_extension), profile->default_mime_type), "text/plain"))));
655
656                         if (!strcasecmp(v->name, "static_file")) {
657                                 ast_string_field_set(pp_file, format, args.filename);
658                                 ast_string_field_build(pp_file, template, "%s%s", profile->staticdir, args.filename);
659                                 AST_LIST_INSERT_TAIL(&profile->static_files, pp_file, entry);
660                                 /* Add a route for the static files, as their filenames won't change per-user */
661                                 build_route(pp_file, profile, NULL, NULL);
662                         } else {
663                                 ast_string_field_set(pp_file, format, v->name);
664                                 ast_string_field_set(pp_file, template, args.filename);
665                                 AST_LIST_INSERT_TAIL(&profile->dynamic_files, pp_file, entry);
666                         }
667                 }
668         }
669
670         ao2_link(profiles, profile);
671
672         profile = unref_profile(profile);
673 }
674
675 static struct extension *delete_extension(struct extension *exten)
676 {
677         ast_var_list_destroy(exten->headp);
678         ast_string_field_free_memory(exten);
679         ast_free(exten);
680
681         return NULL;
682 }
683
684 static struct extension *build_extension(const char *name, struct varshead *vars)
685 {
686         struct extension *exten;
687         const char *tmp;
688
689         if (!(exten = ast_calloc_with_stringfields(1, struct extension, 32))) {
690                 return NULL;
691         }
692
693         ast_string_field_set(exten, name, name);
694
695         exten->headp = ast_var_list_clone(vars);
696         if (!exten->headp) {
697                 ast_log(LOG_ERROR, "Unable to clone variables for extension '%s'\n", name);
698                 delete_extension(exten);
699                 return NULL;
700         }
701
702         tmp = ast_var_find(exten->headp, variable_lookup[AST_PHONEPROV_STD_LINENUMBER]);
703         if (!tmp) {
704                 AST_VAR_LIST_INSERT_TAIL(exten->headp,
705                         ast_var_assign(variable_lookup[AST_PHONEPROV_STD_LINENUMBER], "1"));
706                 exten->index = 1;
707         } else {
708                 sscanf(tmp, "%d", &exten->index);
709         }
710
711         if (!ast_var_find(exten->headp, variable_lookup[AST_PHONEPROV_STD_LINEKEYS])) {
712                 AST_VAR_LIST_INSERT_TAIL(exten->headp,
713                         ast_var_assign(variable_lookup[AST_PHONEPROV_STD_LINEKEYS], "1"));
714         }
715
716         set_timezone_variables(exten->headp,
717                 ast_var_find(vars, variable_lookup[AST_PHONEPROV_STD_TIMEZONE]));
718
719         return exten;
720 }
721
722 static struct user *unref_user(struct user *user)
723 {
724         ao2_cleanup(user);
725
726         return NULL;
727 }
728
729 /*! \brief Return a user looked up by name */
730 static struct user *find_user(const char *macaddress)
731 {
732         return ao2_find(users, macaddress, OBJ_SEARCH_KEY);
733 }
734
735 static int routes_delete_cb(void *obj, void *arg, int flags)
736 {
737         struct http_route *route = obj;
738         struct user *user = route->user;
739         char *macaddress = arg;
740
741         if (user && !strcmp(user->macaddress, macaddress)) {
742                 return CMP_MATCH;
743         }
744         return 0;
745 }
746
747 /*! \brief Free all memory associated with a user */
748 static void user_destructor(void *obj)
749 {
750         struct user *user = obj;
751         struct extension *exten;
752
753         while ((exten = AST_LIST_REMOVE_HEAD(&user->extensions, entry))) {
754                 exten = delete_extension(exten);
755         }
756
757         if (user->profile) {
758                 user->profile = unref_profile(user->profile);
759         }
760
761         if (http_routes) {
762                 ao2_callback(http_routes, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, routes_delete_cb, (void *)user->macaddress);
763         }
764
765         ast_string_field_free_memory(user);
766 }
767
768 /*! \brief Delete all users */
769 static void delete_users(void)
770 {
771         if (!users) {
772                 return;
773         }
774
775         ao2_callback(users, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
776 }
777
778 /*! \brief Build and return a user structure based on gathered config data */
779 static struct user *build_user(const char *mac, struct phone_profile *profile, char *provider_name)
780 {
781         struct user *user;
782
783         if (!(user = ao2_alloc(sizeof(*user), user_destructor))) {
784                 return NULL;
785         }
786
787         if (ast_string_field_init(user, 64)) {
788                 user = unref_user(user);
789                 return NULL;
790         }
791
792         ast_string_field_set(user, macaddress, mac);
793         ast_string_field_set(user, provider_name, provider_name);
794         user->profile = profile;
795         ao2_ref(profile, 1);
796
797         return user;
798 }
799
800 /*! \brief Add an extension to a user ordered by index/linenumber */
801 static int add_user_extension(struct user *user, struct extension *exten)
802 {
803         struct ast_var_t *pvar, *var2;
804         struct ast_str *str = ast_str_create(16);
805
806         if (!str) {
807                 return -1;
808         }
809
810         /* Append profile variables here, and substitute variables on profile
811          * setvars, so that we can use user specific variables in them */
812         AST_VAR_LIST_TRAVERSE(user->profile->headp, pvar) {
813                 if (ast_var_find(exten->headp, pvar->name)) {
814                         continue;
815                 }
816
817                 ast_str_substitute_variables_varshead(&str, 0, exten->headp, pvar->value);
818                 if ((var2 = ast_var_assign(pvar->name, ast_str_buffer(str)))) {
819                         AST_VAR_LIST_INSERT_TAIL(exten->headp, var2);
820                 }
821         }
822         ast_free(str);
823
824         if (AST_LIST_EMPTY(&user->extensions)) {
825                 AST_LIST_INSERT_HEAD(&user->extensions, exten, entry);
826         } else {
827                 struct extension *exten_iter;
828
829                 AST_LIST_TRAVERSE_SAFE_BEGIN(&user->extensions, exten_iter, entry) {
830                         if (exten->index < exten_iter->index) {
831                                 AST_LIST_INSERT_BEFORE_CURRENT(exten, entry);
832                         } else if (exten->index == exten_iter->index) {
833                                 ast_log(LOG_WARNING, "Duplicate linenumber=%d for %s\n", exten->index, user->macaddress);
834                                 return -1;
835                         } else if (!AST_LIST_NEXT(exten_iter, entry)) {
836                                 AST_LIST_INSERT_TAIL(&user->extensions, exten, entry);
837                         }
838                 }
839                 AST_LIST_TRAVERSE_SAFE_END;
840         }
841
842         return 0;
843 }
844
845 /*! \brief Add an http route for dynamic files attached to the profile of the user */
846 static int build_user_routes(struct user *user)
847 {
848         struct phoneprov_file *pp_file;
849         struct ast_str *str;
850
851         if (!(str = ast_str_create(16))) {
852                 return -1;
853         }
854
855         AST_LIST_TRAVERSE(&user->profile->dynamic_files, pp_file, entry) {
856                 ast_str_substitute_variables_varshead(&str, 0, AST_LIST_FIRST(&user->extensions)->headp, pp_file->format);
857                 build_route(pp_file, user->profile, user, ast_str_buffer(str));
858         }
859
860         ast_free(str);
861         return 0;
862 }
863
864 /*! \brief Callback that is executed everytime an http request is received by this module */
865 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)
866 {
867         struct http_route *route;
868         struct ast_str *result;
869         char path[PATH_MAX];
870         char *file = NULL;
871         char *server;
872         int len;
873         int fd;
874         struct ast_str *http_header;
875
876         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
877                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
878                 return 0;
879         }
880
881         if (!(route = ao2_find(http_routes, uri, OBJ_SEARCH_KEY))) {
882                 goto out404;
883         }
884
885         snprintf(path, sizeof(path), "%s/phoneprov/%s", ast_config_AST_DATA_DIR, route->file->template);
886
887         if (!route->user) { /* Static file */
888
889                 fd = open(path, O_RDONLY);
890                 if (fd < 0) {
891                         goto out500;
892                 }
893
894                 len = lseek(fd, 0, SEEK_END);
895                 lseek(fd, 0, SEEK_SET);
896                 if (len < 0) {
897                         ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, len);
898                         close(fd);
899                         goto out500;
900                 }
901
902                 http_header = ast_str_create(80);
903                 ast_str_set(&http_header, 0, "Content-type: %s\r\n",
904                         route->file->mime_type);
905
906                 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 0);
907
908                 close(fd);
909                 route = unref_route(route);
910                 return 0;
911         } else { /* Dynamic file */
912                 struct ast_str *tmp;
913
914                 len = load_file(path, &file);
915                 if (len < 0) {
916                         ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, len);
917                         if (file) {
918                                 ast_free(file);
919                         }
920
921                         goto out500;
922                 }
923
924                 if (!file) {
925                         goto out500;
926                 }
927
928                 if (!(tmp = ast_str_create(len))) {
929                         if (file) {
930                                 ast_free(file);
931                         }
932
933                         goto out500;
934                 }
935
936                 /* Unless we are overridden by serveriface or serveraddr, we set the SERVER variable to
937                  * the IP address we are listening on that the phone contacted for this config file */
938
939                 server = ast_var_find(AST_LIST_FIRST(&route->user->extensions)->headp,
940                         variable_lookup[AST_PHONEPROV_STD_SERVER]);
941
942                 if (!server) {
943                         union {
944                                 struct sockaddr sa;
945                                 struct sockaddr_in sa_in;
946                         } name;
947                         socklen_t namelen = sizeof(name.sa);
948                         int res;
949
950                         if ((res = getsockname(ser->fd, &name.sa, &namelen))) {
951                                 ast_log(LOG_WARNING, "Could not get server IP, breakage likely.\n");
952                         } else {
953                                 struct extension *exten_iter;
954                                 const char *newserver = ast_inet_ntoa(name.sa_in.sin_addr);
955
956                                 AST_LIST_TRAVERSE(&route->user->extensions, exten_iter, entry) {
957                                         AST_VAR_LIST_INSERT_TAIL(exten_iter->headp,
958                                                 ast_var_assign(variable_lookup[AST_PHONEPROV_STD_SERVER], newserver));
959                                 }
960                         }
961                 }
962
963                 ast_str_substitute_variables_varshead(&tmp, 0, AST_LIST_FIRST(&route->user->extensions)->headp, file);
964
965                 ast_free(file);
966
967                 http_header = ast_str_create(80);
968                 ast_str_set(&http_header, 0, "Content-type: %s\r\n",
969                         route->file->mime_type);
970
971                 if (!(result = ast_str_create(512))) {
972                         ast_log(LOG_ERROR, "Could not create result string!\n");
973                         if (tmp) {
974                                 ast_free(tmp);
975                         }
976                         ast_free(http_header);
977                         goto out500;
978                 }
979                 ast_str_append(&result, 0, "%s", ast_str_buffer(tmp));
980
981                 ast_http_send(ser, method, 200, NULL, http_header, result, 0, 0);
982                 ast_free(tmp);
983
984                 route = unref_route(route);
985
986                 return 0;
987         }
988
989 out404:
990         ast_http_error(ser, 404, "Not Found", uri);
991         return 0;
992
993 out500:
994         route = unref_route(route);
995         ast_http_error(ser, 500, "Internal Error", "An internal error has occured.");
996         return 0;
997 }
998
999 /*! \brief A dialplan function that can be used to print a string for each phoneprov user */
1000 static int pp_each_user_helper(struct ast_channel *chan, char *data, char *buf, struct ast_str **bufstr, int len)
1001 {
1002         char *tmp;
1003         struct ao2_iterator i;
1004         struct user *user;
1005         struct ast_str *str;
1006         AST_DECLARE_APP_ARGS(args,
1007                 AST_APP_ARG(string);
1008                 AST_APP_ARG(exclude_mac);
1009         );
1010         AST_STANDARD_APP_ARGS(args, data);
1011
1012         if (!(str = ast_str_create(16))) {
1013                 return -1;
1014         }
1015
1016         /* Fix data by turning %{ into ${ */
1017         while ((tmp = strstr(args.string, "%{")))
1018                 *tmp = '$';
1019
1020         i = ao2_iterator_init(users, 0);
1021         while ((user = ao2_iterator_next(&i))) {
1022                 if (!ast_strlen_zero(args.exclude_mac) && !strcasecmp(user->macaddress, args.exclude_mac)) {
1023                         continue;
1024                 }
1025                 ast_str_substitute_variables_varshead(&str, len, AST_LIST_FIRST(&user->extensions)->headp, args.string);
1026                 if (buf) {
1027                         size_t slen = len;
1028                         ast_build_string(&buf, &slen, "%s", ast_str_buffer(str));
1029                 } else {
1030                         ast_str_append(bufstr, len, "%s", ast_str_buffer(str));
1031                 }
1032                 user = unref_user(user);
1033         }
1034         ao2_iterator_destroy(&i);
1035
1036         ast_free(str);
1037         return 0;
1038 }
1039
1040 static int pp_each_user_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1041 {
1042         return pp_each_user_helper(chan, data, buf, NULL, len);
1043 }
1044
1045 static int pp_each_user_read2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
1046 {
1047         return pp_each_user_helper(chan, data, NULL, buf, len);
1048 }
1049
1050 static struct ast_custom_function pp_each_user_function = {
1051         .name = "PP_EACH_USER",
1052         .read = pp_each_user_read,
1053         .read2 = pp_each_user_read2,
1054 };
1055
1056 /*! \brief A dialplan function that can be used to output a template for each extension attached to a user */
1057 static int pp_each_extension_helper(struct ast_channel *chan, const char *cmd, char *data, char *buf, struct ast_str **bufstr, int len)
1058 {
1059         struct user *user;
1060         struct extension *exten;
1061         char path[PATH_MAX];
1062         char *file;
1063         int filelen;
1064         struct ast_str *str;
1065         AST_DECLARE_APP_ARGS(args,
1066                 AST_APP_ARG(mac);
1067                 AST_APP_ARG(template);
1068         );
1069
1070         AST_STANDARD_APP_ARGS(args, data);
1071
1072         if (ast_strlen_zero(args.mac) || ast_strlen_zero(args.template)) {
1073                 ast_log(LOG_WARNING, "PP_EACH_EXTENSION requries both a macaddress and template filename.\n");
1074                 return 0;
1075         }
1076
1077         if (!(user = find_user(args.mac))) {
1078                 ast_log(LOG_WARNING, "Could not find user with mac = '%s'\n", args.mac);
1079                 return 0;
1080         }
1081
1082         snprintf(path, sizeof(path), "%s/phoneprov/%s", ast_config_AST_DATA_DIR, args.template);
1083         filelen = load_file(path, &file);
1084         if (filelen < 0) {
1085                 ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, filelen);
1086                 if (file) {
1087                         ast_free(file);
1088                 }
1089                 return 0;
1090         }
1091
1092         if (!file) {
1093                 return 0;
1094         }
1095
1096         if (!(str = ast_str_create(filelen))) {
1097                 return 0;
1098         }
1099
1100         AST_LIST_TRAVERSE(&user->extensions, exten, entry) {
1101                 ast_str_substitute_variables_varshead(&str, 0, exten->headp, file);
1102                 if (buf) {
1103                         size_t slen = len;
1104                         ast_build_string(&buf, &slen, "%s", ast_str_buffer(str));
1105                 } else {
1106                         ast_str_append(bufstr, len, "%s", ast_str_buffer(str));
1107                 }
1108         }
1109
1110         ast_free(file);
1111         ast_free(str);
1112
1113         user = unref_user(user);
1114
1115         return 0;
1116 }
1117
1118 static int pp_each_extension_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1119 {
1120         return pp_each_extension_helper(chan, cmd, data, buf, NULL, len);
1121 }
1122
1123 static int pp_each_extension_read2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
1124 {
1125         return pp_each_extension_helper(chan, cmd, data, NULL, buf, len);
1126 }
1127
1128 static struct ast_custom_function pp_each_extension_function = {
1129         .name = "PP_EACH_EXTENSION",
1130         .read = pp_each_extension_read,
1131         .read2 = pp_each_extension_read2,
1132 };
1133
1134 #define FORMATS "%-20.20s %-40.40s  %-30.30s\n"
1135 #define FORMATD "%-20.20s %-20.20s %-40.40s  %-30.30s\n"
1136 static int route_list_cb(void *obj, void *arg, void *data, int flags)
1137 {
1138         int fd = *(int *)arg;
1139         struct http_route *route = obj;
1140
1141         if (data && route->user) {
1142                 ast_cli(fd, FORMATD, route->user->provider_name, route->profile->name, route->uri, route->file->template);
1143         }
1144         if (!data && !route->user) {
1145                 ast_cli(fd, FORMATS, route->profile->name, route->uri, route->file->template);
1146         }
1147
1148         return CMP_MATCH;
1149 }
1150
1151 /*! \brief CLI command to list static and dynamic routes */
1152 static char *handle_show_routes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1153 {
1154         int fd = a->fd;
1155         switch(cmd) {
1156         case CLI_INIT:
1157                 e->command = "phoneprov show routes";
1158                 e->usage =
1159                         "Usage: phoneprov show routes\n"
1160                         "       Lists all registered phoneprov http routes.\n";
1161                 return NULL;
1162         case CLI_GENERATE:
1163                 return NULL;
1164         }
1165
1166         /* This currently iterates over routes twice, but it is the only place I've needed
1167          * to really separate static an dynamic routes, so I've just left it this way. */
1168         ast_cli(a->fd, "Static routes\n\n");
1169         ast_cli(a->fd, FORMATS, "Profile", "Relative URI", "Physical location");
1170
1171         ao2_callback_data(http_routes, OBJ_NODATA | OBJ_MULTIPLE, route_list_cb, &fd, NULL);
1172
1173         ast_cli(a->fd, "\nDynamic routes\n\n");
1174         ast_cli(a->fd, FORMATD, "Provider", "Profile", "Relative URI", "Template");
1175
1176         ao2_callback_data(http_routes, OBJ_NODATA | OBJ_MULTIPLE, route_list_cb, &fd, (void *)1);
1177
1178         return CLI_SUCCESS;
1179 }
1180
1181 static struct ast_cli_entry pp_cli[] = {
1182         AST_CLI_DEFINE(handle_show_routes, "Show registered phoneprov http routes"),
1183 };
1184
1185 static struct ast_http_uri phoneprovuri = {
1186         .callback = phoneprov_callback,
1187         .description = "Asterisk HTTP Phone Provisioning Tool",
1188         .uri = "phoneprov",
1189         .has_subtree = 1,
1190         .data = NULL,
1191         .key = __FILE__,
1192 };
1193
1194 static struct varshead *get_defaults(void)
1195 {
1196         struct ast_config *phoneprov_cfg;
1197         struct ast_config *cfg;
1198         const char *value;
1199         struct ast_variable *v;
1200         struct ast_var_t *var;
1201         struct ast_flags config_flags = { 0 };
1202         struct varshead *defaults = ast_var_list_create();
1203
1204         if (!defaults) {
1205                 ast_log(LOG_ERROR, "Unable to create default var list.\n");
1206                 return NULL;
1207         }
1208
1209         if (!(phoneprov_cfg = ast_config_load("phoneprov.conf", config_flags))
1210                 || phoneprov_cfg == CONFIG_STATUS_FILEINVALID) {
1211                 ast_log(LOG_ERROR, "Unable to load config phoneprov.conf\n");
1212                 ast_var_list_destroy(defaults);
1213                 return NULL;
1214         }
1215
1216         value = ast_variable_retrieve(phoneprov_cfg, "general", pp_general_lookup[AST_PHONEPROV_STD_SERVER]);
1217         if (!value) {
1218                 struct in_addr addr;
1219                 value = ast_variable_retrieve(phoneprov_cfg, "general", pp_general_lookup[AST_PHONEPROV_STD_SERVER_IFACE]);
1220                 if (value) {
1221                         lookup_iface(value, &addr);
1222                         value = ast_inet_ntoa(addr);
1223                 }
1224         }
1225         if (value) {
1226                 var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_SERVER], value);
1227                 AST_VAR_LIST_INSERT_TAIL(defaults, var);
1228         } else {
1229                 ast_log(LOG_WARNING, "Unable to find a valid server address or name.\n");
1230         }
1231
1232         value = ast_variable_retrieve(phoneprov_cfg, "general", pp_general_lookup[AST_PHONEPROV_STD_SERVER_PORT]);
1233         if (!value) {
1234                 if ((cfg = ast_config_load("sip.conf", config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1235                         value = ast_variable_retrieve(cfg, "general", "bindport");
1236                         ast_config_destroy(cfg);
1237                 }
1238         }
1239         var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_SERVER_PORT], S_OR(value, "5060"));
1240         AST_VAR_LIST_INSERT_TAIL(defaults, var);
1241
1242         value = ast_variable_retrieve(phoneprov_cfg, "general", pp_general_lookup[AST_PHONEPROV_STD_PROFILE]);
1243         if (!value) {
1244                 ast_log(LOG_ERROR, "Unable to load default profile.\n");
1245                 ast_config_destroy(phoneprov_cfg);
1246                 ast_var_list_destroy(defaults);
1247                 return NULL;
1248         }
1249         var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_PROFILE], value);
1250         AST_VAR_LIST_INSERT_TAIL(defaults, var);
1251         ast_config_destroy(phoneprov_cfg);
1252
1253         if (!(cfg = ast_config_load("users.conf", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
1254                 ast_log(LOG_ERROR, "Unable to load users.conf\n");
1255                 ast_var_list_destroy(defaults);
1256                 return NULL;
1257         }
1258
1259         /* Go ahead and load global variables from users.conf so we can append to profiles */
1260         for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
1261                 if (!strcasecmp(v->name, pp_user_lookup[AST_PHONEPROV_STD_VOICEMAIL_EXTEN])) {
1262                         var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_VOICEMAIL_EXTEN], v->value);
1263                         AST_VAR_LIST_INSERT_TAIL(defaults, var);
1264                 }
1265                 if (!strcasecmp(v->name, pp_user_lookup[AST_PHONEPROV_STD_EXTENSION_LENGTH])) {
1266                         var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_EXTENSION_LENGTH], v->value);
1267                         AST_VAR_LIST_INSERT_TAIL(defaults, var);
1268                 }
1269         }
1270         ast_config_destroy(cfg);
1271
1272         return defaults;
1273 }
1274
1275 static int load_users(void)
1276 {
1277         struct ast_config *cfg;
1278         char *cat;
1279         const char *value;
1280         struct ast_flags config_flags = { 0 };
1281         struct varshead *defaults = get_defaults();
1282
1283         if (!defaults) {
1284                 ast_log(LOG_WARNING, "Unable to load default variables.\n");
1285                 return -1;
1286         }
1287
1288         if (!(cfg = ast_config_load("users.conf", config_flags))
1289                 || cfg == CONFIG_STATUS_FILEINVALID) {
1290                 ast_log(LOG_WARNING, "Unable to load users.conf\n");
1291                 return -1;
1292         }
1293
1294         cat = NULL;
1295         while ((cat = ast_category_browse(cfg, cat))) {
1296                 const char *tmp;
1297                 int i;
1298                 struct ast_var_t *varx;
1299                 struct ast_var_t *vard;
1300
1301                 if (strcasecmp(cat, "general") && strcasecmp(cat, "authentication")) {
1302                         struct varshead *variables = ast_var_list_create();
1303
1304                         if (!((tmp = ast_variable_retrieve(cfg, cat, "autoprov")) && ast_true(tmp))) {
1305                                 ast_var_list_destroy(variables);
1306                                 continue;
1307                         }
1308
1309                         /* Transfer the standard variables */
1310                         for (i = 0; i < AST_PHONEPROV_STD_VAR_LIST_LENGTH; i++) {
1311                                 if (pp_user_lookup[i]) {
1312                                         value = ast_variable_retrieve(cfg, cat, pp_user_lookup[i]);
1313                                         if (value) {
1314                                                 varx = ast_var_assign(variable_lookup[i],
1315                                                         value);
1316                                                 AST_VAR_LIST_INSERT_TAIL(variables, varx);
1317                                         }
1318                                 }
1319                         }
1320
1321                         if (!ast_var_find(variables, variable_lookup[AST_PHONEPROV_STD_MAC])) {
1322                                 ast_log(LOG_WARNING, "autoprov set for %s, but no mac address - skipping.\n", cat);
1323                                 ast_var_list_destroy(variables);
1324                                 continue;
1325                         }
1326
1327                         /* Apply defaults */
1328                         AST_VAR_LIST_TRAVERSE(defaults, vard) {
1329                                 if (ast_var_find(variables, vard->name)) {
1330                                         continue;
1331                                 }
1332                                 varx = ast_var_assign(vard->name, vard->value);
1333                                 AST_VAR_LIST_INSERT_TAIL(variables, varx);
1334                         }
1335
1336                         ast_phoneprov_add_extension(SIPUSERS_PROVIDER_NAME, variables);
1337                 }
1338         }
1339         ast_config_destroy(cfg);
1340         return 0;
1341 }
1342
1343 static int load_common(void)
1344 {
1345         struct ast_config *phoneprov_cfg;
1346         struct ast_flags config_flags = { 0 };
1347         char *cat;
1348
1349         if (!(phoneprov_cfg = ast_config_load("phoneprov.conf", config_flags))
1350                 || phoneprov_cfg == CONFIG_STATUS_FILEINVALID) {
1351                 ast_log(LOG_ERROR, "Unable to load config phoneprov.conf\n");
1352                 return -1;
1353         }
1354
1355         cat = NULL;
1356         while ((cat = ast_category_browse(phoneprov_cfg, cat))) {
1357                 if (!strcasecmp(cat, "general")) {
1358                         continue;
1359                 }
1360                 build_profile(cat, ast_variable_browse(phoneprov_cfg, cat));
1361         }
1362         ast_config_destroy(phoneprov_cfg);
1363
1364         if (!ao2_container_count(profiles)) {
1365                 ast_log(LOG_ERROR, "There are no provisioning profiles in phoneprov.conf.\n");
1366                 return -1;
1367         }
1368
1369         return 0;
1370 }
1371
1372 static int unload_module(void)
1373 {
1374         ast_http_uri_unlink(&phoneprovuri);
1375         ast_custom_function_unregister(&pp_each_user_function);
1376         ast_custom_function_unregister(&pp_each_extension_function);
1377         ast_cli_unregister_multiple(pp_cli, ARRAY_LEN(pp_cli));
1378
1379         /* This cleans up the sip.conf/users.conf provider (called specifically for clarity) */
1380         ast_phoneprov_provider_unregister(SIPUSERS_PROVIDER_NAME);
1381
1382         /* This cleans up the framework which also cleans up the providers. */
1383         delete_profiles();
1384         ao2_cleanup(profiles);
1385         profiles = NULL;
1386         delete_routes();
1387         delete_users();
1388         ao2_cleanup(http_routes);
1389         http_routes = NULL;
1390         ao2_cleanup(users);
1391         users = NULL;
1392         delete_providers();
1393         ao2_cleanup(providers);
1394         providers = NULL;
1395
1396         return 0;
1397 }
1398
1399 /*!
1400  * \brief Load the module
1401  *
1402  * Module loading including tests for configuration or dependencies.
1403  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1404  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1405  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1406  * configuration file or other non-critical problem return
1407  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1408  */
1409 static int load_module(void)
1410 {
1411         profiles = ao2_container_alloc(MAX_PROFILE_BUCKETS, phone_profile_hash_fn, phone_profile_cmp_fn);
1412         if (!profiles) {
1413                 ast_log(LOG_ERROR, "Unable to allocate profiles container.\n");
1414                 return AST_MODULE_LOAD_DECLINE;
1415         }
1416
1417         http_routes = ao2_container_alloc(MAX_ROUTE_BUCKETS, http_route_hash_fn, http_route_cmp_fn);
1418         if (!http_routes) {
1419                 ast_log(LOG_ERROR, "Unable to allocate routes container.\n");
1420                 goto error;
1421         }
1422
1423         if (load_common()) {
1424                 ast_log(LOG_ERROR, "Unable to load provisioning profiles.\n");
1425                 goto error;
1426         }
1427
1428         users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_fn, user_cmp_fn);
1429         if (!users) {
1430                 ast_log(LOG_ERROR, "Unable to allocate users container.\n");
1431                 goto error;
1432         }
1433
1434         providers = ao2_container_alloc(MAX_PROVIDER_BUCKETS, phoneprov_provider_hash_fn, phoneprov_provider_cmp_fn);
1435         if (!providers) {
1436                 ast_log(LOG_ERROR, "Unable to allocate providers container.\n");
1437                 goto error;
1438         }
1439
1440         /* Register ourselves as the provider for sip.conf/users.conf */
1441         if (ast_phoneprov_provider_register(SIPUSERS_PROVIDER_NAME, load_users)) {
1442                 ast_log(LOG_WARNING, "Unable register sip/users config provider.  Others may succeed.\n");
1443         }
1444
1445         ast_http_uri_link(&phoneprovuri);
1446
1447         ast_custom_function_register(&pp_each_user_function);
1448         ast_custom_function_register(&pp_each_extension_function);
1449         ast_cli_register_multiple(pp_cli, ARRAY_LEN(pp_cli));
1450
1451         return AST_MODULE_LOAD_SUCCESS;
1452
1453 error:
1454         unload_module();
1455         return AST_MODULE_LOAD_DECLINE;
1456 }
1457
1458 static int reload(void)
1459 {
1460         struct ao2_iterator i;
1461         struct phoneprov_provider *provider;
1462
1463         /* Clean everything except the providers */
1464         delete_routes();
1465         delete_users();
1466         delete_profiles();
1467
1468         /* Reload the profiles */
1469         if (load_common()) {
1470                 ast_log(LOG_ERROR, "Unable to reload provisioning profiles.\n");
1471                 unload_module();
1472                 return AST_MODULE_LOAD_DECLINE;
1473         }
1474
1475         /* For each provider, reload the users */
1476         ao2_lock(providers);
1477         i = ao2_iterator_init(providers, 0);
1478         for(; (provider = ao2_iterator_next(&i)); ao2_ref(provider, -1)) {
1479                 ast_log(LOG_VERBOSE, "Reloading provider '%s' users.\n", provider->provider_name);
1480                 if (provider->load_users()) {
1481                         ast_log(LOG_ERROR, "Unable to load provider '%s' users. Reload aborted.\n", provider->provider_name);
1482                         continue;
1483                 }
1484         }
1485         ao2_iterator_destroy(&i);
1486         ao2_unlock(providers);
1487
1488         return AST_MODULE_LOAD_SUCCESS;
1489 }
1490
1491 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "HTTP Phone Provisioning",
1492                 .support_level = AST_MODULE_SUPPORT_EXTENDED,
1493                 .load = load_module,
1494                 .unload = unload_module,
1495                 .reload = reload,
1496                 .load_pri = AST_MODPRI_CHANNEL_DEPEND,
1497         );
1498
1499 /****  Public API for register/unregister, set defaults, and add extension. ****/
1500
1501 const char *ast_phoneprov_std_variable_lookup(enum ast_phoneprov_std_variables var)
1502 {
1503         if (var >= AST_PHONEPROV_STD_VAR_LIST_LENGTH) {
1504                 return NULL;
1505         }
1506
1507         return variable_lookup[var];
1508 }
1509
1510 int ast_phoneprov_provider_register(char *provider_name,
1511         ast_phoneprov_load_users_cb load_users)
1512 {
1513         struct phoneprov_provider *provider;
1514
1515         if (ast_strlen_zero(provider_name)) {
1516                 ast_log(LOG_ERROR, "Provider name can't be empty.\n");
1517                 return -1;
1518         }
1519
1520         if (!providers) {
1521                 ast_log(LOG_WARNING, "Provider '%s' cannot be registered: res_phoneprov not loaded.\n", provider_name);
1522                 return -1;
1523         }
1524
1525         provider = find_provider(provider_name);
1526         if (provider) {
1527                 ast_log(LOG_ERROR, "There is already a provider registered named '%s'.\n", provider_name);
1528                 ao2_ref(provider, -1);
1529                 return -1;
1530         }
1531
1532         provider = ao2_alloc(sizeof(struct phoneprov_provider), provider_destructor);
1533         if (!provider) {
1534                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory for provider '%s'.\n", provider_name);
1535                 return -1;
1536         }
1537
1538         if (ast_string_field_init(provider, 32)) {
1539                 ao2_ref(provider, -1);
1540                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory for provider '%s' stringfields.\n", provider_name);
1541                 return -1;
1542         }
1543
1544         ast_string_field_set(provider, provider_name, provider_name);
1545         provider->load_users = load_users;
1546
1547         ao2_link(providers, provider);
1548         ao2_ref(provider, -1);
1549
1550         if (provider->load_users()) {
1551                 ast_log(LOG_ERROR, "Unable to load provider '%s' users. Register aborted.\n", provider_name);
1552                 ast_phoneprov_provider_unregister(provider_name);
1553                 return -1;
1554         }
1555
1556         ast_log(LOG_VERBOSE, "Registered phoneprov provider '%s'.\n", provider_name);
1557         return 0;
1558 }
1559
1560 static int extensions_delete_cb(void *obj, void *arg, int flags)
1561 {
1562         char *provider_name = arg;
1563         struct user *user = obj;
1564         if (strcmp(user->provider_name, provider_name)) {
1565                 return 0;
1566         }
1567         return CMP_MATCH;
1568 }
1569
1570 static int extension_delete_cb(void *obj, void *arg, void *data, int flags)
1571 {
1572         struct user *user = obj;
1573         char *provider_name = data;
1574         char *macaddress = arg;
1575
1576         if (!strcmp(user->provider_name, provider_name) && !strcasecmp(user->macaddress, macaddress)) {
1577                 return CMP_MATCH;
1578         }
1579         return 0;
1580 }
1581
1582 void ast_phoneprov_delete_extension(char *provider_name, char *macaddress)
1583 {
1584         ao2_callback_data(users, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
1585                 extension_delete_cb, macaddress, provider_name);
1586 }
1587
1588 void ast_phoneprov_delete_extensions(char *provider_name)
1589 {
1590         ao2_callback(users, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, extensions_delete_cb, provider_name);
1591 }
1592
1593 void ast_phoneprov_provider_unregister(char *provider_name)
1594 {
1595         if (!providers) {
1596                 return;
1597         }
1598
1599         ast_phoneprov_delete_extensions(provider_name);
1600         ao2_find(providers, provider_name, OBJ_SEARCH_KEY | OBJ_NODATA | OBJ_UNLINK);
1601         ast_log(LOG_VERBOSE, "Unegistered phoneprov provider '%s'.\n", provider_name);
1602 }
1603
1604 int ast_phoneprov_add_extension(char *provider_name, struct varshead *vars)
1605 {
1606         RAII_VAR(struct phoneprov_provider *, provider, NULL, ao2_cleanup);
1607         RAII_VAR(struct user *, user, NULL, ao2_cleanup);
1608         RAII_VAR(struct phone_profile *, profile, NULL, ao2_cleanup);
1609         struct extension *exten;
1610         char *profile_name;
1611         char *mac;
1612         char *username;
1613
1614         if (ast_strlen_zero(provider_name)) {
1615                 ast_log(LOG_ERROR, "Provider name can't be empty.\n");
1616                 return -1;
1617         }
1618         if (!vars) {
1619                 ast_log(LOG_ERROR, "Variable list can't be empty.\n");
1620                 return -1;
1621         }
1622
1623         username = ast_var_find(vars, variable_lookup[AST_PHONEPROV_STD_USERNAME]);
1624         if (!username) {
1625                 ast_log(LOG_ERROR, "Extension name can't be empty.\n");
1626                 return -1;
1627         }
1628
1629         mac = ast_var_find(vars, variable_lookup[AST_PHONEPROV_STD_MAC]);
1630         if (!mac) {
1631                 ast_log(LOG_ERROR, "MAC Address can't be empty.\n");
1632                 return -1;
1633         }
1634
1635         provider = find_provider(provider_name);
1636         if (!provider) {
1637                 ast_log(LOG_ERROR, "Provider '%s' wasn't found in the registry.\n", provider_name);
1638                 return -1;
1639         }
1640
1641         profile_name = ast_var_find(vars,
1642                 variable_lookup[AST_PHONEPROV_STD_PROFILE]);
1643         if (!profile_name) {
1644                 ast_log(LOG_ERROR, "No profile could be found for user '%s' - skipping.\n", username);
1645                 return -1;
1646         }
1647         if (!(profile = find_profile(profile_name))) {
1648                 ast_log(LOG_ERROR, "Could not look up profile '%s' - skipping.\n", profile_name);
1649                 return -1;
1650         }
1651
1652         if (!(user = find_user(mac))) {
1653
1654                 if (!(user = build_user(mac, profile, provider_name))) {
1655                         ast_log(LOG_ERROR, "Could not create user for '%s' - skipping\n", mac);
1656                         return -1;
1657                 }
1658
1659                 if (!(exten = build_extension(username, vars))) {
1660                         ast_log(LOG_ERROR, "Could not create extension for '%s' - skipping\n", user->macaddress);
1661                         return -1;
1662                 }
1663
1664                 if (add_user_extension(user, exten)) {
1665                         ast_log(LOG_WARNING, "Could not add extension '%s' to user '%s'\n", exten->name, user->macaddress);
1666                         exten = delete_extension(exten);
1667                         return -1;
1668                 }
1669
1670                 if (build_user_routes(user)) {
1671                         ast_log(LOG_WARNING, "Could not create http routes for '%s' - skipping\n", user->macaddress);
1672                         return -1;
1673                 }
1674                 ast_log(LOG_VERBOSE, "Created %s/%s for provider '%s'.\n", username, mac, provider_name);
1675                 ao2_link(users, user);
1676
1677         } else {
1678                 if (strcmp(provider_name, user->provider_name)) {
1679                         ast_log(LOG_ERROR, "MAC address '%s' was already added by provider '%s' - skipping\n", user->macaddress, user->provider_name);
1680                         return -1;
1681                 }
1682
1683                 if (!(exten = build_extension(username, vars))) {
1684                         ast_log(LOG_ERROR, "Could not create extension for '%s' - skipping\n", user->macaddress);
1685                         return -1;
1686                 }
1687
1688                 if (add_user_extension(user, exten)) {
1689                         ast_log(LOG_WARNING, "Could not add extension '%s' to user '%s'\n", exten->name, user->macaddress);
1690                         exten = delete_extension(exten);
1691                         return -1;
1692                 }
1693                 ast_log(LOG_VERBOSE, "Added %s/%s for provider '%s'.\n", username, mac, provider_name);
1694         }
1695
1696         return 0;
1697 }