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