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