78511cccf9848eb218d118093c7b7d0538852cfe
[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         ao2_callback(http_routes, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, routes_delete_cb, (void *)user->macaddress);
762
763         ast_string_field_free_memory(user);
764 }
765
766 /*! \brief Delete all users */
767 static void delete_users(void)
768 {
769         if (!users) {
770                 return;
771         }
772
773         ao2_callback(users, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
774 }
775
776 /*! \brief Build and return a user structure based on gathered config data */
777 static struct user *build_user(const char *mac, struct phone_profile *profile, char *provider_name)
778 {
779         struct user *user;
780
781         if (!(user = ao2_alloc(sizeof(*user), user_destructor))) {
782                 return NULL;
783         }
784
785         if (ast_string_field_init(user, 64)) {
786                 user = unref_user(user);
787                 return NULL;
788         }
789
790         ast_string_field_set(user, macaddress, mac);
791         ast_string_field_set(user, provider_name, provider_name);
792         user->profile = profile;
793         ao2_ref(profile, 1);
794
795         return user;
796 }
797
798 /*! \brief Add an extension to a user ordered by index/linenumber */
799 static int add_user_extension(struct user *user, struct extension *exten)
800 {
801         struct ast_var_t *pvar, *var2;
802         struct ast_str *str = ast_str_create(16);
803
804         if (!str) {
805                 return -1;
806         }
807
808         /* Append profile variables here, and substitute variables on profile
809          * setvars, so that we can use user specific variables in them */
810         AST_VAR_LIST_TRAVERSE(user->profile->headp, pvar) {
811                 if (ast_var_find(exten->headp, pvar->name)) {
812                         continue;
813                 }
814
815                 ast_str_substitute_variables_varshead(&str, 0, exten->headp, pvar->value);
816                 if ((var2 = ast_var_assign(pvar->name, ast_str_buffer(str)))) {
817                         AST_VAR_LIST_INSERT_TAIL(exten->headp, var2);
818                 }
819         }
820         ast_free(str);
821
822         if (AST_LIST_EMPTY(&user->extensions)) {
823                 AST_LIST_INSERT_HEAD(&user->extensions, exten, entry);
824         } else {
825                 struct extension *exten_iter;
826
827                 AST_LIST_TRAVERSE_SAFE_BEGIN(&user->extensions, exten_iter, entry) {
828                         if (exten->index < exten_iter->index) {
829                                 AST_LIST_INSERT_BEFORE_CURRENT(exten, entry);
830                         } else if (exten->index == exten_iter->index) {
831                                 ast_log(LOG_WARNING, "Duplicate linenumber=%d for %s\n", exten->index, user->macaddress);
832                                 return -1;
833                         } else if (!AST_LIST_NEXT(exten_iter, entry)) {
834                                 AST_LIST_INSERT_TAIL(&user->extensions, exten, entry);
835                         }
836                 }
837                 AST_LIST_TRAVERSE_SAFE_END;
838         }
839
840         return 0;
841 }
842
843 /*! \brief Add an http route for dynamic files attached to the profile of the user */
844 static int build_user_routes(struct user *user)
845 {
846         struct phoneprov_file *pp_file;
847         struct ast_str *str;
848
849         if (!(str = ast_str_create(16))) {
850                 return -1;
851         }
852
853         AST_LIST_TRAVERSE(&user->profile->dynamic_files, pp_file, entry) {
854                 ast_str_substitute_variables_varshead(&str, 0, AST_LIST_FIRST(&user->extensions)->headp, pp_file->format);
855                 build_route(pp_file, user->profile, user, ast_str_buffer(str));
856         }
857
858         ast_free(str);
859         return 0;
860 }
861
862 /*! \brief Callback that is executed everytime an http request is received by this module */
863 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)
864 {
865         struct http_route *route;
866         struct ast_str *result;
867         char path[PATH_MAX];
868         char *file = NULL;
869         char *server;
870         int len;
871         int fd;
872         struct ast_str *http_header;
873
874         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
875                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
876                 return 0;
877         }
878
879         if (!(route = ao2_find(http_routes, uri, OBJ_SEARCH_KEY))) {
880                 goto out404;
881         }
882
883         snprintf(path, sizeof(path), "%s/phoneprov/%s", ast_config_AST_DATA_DIR, route->file->template);
884
885         if (!route->user) { /* Static file */
886
887                 fd = open(path, O_RDONLY);
888                 if (fd < 0) {
889                         goto out500;
890                 }
891
892                 len = lseek(fd, 0, SEEK_END);
893                 lseek(fd, 0, SEEK_SET);
894                 if (len < 0) {
895                         ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, len);
896                         close(fd);
897                         goto out500;
898                 }
899
900                 http_header = ast_str_create(80);
901                 ast_str_set(&http_header, 0, "Content-type: %s\r\n",
902                         route->file->mime_type);
903
904                 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 0);
905
906                 close(fd);
907                 route = unref_route(route);
908                 return 0;
909         } else { /* Dynamic file */
910                 struct ast_str *tmp;
911
912                 len = load_file(path, &file);
913                 if (len < 0) {
914                         ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, len);
915                         if (file) {
916                                 ast_free(file);
917                         }
918
919                         goto out500;
920                 }
921
922                 if (!file) {
923                         goto out500;
924                 }
925
926                 if (!(tmp = ast_str_create(len))) {
927                         if (file) {
928                                 ast_free(file);
929                         }
930
931                         goto out500;
932                 }
933
934                 /* Unless we are overridden by serveriface or serveraddr, we set the SERVER variable to
935                  * the IP address we are listening on that the phone contacted for this config file */
936
937                 server = ast_var_find(AST_LIST_FIRST(&route->user->extensions)->headp,
938                         variable_lookup[AST_PHONEPROV_STD_SERVER]);
939
940                 if (!server) {
941                         union {
942                                 struct sockaddr sa;
943                                 struct sockaddr_in sa_in;
944                         } name;
945                         socklen_t namelen = sizeof(name.sa);
946                         int res;
947
948                         if ((res = getsockname(ser->fd, &name.sa, &namelen))) {
949                                 ast_log(LOG_WARNING, "Could not get server IP, breakage likely.\n");
950                         } else {
951                                 struct extension *exten_iter;
952                                 const char *newserver = ast_inet_ntoa(name.sa_in.sin_addr);
953
954                                 AST_LIST_TRAVERSE(&route->user->extensions, exten_iter, entry) {
955                                         AST_VAR_LIST_INSERT_TAIL(exten_iter->headp,
956                                                 ast_var_assign(variable_lookup[AST_PHONEPROV_STD_SERVER], newserver));
957                                 }
958                         }
959                 }
960
961                 ast_str_substitute_variables_varshead(&tmp, 0, AST_LIST_FIRST(&route->user->extensions)->headp, file);
962
963                 ast_free(file);
964
965                 http_header = ast_str_create(80);
966                 ast_str_set(&http_header, 0, "Content-type: %s\r\n",
967                         route->file->mime_type);
968
969                 if (!(result = ast_str_create(512))) {
970                         ast_log(LOG_ERROR, "Could not create result string!\n");
971                         if (tmp) {
972                                 ast_free(tmp);
973                         }
974                         ast_free(http_header);
975                         goto out500;
976                 }
977                 ast_str_append(&result, 0, "%s", ast_str_buffer(tmp));
978
979                 ast_http_send(ser, method, 200, NULL, http_header, result, 0, 0);
980                 ast_free(tmp);
981
982                 route = unref_route(route);
983
984                 return 0;
985         }
986
987 out404:
988         ast_http_error(ser, 404, "Not Found", uri);
989         return 0;
990
991 out500:
992         route = unref_route(route);
993         ast_http_error(ser, 500, "Internal Error", "An internal error has occured.");
994         return 0;
995 }
996
997 /*! \brief A dialplan function that can be used to print a string for each phoneprov user */
998 static int pp_each_user_helper(struct ast_channel *chan, char *data, char *buf, struct ast_str **bufstr, int len)
999 {
1000         char *tmp;
1001         struct ao2_iterator i;
1002         struct user *user;
1003         struct ast_str *str;
1004         AST_DECLARE_APP_ARGS(args,
1005                 AST_APP_ARG(string);
1006                 AST_APP_ARG(exclude_mac);
1007         );
1008         AST_STANDARD_APP_ARGS(args, data);
1009
1010         if (!(str = ast_str_create(16))) {
1011                 return -1;
1012         }
1013
1014         /* Fix data by turning %{ into ${ */
1015         while ((tmp = strstr(args.string, "%{")))
1016                 *tmp = '$';
1017
1018         i = ao2_iterator_init(users, 0);
1019         while ((user = ao2_iterator_next(&i))) {
1020                 if (!ast_strlen_zero(args.exclude_mac) && !strcasecmp(user->macaddress, args.exclude_mac)) {
1021                         continue;
1022                 }
1023                 ast_str_substitute_variables_varshead(&str, len, AST_LIST_FIRST(&user->extensions)->headp, args.string);
1024                 if (buf) {
1025                         size_t slen = len;
1026                         ast_build_string(&buf, &slen, "%s", ast_str_buffer(str));
1027                 } else {
1028                         ast_str_append(bufstr, len, "%s", ast_str_buffer(str));
1029                 }
1030                 user = unref_user(user);
1031         }
1032         ao2_iterator_destroy(&i);
1033
1034         ast_free(str);
1035         return 0;
1036 }
1037
1038 static int pp_each_user_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1039 {
1040         return pp_each_user_helper(chan, data, buf, NULL, len);
1041 }
1042
1043 static int pp_each_user_read2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
1044 {
1045         return pp_each_user_helper(chan, data, NULL, buf, len);
1046 }
1047
1048 static struct ast_custom_function pp_each_user_function = {
1049         .name = "PP_EACH_USER",
1050         .read = pp_each_user_read,
1051         .read2 = pp_each_user_read2,
1052 };
1053
1054 /*! \brief A dialplan function that can be used to output a template for each extension attached to a user */
1055 static int pp_each_extension_helper(struct ast_channel *chan, const char *cmd, char *data, char *buf, struct ast_str **bufstr, int len)
1056 {
1057         struct user *user;
1058         struct extension *exten;
1059         char path[PATH_MAX];
1060         char *file;
1061         int filelen;
1062         struct ast_str *str;
1063         AST_DECLARE_APP_ARGS(args,
1064                 AST_APP_ARG(mac);
1065                 AST_APP_ARG(template);
1066         );
1067
1068         AST_STANDARD_APP_ARGS(args, data);
1069
1070         if (ast_strlen_zero(args.mac) || ast_strlen_zero(args.template)) {
1071                 ast_log(LOG_WARNING, "PP_EACH_EXTENSION requries both a macaddress and template filename.\n");
1072                 return 0;
1073         }
1074
1075         if (!(user = find_user(args.mac))) {
1076                 ast_log(LOG_WARNING, "Could not find user with mac = '%s'\n", args.mac);
1077                 return 0;
1078         }
1079
1080         snprintf(path, sizeof(path), "%s/phoneprov/%s", ast_config_AST_DATA_DIR, args.template);
1081         filelen = load_file(path, &file);
1082         if (filelen < 0) {
1083                 ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, filelen);
1084                 if (file) {
1085                         ast_free(file);
1086                 }
1087                 return 0;
1088         }
1089
1090         if (!file) {
1091                 return 0;
1092         }
1093
1094         if (!(str = ast_str_create(filelen))) {
1095                 return 0;
1096         }
1097
1098         AST_LIST_TRAVERSE(&user->extensions, exten, entry) {
1099                 ast_str_substitute_variables_varshead(&str, 0, exten->headp, file);
1100                 if (buf) {
1101                         size_t slen = len;
1102                         ast_build_string(&buf, &slen, "%s", ast_str_buffer(str));
1103                 } else {
1104                         ast_str_append(bufstr, len, "%s", ast_str_buffer(str));
1105                 }
1106         }
1107
1108         ast_free(file);
1109         ast_free(str);
1110
1111         user = unref_user(user);
1112
1113         return 0;
1114 }
1115
1116 static int pp_each_extension_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1117 {
1118         return pp_each_extension_helper(chan, cmd, data, buf, NULL, len);
1119 }
1120
1121 static int pp_each_extension_read2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
1122 {
1123         return pp_each_extension_helper(chan, cmd, data, NULL, buf, len);
1124 }
1125
1126 static struct ast_custom_function pp_each_extension_function = {
1127         .name = "PP_EACH_EXTENSION",
1128         .read = pp_each_extension_read,
1129         .read2 = pp_each_extension_read2,
1130 };
1131
1132 #define FORMATS "%-20.20s %-40.40s  %-30.30s\n"
1133 #define FORMATD "%-20.20s %-20.20s %-40.40s  %-30.30s\n"
1134 static int route_list_cb(void *obj, void *arg, void *data, int flags)
1135 {
1136         int fd = *(int *)arg;
1137         struct http_route *route = obj;
1138
1139         if (data && route->user) {
1140                 ast_cli(fd, FORMATD, route->user->provider_name, route->profile->name, route->uri, route->file->template);
1141         }
1142         if (!data && !route->user) {
1143                 ast_cli(fd, FORMATS, route->profile->name, route->uri, route->file->template);
1144         }
1145
1146         return CMP_MATCH;
1147 }
1148
1149 /*! \brief CLI command to list static and dynamic routes */
1150 static char *handle_show_routes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1151 {
1152         int fd = a->fd;
1153         switch(cmd) {
1154         case CLI_INIT:
1155                 e->command = "phoneprov show routes";
1156                 e->usage =
1157                         "Usage: phoneprov show routes\n"
1158                         "       Lists all registered phoneprov http routes.\n";
1159                 return NULL;
1160         case CLI_GENERATE:
1161                 return NULL;
1162         }
1163
1164         /* This currently iterates over routes twice, but it is the only place I've needed
1165          * to really separate static an dynamic routes, so I've just left it this way. */
1166         ast_cli(a->fd, "Static routes\n\n");
1167         ast_cli(a->fd, FORMATS, "Profile", "Relative URI", "Physical location");
1168
1169         ao2_callback_data(http_routes, OBJ_NODATA | OBJ_MULTIPLE, route_list_cb, &fd, NULL);
1170
1171         ast_cli(a->fd, "\nDynamic routes\n\n");
1172         ast_cli(a->fd, FORMATD, "Provider", "Profile", "Relative URI", "Template");
1173
1174         ao2_callback_data(http_routes, OBJ_NODATA | OBJ_MULTIPLE, route_list_cb, &fd, (void *)1);
1175
1176         return CLI_SUCCESS;
1177 }
1178
1179 static struct ast_cli_entry pp_cli[] = {
1180         AST_CLI_DEFINE(handle_show_routes, "Show registered phoneprov http routes"),
1181 };
1182
1183 static struct ast_http_uri phoneprovuri = {
1184         .callback = phoneprov_callback,
1185         .description = "Asterisk HTTP Phone Provisioning Tool",
1186         .uri = "phoneprov",
1187         .has_subtree = 1,
1188         .data = NULL,
1189         .key = __FILE__,
1190 };
1191
1192 static struct varshead *get_defaults(void)
1193 {
1194         struct ast_config *phoneprov_cfg;
1195         struct ast_config *cfg;
1196         const char *value;
1197         struct ast_variable *v;
1198         struct ast_var_t *var;
1199         struct ast_flags config_flags = { 0 };
1200         struct varshead *defaults = ast_var_list_create();
1201
1202         if (!defaults) {
1203                 ast_log(LOG_ERROR, "Unable to create default var list.\n");
1204                 return NULL;
1205         }
1206
1207         if (!(phoneprov_cfg = ast_config_load("phoneprov.conf", config_flags))
1208                 || phoneprov_cfg == CONFIG_STATUS_FILEINVALID) {
1209                 ast_log(LOG_ERROR, "Unable to load config phoneprov.conf\n");
1210                 ast_var_list_destroy(defaults);
1211                 return NULL;
1212         }
1213
1214         value = ast_variable_retrieve(phoneprov_cfg, "general", pp_general_lookup[AST_PHONEPROV_STD_SERVER]);
1215         if (!value) {
1216                 struct in_addr addr;
1217                 value = ast_variable_retrieve(phoneprov_cfg, "general", pp_general_lookup[AST_PHONEPROV_STD_SERVER_IFACE]);
1218                 if (value) {
1219                         lookup_iface(value, &addr);
1220                         value = ast_inet_ntoa(addr);
1221                 }
1222         }
1223         if (value) {
1224                 var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_SERVER], value);
1225                 AST_VAR_LIST_INSERT_TAIL(defaults, var);
1226         } else {
1227                 ast_log(LOG_WARNING, "Unable to find a valid server address or name.\n");
1228         }
1229
1230         value = ast_variable_retrieve(phoneprov_cfg, "general", pp_general_lookup[AST_PHONEPROV_STD_SERVER_PORT]);
1231         if (!value) {
1232                 if ((cfg = ast_config_load("sip.conf", config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1233                         value = ast_variable_retrieve(cfg, "general", "bindport");
1234                         ast_config_destroy(cfg);
1235                 }
1236         }
1237         var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_SERVER_PORT], S_OR(value, "5060"));
1238         AST_VAR_LIST_INSERT_TAIL(defaults, var);
1239
1240         value = ast_variable_retrieve(phoneprov_cfg, "general", pp_general_lookup[AST_PHONEPROV_STD_PROFILE]);
1241         if (!value) {
1242                 ast_log(LOG_ERROR, "Unable to load default profile.\n");
1243                 ast_config_destroy(phoneprov_cfg);
1244                 ast_var_list_destroy(defaults);
1245                 return NULL;
1246         }
1247         var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_PROFILE], value);
1248         AST_VAR_LIST_INSERT_TAIL(defaults, var);
1249         ast_config_destroy(phoneprov_cfg);
1250
1251         if (!(cfg = ast_config_load("users.conf", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
1252                 ast_log(LOG_ERROR, "Unable to load users.conf\n");
1253                 ast_var_list_destroy(defaults);
1254                 return NULL;
1255         }
1256
1257         /* Go ahead and load global variables from users.conf so we can append to profiles */
1258         for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
1259                 if (!strcasecmp(v->name, pp_user_lookup[AST_PHONEPROV_STD_VOICEMAIL_EXTEN])) {
1260                         var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_VOICEMAIL_EXTEN], v->value);
1261                         AST_VAR_LIST_INSERT_TAIL(defaults, var);
1262                 }
1263                 if (!strcasecmp(v->name, pp_user_lookup[AST_PHONEPROV_STD_EXTENSION_LENGTH])) {
1264                         var = ast_var_assign(variable_lookup[AST_PHONEPROV_STD_EXTENSION_LENGTH], v->value);
1265                         AST_VAR_LIST_INSERT_TAIL(defaults, var);
1266                 }
1267         }
1268         ast_config_destroy(cfg);
1269
1270         return defaults;
1271 }
1272
1273 static int load_users(void)
1274 {
1275         struct ast_config *cfg;
1276         char *cat;
1277         const char *value;
1278         struct ast_flags config_flags = { 0 };
1279         struct varshead *defaults = get_defaults();
1280
1281         if (!defaults) {
1282                 ast_log(LOG_WARNING, "Unable to load default variables.\n");
1283                 return -1;
1284         }
1285
1286         if (!(cfg = ast_config_load("users.conf", config_flags))
1287                 || cfg == CONFIG_STATUS_FILEINVALID) {
1288                 ast_log(LOG_WARNING, "Unable to load users.conf\n");
1289                 return -1;
1290         }
1291
1292         cat = NULL;
1293         while ((cat = ast_category_browse(cfg, cat))) {
1294                 const char *tmp;
1295                 int i;
1296                 struct ast_var_t *varx;
1297                 struct ast_var_t *vard;
1298
1299                 if (strcasecmp(cat, "general") && strcasecmp(cat, "authentication")) {
1300                         struct varshead *variables = ast_var_list_create();
1301
1302                         if (!((tmp = ast_variable_retrieve(cfg, cat, "autoprov")) && ast_true(tmp))) {
1303                                 ast_var_list_destroy(variables);
1304                                 continue;
1305                         }
1306
1307                         /* Transfer the standard variables */
1308                         for (i = 0; i < AST_PHONEPROV_STD_VAR_LIST_LENGTH; i++) {
1309                                 if (pp_user_lookup[i]) {
1310                                         value = ast_variable_retrieve(cfg, cat, pp_user_lookup[i]);
1311                                         if (value) {
1312                                                 varx = ast_var_assign(variable_lookup[i],
1313                                                         value);
1314                                                 AST_VAR_LIST_INSERT_TAIL(variables, varx);
1315                                         }
1316                                 }
1317                         }
1318
1319                         if (!ast_var_find(variables, variable_lookup[AST_PHONEPROV_STD_MAC])) {
1320                                 ast_log(LOG_WARNING, "autoprov set for %s, but no mac address - skipping.\n", cat);
1321                                 ast_var_list_destroy(variables);
1322                                 continue;
1323                         }
1324
1325                         /* Apply defaults */
1326                         AST_VAR_LIST_TRAVERSE(defaults, vard) {
1327                                 if (ast_var_find(variables, vard->name)) {
1328                                         continue;
1329                                 }
1330                                 varx = ast_var_assign(vard->name, vard->value);
1331                                 AST_VAR_LIST_INSERT_TAIL(variables, varx);
1332                         }
1333
1334                         ast_phoneprov_add_extension(SIPUSERS_PROVIDER_NAME, variables);
1335                 }
1336         }
1337         ast_config_destroy(cfg);
1338         return 0;
1339 }
1340
1341 static int load_common(void)
1342 {
1343         struct ast_config *phoneprov_cfg;
1344         struct ast_flags config_flags = { 0 };
1345         char *cat;
1346
1347         if (!(phoneprov_cfg = ast_config_load("phoneprov.conf", config_flags))
1348                 || phoneprov_cfg == CONFIG_STATUS_FILEINVALID) {
1349                 ast_log(LOG_ERROR, "Unable to load config phoneprov.conf\n");
1350                 return -1;
1351         }
1352
1353         cat = NULL;
1354         while ((cat = ast_category_browse(phoneprov_cfg, cat))) {
1355                 if (!strcasecmp(cat, "general")) {
1356                         continue;
1357                 }
1358                 build_profile(cat, ast_variable_browse(phoneprov_cfg, cat));
1359         }
1360         ast_config_destroy(phoneprov_cfg);
1361
1362         if (!ao2_container_count(profiles)) {
1363                 ast_log(LOG_ERROR, "There are no provisioning profiles in phoneprov.conf.\n");
1364                 return -1;
1365         }
1366
1367         return 0;
1368 }
1369
1370 static int unload_module(void)
1371 {
1372         ast_http_uri_unlink(&phoneprovuri);
1373         ast_custom_function_unregister(&pp_each_user_function);
1374         ast_custom_function_unregister(&pp_each_extension_function);
1375         ast_cli_unregister_multiple(pp_cli, ARRAY_LEN(pp_cli));
1376
1377         /* This cleans up the sip.conf/users.conf provider (called specifically for clarity) */
1378         ast_phoneprov_provider_unregister(SIPUSERS_PROVIDER_NAME);
1379
1380         /* This cleans up the framework which also cleans up the providers. */
1381         delete_profiles();
1382         ao2_cleanup(profiles);
1383         profiles = NULL;
1384         delete_routes();
1385         ao2_cleanup(http_routes);
1386         http_routes = NULL;
1387         delete_users();
1388         ao2_cleanup(users);
1389         users = NULL;
1390         delete_providers();
1391         ao2_cleanup(providers);
1392         providers = NULL;
1393
1394         return 0;
1395 }
1396
1397 /*!
1398  * \brief Load the module
1399  *
1400  * Module loading including tests for configuration or dependencies.
1401  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1402  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1403  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1404  * configuration file or other non-critical problem return
1405  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1406  */
1407 static int load_module(void)
1408 {
1409         profiles = ao2_container_alloc(MAX_PROFILE_BUCKETS, phone_profile_hash_fn, phone_profile_cmp_fn);
1410         if (!profiles) {
1411                 ast_log(LOG_ERROR, "Unable to allocate profiles container.\n");
1412                 return AST_MODULE_LOAD_DECLINE;
1413         }
1414
1415         http_routes = ao2_container_alloc(MAX_ROUTE_BUCKETS, http_route_hash_fn, http_route_cmp_fn);
1416         if (!http_routes) {
1417                 ast_log(LOG_ERROR, "Unable to allocate routes container.\n");
1418                 goto error;
1419         }
1420
1421         if (load_common()) {
1422                 ast_log(LOG_ERROR, "Unable to load provisioning profiles.\n");
1423                 goto error;
1424         }
1425
1426         users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_fn, user_cmp_fn);
1427         if (!users) {
1428                 ast_log(LOG_ERROR, "Unable to allocate users container.\n");
1429                 goto error;
1430         }
1431
1432         providers = ao2_container_alloc(MAX_PROVIDER_BUCKETS, phoneprov_provider_hash_fn, phoneprov_provider_cmp_fn);
1433         if (!providers) {
1434                 ast_log(LOG_ERROR, "Unable to allocate providers container.\n");
1435                 goto error;
1436         }
1437
1438         /* Register ourselves as the provider for sip.conf/users.conf */
1439         if (ast_phoneprov_provider_register(SIPUSERS_PROVIDER_NAME, load_users)) {
1440                 ast_log(LOG_WARNING, "Unable register sip/users config provider.  Others may succeed.\n");
1441         }
1442
1443         ast_http_uri_link(&phoneprovuri);
1444
1445         ast_custom_function_register(&pp_each_user_function);
1446         ast_custom_function_register(&pp_each_extension_function);
1447         ast_cli_register_multiple(pp_cli, ARRAY_LEN(pp_cli));
1448
1449         return AST_MODULE_LOAD_SUCCESS;
1450
1451 error:
1452         unload_module();
1453         return AST_MODULE_LOAD_DECLINE;
1454 }
1455
1456 static int reload(void)
1457 {
1458         struct ao2_iterator i;
1459         struct phoneprov_provider *provider;
1460
1461         /* Clean everything except the providers */
1462         delete_routes();
1463         delete_users();
1464         delete_profiles();
1465
1466         /* Reload the profiles */
1467         if (load_common()) {
1468                 ast_log(LOG_ERROR, "Unable to reload provisioning profiles.\n");
1469                 unload_module();
1470                 return AST_MODULE_LOAD_DECLINE;
1471         }
1472
1473         /* For each provider, reload the users */
1474         ao2_lock(providers);
1475         i = ao2_iterator_init(providers, 0);
1476         for(; (provider = ao2_iterator_next(&i)); ao2_ref(provider, -1)) {
1477                 ast_log(LOG_VERBOSE, "Reloading provider '%s' users.\n", provider->provider_name);
1478                 if (provider->load_users()) {
1479                         ast_log(LOG_ERROR, "Unable to load provider '%s' users. Reload aborted.\n", provider->provider_name);
1480                         continue;
1481                 }
1482         }
1483         ao2_iterator_destroy(&i);
1484         ao2_unlock(providers);
1485
1486         return AST_MODULE_LOAD_SUCCESS;
1487 }
1488
1489 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "HTTP Phone Provisioning",
1490                 .support_level = AST_MODULE_SUPPORT_EXTENDED,
1491                 .load = load_module,
1492                 .unload = unload_module,
1493                 .reload = reload,
1494                 .load_pri = AST_MODPRI_CHANNEL_DEPEND,
1495         );
1496
1497 /****  Public API for register/unregister, set defaults, and add extension. ****/
1498
1499 const char *ast_phoneprov_std_variable_lookup(enum ast_phoneprov_std_variables var)
1500 {
1501         if (var >= AST_PHONEPROV_STD_VAR_LIST_LENGTH) {
1502                 return NULL;
1503         }
1504
1505         return variable_lookup[var];
1506 }
1507
1508 int ast_phoneprov_provider_register(char *provider_name,
1509         ast_phoneprov_load_users_cb load_users)
1510 {
1511         struct phoneprov_provider *provider;
1512
1513         if (ast_strlen_zero(provider_name)) {
1514                 ast_log(LOG_ERROR, "Provider name can't be empty.\n");
1515                 return -1;
1516         }
1517
1518         if (!providers) {
1519                 ast_log(LOG_WARNING, "Provider '%s' cannot be registered: res_phoneprov not loaded.\n", provider_name);
1520                 return -1;
1521         }
1522
1523         provider = find_provider(provider_name);
1524         if (provider) {
1525                 ast_log(LOG_ERROR, "There is already a provider registered named '%s'.\n", provider_name);
1526                 ao2_ref(provider, -1);
1527                 return -1;
1528         }
1529
1530         provider = ao2_alloc(sizeof(struct phoneprov_provider), provider_destructor);
1531         if (!provider) {
1532                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory for provider '%s'.\n", provider_name);
1533                 return -1;
1534         }
1535
1536         if (ast_string_field_init(provider, 32)) {
1537                 ao2_ref(provider, -1);
1538                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory for provider '%s' stringfields.\n", provider_name);
1539                 return -1;
1540         }
1541
1542         ast_string_field_set(provider, provider_name, provider_name);
1543         provider->load_users = load_users;
1544
1545         ao2_link(providers, provider);
1546         ao2_ref(provider, -1);
1547
1548         if (provider->load_users()) {
1549                 ast_log(LOG_ERROR, "Unable to load provider '%s' users. Register aborted.\n", provider_name);
1550                 ast_phoneprov_provider_unregister(provider_name);
1551                 return -1;
1552         }
1553
1554         ast_log(LOG_VERBOSE, "Registered phoneprov provider '%s'.\n", provider_name);
1555         return 0;
1556 }
1557
1558 static int extensions_delete_cb(void *obj, void *arg, int flags)
1559 {
1560         char *provider_name = arg;
1561         struct user *user = obj;
1562         if (strcmp(user->provider_name, provider_name)) {
1563                 return 0;
1564         }
1565         return CMP_MATCH;
1566 }
1567
1568 static int extension_delete_cb(void *obj, void *arg, void *data, int flags)
1569 {
1570         struct user *user = obj;
1571         char *provider_name = data;
1572         char *macaddress = arg;
1573
1574         if (!strcmp(user->provider_name, provider_name) && !strcasecmp(user->macaddress, macaddress)) {
1575                 return CMP_MATCH;
1576         }
1577         return 0;
1578 }
1579
1580 void ast_phoneprov_delete_extension(char *provider_name, char *macaddress)
1581 {
1582         ao2_callback_data(users, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
1583                 extension_delete_cb, macaddress, provider_name);
1584 }
1585
1586 void ast_phoneprov_delete_extensions(char *provider_name)
1587 {
1588         ao2_callback(users, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, extensions_delete_cb, provider_name);
1589 }
1590
1591 void ast_phoneprov_provider_unregister(char *provider_name)
1592 {
1593         if (!providers) {
1594                 return;
1595         }
1596
1597         ast_phoneprov_delete_extensions(provider_name);
1598         ao2_find(providers, provider_name, OBJ_SEARCH_KEY | OBJ_NODATA | OBJ_UNLINK);
1599         ast_log(LOG_VERBOSE, "Unegistered phoneprov provider '%s'.\n", provider_name);
1600 }
1601
1602 int ast_phoneprov_add_extension(char *provider_name, struct varshead *vars)
1603 {
1604         RAII_VAR(struct phoneprov_provider *, provider, NULL, ao2_cleanup);
1605         RAII_VAR(struct user *, user, NULL, ao2_cleanup);
1606         RAII_VAR(struct phone_profile *, profile, NULL, ao2_cleanup);
1607         struct extension *exten;
1608         char *profile_name;
1609         char *mac;
1610         char *username;
1611
1612         if (ast_strlen_zero(provider_name)) {
1613                 ast_log(LOG_ERROR, "Provider name can't be empty.\n");
1614                 return -1;
1615         }
1616         if (!vars) {
1617                 ast_log(LOG_ERROR, "Variable list can't be empty.\n");
1618                 return -1;
1619         }
1620
1621         username = ast_var_find(vars, variable_lookup[AST_PHONEPROV_STD_USERNAME]);
1622         if (!username) {
1623                 ast_log(LOG_ERROR, "Extension name can't be empty.\n");
1624                 return -1;
1625         }
1626
1627         mac = ast_var_find(vars, variable_lookup[AST_PHONEPROV_STD_MAC]);
1628         if (!mac) {
1629                 ast_log(LOG_ERROR, "MAC Address can't be empty.\n");
1630                 return -1;
1631         }
1632
1633         provider = find_provider(provider_name);
1634         if (!provider) {
1635                 ast_log(LOG_ERROR, "Provider '%s' wasn't found in the registry.\n", provider_name);
1636                 return -1;
1637         }
1638
1639         profile_name = ast_var_find(vars,
1640                 variable_lookup[AST_PHONEPROV_STD_PROFILE]);
1641         if (!profile_name) {
1642                 ast_log(LOG_ERROR, "No profile could be found for user '%s' - skipping.\n", username);
1643                 return -1;
1644         }
1645         if (!(profile = find_profile(profile_name))) {
1646                 ast_log(LOG_ERROR, "Could not look up profile '%s' - skipping.\n", profile_name);
1647                 return -1;
1648         }
1649
1650         if (!(user = find_user(mac))) {
1651
1652                 if (!(user = build_user(mac, profile, provider_name))) {
1653                         ast_log(LOG_ERROR, "Could not create user for '%s' - skipping\n", mac);
1654                         return -1;
1655                 }
1656
1657                 if (!(exten = build_extension(username, vars))) {
1658                         ast_log(LOG_ERROR, "Could not create extension for '%s' - skipping\n", user->macaddress);
1659                         return -1;
1660                 }
1661
1662                 if (add_user_extension(user, exten)) {
1663                         ast_log(LOG_WARNING, "Could not add extension '%s' to user '%s'\n", exten->name, user->macaddress);
1664                         exten = delete_extension(exten);
1665                         return -1;
1666                 }
1667
1668                 if (build_user_routes(user)) {
1669                         ast_log(LOG_WARNING, "Could not create http routes for '%s' - skipping\n", user->macaddress);
1670                         return -1;
1671                 }
1672                 ast_log(LOG_VERBOSE, "Created %s/%s for provider '%s'.\n", username, mac, provider_name);
1673                 ao2_link(users, user);
1674
1675         } else {
1676                 if (strcmp(provider_name, user->provider_name)) {
1677                         ast_log(LOG_ERROR, "MAC address '%s' was already added by provider '%s' - skipping\n", user->macaddress, user->provider_name);
1678                         return -1;
1679                 }
1680
1681                 if (!(exten = build_extension(username, vars))) {
1682                         ast_log(LOG_ERROR, "Could not create extension for '%s' - skipping\n", user->macaddress);
1683                         return -1;
1684                 }
1685
1686                 if (add_user_extension(user, exten)) {
1687                         ast_log(LOG_WARNING, "Could not add extension '%s' to user '%s'\n", exten->name, user->macaddress);
1688                         exten = delete_extension(exten);
1689                         return -1;
1690                 }
1691                 ast_log(LOG_VERBOSE, "Added %s/%s for provider '%s'.\n", username, mac, provider_name);
1692         }
1693
1694         return 0;
1695 }