fix a few more XML documentation problems
[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$")
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                                 if (errno != EPIPE) {
450                                         ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
451                                 } else {
452                                         ast_debug(3, "Requester closed the connection while downloading '%s'\n", path);
453                                 }
454                                 break;
455                         }
456                 }
457
458                 close(fd);
459                 route = unref_route(route);
460                 return NULL;
461         } else { /* Dynamic file */
462                 int bufsize;
463                 char *tmp;
464
465                 len = load_file(path, &file);
466                 if (len < 0) {
467                         ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, len);
468                         if (file) {
469                                 ast_free(file);
470                         }
471
472                         goto out500;
473                 }
474
475                 if (!file) {
476                         goto out500;
477                 }
478
479                 /* XXX This is a hack -- maybe sum length of all variables in route->user->headp and add that? */
480                 bufsize = len + VAR_BUF_SIZE;
481
482                 /* malloc() instead of alloca() here, just in case the file is bigger than
483                  * we have enough stack space for. */
484                 if (!(tmp = ast_calloc(1, bufsize))) {
485                         if (file) {
486                                 ast_free(file);
487                         }
488
489                         goto out500;
490                 }
491
492                 /* Unless we are overridden by serveriface or serveraddr, we set the SERVER variable to
493                  * the IP address we are listening on that the phone contacted for this config file */
494                 if (ast_strlen_zero(global_server)) {
495                         struct sockaddr name;
496                         socklen_t namelen = sizeof(name);
497                         int res;
498
499                         if ((res = getsockname(ser->fd, &name, &namelen))) {
500                                 ast_log(LOG_WARNING, "Could not get server IP, breakage likely.\n");
501                         } else {
502                                 struct ast_var_t *var;
503                                 struct extension *exten_iter;
504
505                                 if ((var = ast_var_assign("SERVER", ast_inet_ntoa(((struct sockaddr_in *)&name)->sin_addr)))) {
506                                         AST_LIST_TRAVERSE(&route->user->extensions, exten_iter, entry) {
507                                                 AST_LIST_INSERT_TAIL(exten_iter->headp, var, entries);
508                                         }
509                                 }
510                         }
511                 }
512
513                 pbx_substitute_variables_varshead(AST_LIST_FIRST(&route->user->extensions)->headp, file, tmp, bufsize);
514
515                 if (file) {
516                         ast_free(file);
517                 }
518
519                 ast_str_append(&result, 0,
520                         "Content-Type: %s\r\n"
521                         "Content-length: %d\r\n"
522                         "\r\n"
523                         "%s", route->file->mime_type, (int) strlen(tmp), tmp);
524
525                 if (tmp) {
526                         ast_free(tmp);
527                 }
528
529                 route = unref_route(route);
530
531                 return result;
532         }
533
534 out404:
535         *status = 404;
536         *title = strdup("Not Found");
537         *contentlength = 0;
538         return ast_http_error(404, "Not Found", NULL, "The requested URL was not found on this server.");
539
540 out500:
541         route = unref_route(route);
542         *status = 500;
543         *title = strdup("Internal Server Error");
544         *contentlength = 0;
545         return ast_http_error(500, "Internal Error", NULL, "An internal error has occured.");
546 }
547
548 /*! \brief Build a route structure and add it to the list of available http routes
549         \param pp_file File to link to the route
550         \param user User to link to the route (NULL means static route)
551         \param uri URI of the route
552 */
553 static void build_route(struct phoneprov_file *pp_file, struct user *user, char *uri)
554 {
555         struct http_route *route;
556
557         if (!(route = ao2_alloc(sizeof(*route), route_destructor))) {
558                 return;
559         }
560
561         if (ast_string_field_init(route, 32)) {
562                 ast_log(LOG_ERROR, "Couldn't create string fields for %s\n", pp_file->format);
563                 route = unref_route(route);
564                 return;
565         }
566
567         ast_string_field_set(route, uri, S_OR(uri, pp_file->format));
568         route->user = user;
569         route->file = pp_file;
570
571         ao2_link(http_routes, route);
572
573         route = unref_route(route);
574 }
575
576 /*! \brief Build a phone profile and add it to the list of phone profiles
577         \param name the name of the profile
578         \param v ast_variable from parsing phoneprov.conf
579 */
580 static void build_profile(const char *name, struct ast_variable *v)
581 {
582         struct phone_profile *profile;
583         struct ast_var_t *var;
584
585         if (!(profile = ao2_alloc(sizeof(*profile), profile_destructor))) {
586                 return;
587         }
588
589         if (ast_string_field_init(profile, 32)) {
590                 profile = unref_profile(profile);
591                 return;
592         }
593
594         if (!(profile->headp = ast_calloc(1, sizeof(*profile->headp)))) {
595                 profile = unref_profile(profile);
596                 return;
597         }
598
599         AST_LIST_HEAD_INIT_NOLOCK(&profile->static_files);
600         AST_LIST_HEAD_INIT_NOLOCK(&profile->dynamic_files);
601
602         ast_string_field_set(profile, name, name);
603         for (; v; v = v->next) {
604                 if (!strcasecmp(v->name, "mime_type")) {
605                         ast_string_field_set(profile, default_mime_type, v->value);
606                 } else if (!strcasecmp(v->name, "setvar")) {
607                         struct ast_var_t *variable;
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                                 if ((variable = ast_var_assign(args.varname, args.varval)))
624                                         AST_LIST_INSERT_TAIL(profile->headp, variable, entries);
625                         } while (0);
626                 } else if (!strcasecmp(v->name, "staticdir")) {
627                         ast_string_field_set(profile, staticdir, v->value);
628                 } else {
629                         struct phoneprov_file *pp_file;
630                         char *file_extension;
631                         char *value_copy = ast_strdupa(v->value);
632
633                         AST_DECLARE_APP_ARGS(args,
634                                 AST_APP_ARG(filename);
635                                 AST_APP_ARG(mimetype);
636                         );
637
638                         if (!(pp_file = ast_calloc(1, sizeof(*pp_file)))) {
639                                 profile = unref_profile(profile);
640                                 return;
641                         }
642                         if (ast_string_field_init(pp_file, 32)) {
643                                 ast_free(pp_file);
644                                 profile = unref_profile(profile);
645                                 return;
646                         }
647
648                         if ((file_extension = strrchr(pp_file->format, '.')))
649                                 file_extension++;
650
651                         AST_STANDARD_APP_ARGS(args, value_copy);
652
653                         /* Mime type order of preference
654                          * 1) Specific mime-type defined for file in profile
655                          * 2) Mime determined by extension
656                          * 3) Default mime type specified in profile
657                          * 4) text/plain
658                          */
659                         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"))));
660
661                         if (!strcasecmp(v->name, "static_file")) {
662                                 ast_string_field_set(pp_file, format, args.filename);
663                                 ast_string_field_build(pp_file, template, "%s%s", profile->staticdir, args.filename);
664                                 AST_LIST_INSERT_TAIL(&profile->static_files, pp_file, entry);
665                                 /* Add a route for the static files, as their filenames won't change per-user */
666                                 build_route(pp_file, NULL, NULL);
667                         } else {
668                                 ast_string_field_set(pp_file, format, v->name);
669                                 ast_string_field_set(pp_file, template, args.filename);
670                                 AST_LIST_INSERT_TAIL(&profile->dynamic_files, pp_file, entry);
671                         }
672                 }
673         }
674
675         /* Append the global variables to the variables list for this profile.
676          * This is for convenience later, when we need to provide a single
677          * variable list for use in substitution. */
678         ast_mutex_lock(&globals_lock);
679         AST_LIST_TRAVERSE(&global_variables, var, entries) {
680                 struct ast_var_t *new_var;
681                 if ((new_var = ast_var_assign(var->name, var->value))) {
682                         AST_LIST_INSERT_TAIL(profile->headp, new_var, entries);
683                 }
684         }
685         ast_mutex_unlock(&globals_lock);
686
687         ao2_link(profiles, profile);
688
689         profile = unref_profile(profile);
690 }
691
692 static struct extension *delete_extension(struct extension *exten)
693 {
694         struct ast_var_t *var;
695         while ((var = AST_LIST_REMOVE_HEAD(exten->headp, entries))) {
696                 ast_var_delete(var);
697         }
698         ast_free(exten->headp);
699         ast_string_field_free_memory(exten);
700
701         ast_free(exten);
702
703         return NULL;
704 }
705
706 static struct extension *build_extension(struct ast_config *cfg, const char *name)
707 {
708         struct extension *exten;
709         struct ast_var_t *var;
710         const char *tmp;
711         int i;
712
713         if (!(exten = ast_calloc(1, sizeof(*exten)))) {
714                 return NULL;
715         }
716
717         if (ast_string_field_init(exten, 32)) {
718                 ast_free(exten);
719                 exten = NULL;
720                 return NULL;
721         }
722
723         ast_string_field_set(exten, name, name);
724
725         if (!(exten->headp = ast_calloc(1, sizeof(*exten->headp)))) {
726                 ast_free(exten);
727                 exten = NULL;
728                 return NULL;
729         }
730
731         for (i = 0; i < PP_VAR_LIST_LENGTH; i++) {
732                 tmp = ast_variable_retrieve(cfg, name, pp_variable_list[i].user_var);
733
734                 /* If we didn't get a USERNAME variable, set it to the user->name */
735                 if (i == PP_USERNAME && !tmp) {
736                         if ((var = ast_var_assign(pp_variable_list[PP_USERNAME].template_var, exten->name))) {
737                                 AST_LIST_INSERT_TAIL(exten->headp, var, entries);
738                         }
739                         continue;
740                 } else if (i == PP_TIMEZONE) {
741                         /* perfectly ok if tmp is NULL, will set variables based on server's time zone */
742                         set_timezone_variables(exten->headp, tmp);
743                 } else if (i == PP_LINENUMBER) {
744                         if (!tmp) {
745                                 tmp = "1";
746                         }
747                         exten->index = atoi(tmp);
748                 } else if (i == PP_LINEKEYS) {
749                         if (!tmp) {
750                                 tmp = "1";
751                         }
752                 }
753
754                 if (tmp && (var = ast_var_assign(pp_variable_list[i].template_var, tmp))) {
755                         AST_LIST_INSERT_TAIL(exten->headp, var, entries);
756                 }
757         }
758
759         if (!ast_strlen_zero(global_server)) {
760                 if ((var = ast_var_assign("SERVER", global_server)))
761                         AST_LIST_INSERT_TAIL(exten->headp, var, entries);
762         }
763
764         if (!ast_strlen_zero(global_serverport)) {
765                 if ((var = ast_var_assign("SERVER_PORT", global_serverport)))
766                         AST_LIST_INSERT_TAIL(exten->headp, var, entries);
767         }
768
769         return exten;
770 }
771
772 static struct user *unref_user(struct user *user)
773 {
774         ao2_ref(user, -1);
775
776         return NULL;
777 }
778
779 /*! \brief Return a user looked up by name */
780 static struct user *find_user(const char *macaddress)
781 {
782         struct user tmp = {
783                 .macaddress = macaddress,
784         };
785
786         return ao2_find(users, &tmp, OBJ_POINTER);
787 }
788
789 static int users_hash_fn(const void *obj, const int flags)
790 {
791         const struct user *user = obj;
792
793         return ast_str_case_hash(user->macaddress);
794 }
795
796 static int users_cmp_fn(void *obj, void *arg, int flags)
797 {
798         const struct user *user1 = obj, *user2 = arg;
799
800         return !strcasecmp(user1->macaddress, user2->macaddress) ? CMP_MATCH | CMP_STOP : 0;
801 }
802
803 /*! \brief Free all memory associated with a user */
804 static void user_destructor(void *obj)
805 {
806         struct user *user = obj;
807         struct extension *exten;
808
809         while ((exten = AST_LIST_REMOVE_HEAD(&user->extensions, entry))) {
810                 exten = delete_extension(exten);
811         }
812
813         if (user->profile) {
814                 user->profile = unref_profile(user->profile);
815         }
816
817         ast_string_field_free_memory(user);
818 }
819
820 /*! \brief Delete all users */
821 static void delete_users(void)
822 {
823         struct ao2_iterator i;
824         struct user *user;
825
826         i = ao2_iterator_init(users, 0);
827         while ((user = ao2_iterator_next(&i))) {
828                 ao2_unlink(users, user);
829                 user = unref_user(user);
830         }
831 }
832
833 /*! \brief Build and return a user structure based on gathered config data */
834 static struct user *build_user(const char *mac, struct phone_profile *profile)
835 {
836         struct user *user;
837
838         if (!(user = ao2_alloc(sizeof(*user), user_destructor))) {
839                 profile = unref_profile(profile);
840                 return NULL;
841         }
842
843         if (ast_string_field_init(user, 32)) {
844                 profile = unref_profile(profile);
845                 user = unref_user(user);
846                 return NULL;
847         }
848
849         ast_string_field_set(user, macaddress, mac);
850         user->profile = profile; /* already ref counted by find_profile */
851
852         return user;
853 }
854
855 /*! \brief Add an extension to a user ordered by index/linenumber */
856 static int add_user_extension(struct user *user, struct extension *exten)
857 {
858         struct ast_var_t *var;
859
860         /* Append profile variables here, and substitute variables on profile
861          * setvars, so that we can use user specific variables in them */
862         AST_LIST_TRAVERSE(user->profile->headp, var, entries) {
863                 char expand_buf[VAR_BUF_SIZE] = {0,};
864                 struct ast_var_t *var2;
865
866                 pbx_substitute_variables_varshead(exten->headp, var->value, expand_buf, sizeof(expand_buf));
867                 if ((var2 = ast_var_assign(var->name, expand_buf)))
868                         AST_LIST_INSERT_TAIL(exten->headp, var2, entries);
869         }
870
871         if (AST_LIST_EMPTY(&user->extensions)) {
872                 AST_LIST_INSERT_HEAD(&user->extensions, exten, entry);
873         } else {
874                 struct extension *exten_iter;
875
876                 AST_LIST_TRAVERSE_SAFE_BEGIN(&user->extensions, exten_iter, entry) {
877                         if (exten->index < exten_iter->index) {
878                                 AST_LIST_INSERT_BEFORE_CURRENT(exten, entry);
879                         } else if (exten->index == exten_iter->index) {
880                                 ast_log(LOG_WARNING, "Duplicate linenumber=%d for %s\n", exten->index, user->macaddress);
881                                 return -1;
882                         } else if (!AST_LIST_NEXT(exten_iter, entry)) {
883                                 AST_LIST_INSERT_TAIL(&user->extensions, exten, entry);
884                         }
885                 }
886                 AST_LIST_TRAVERSE_SAFE_END;
887         }
888
889         return 0;
890 }
891
892 /*! \brief Add an http route for dynamic files attached to the profile of the user */
893 static int build_user_routes(struct user *user)
894 {
895         struct phoneprov_file *pp_file;
896
897         AST_LIST_TRAVERSE(&user->profile->dynamic_files, pp_file, entry) {
898                 char expand_buf[VAR_BUF_SIZE] = { 0, };
899
900                 pbx_substitute_variables_varshead(AST_LIST_FIRST(&user->extensions)->headp, pp_file->format, expand_buf, sizeof(expand_buf));
901                 build_route(pp_file, user, expand_buf);
902         }
903
904         return 0;
905 }
906
907 /* \brief Parse config files and create appropriate structures */
908 static int set_config(void)
909 {
910         struct ast_config *cfg, *phoneprov_cfg;
911         char *cat;
912         struct ast_variable *v;
913         struct ast_flags config_flags = { 0 };
914         struct ast_var_t *var;
915
916         /* Try to grab the port from sip.conf.  If we don't get it here, we'll set it
917          * to whatever is set in phoneprov.conf or default to 5060 */
918         if ((cfg = ast_config_load("sip.conf", config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
919                 ast_copy_string(global_serverport, S_OR(ast_variable_retrieve(cfg, "general", "bindport"), "5060"), sizeof(global_serverport));
920                 ast_config_destroy(cfg);
921         }
922
923         if (!(cfg = ast_config_load("users.conf", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
924                 ast_log(LOG_WARNING, "Unable to load users.conf\n");
925                 return 0;
926         }
927
928         /* Go ahead and load global variables from users.conf so we can append to profiles */
929         for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
930                 if (!strcasecmp(v->name, "vmexten")) {
931                         if ((var = ast_var_assign("VOICEMAIL_EXTEN", v->value))) {
932                                 ast_mutex_lock(&globals_lock);
933                                 AST_LIST_INSERT_TAIL(&global_variables, var, entries);
934                                 ast_mutex_unlock(&globals_lock);
935                         }
936                 }
937                 if (!strcasecmp(v->name, "localextenlength")) {
938                         if ((var = ast_var_assign("EXTENSION_LENGTH", v->value)))
939                                 ast_mutex_lock(&globals_lock);
940                                 AST_LIST_INSERT_TAIL(&global_variables, var, entries);
941                                 ast_mutex_unlock(&globals_lock);
942                 }
943         }
944
945         if (!(phoneprov_cfg = ast_config_load("phoneprov.conf", config_flags)) || phoneprov_cfg == CONFIG_STATUS_FILEINVALID) {
946                 ast_log(LOG_ERROR, "Unable to load config phoneprov.conf\n");
947                 ast_config_destroy(cfg);
948                 return -1;
949         }
950
951         cat = NULL;
952         while ((cat = ast_category_browse(phoneprov_cfg, cat))) {
953                 if (!strcasecmp(cat, "general")) {
954                         for (v = ast_variable_browse(phoneprov_cfg, cat); v; v = v->next) {
955                                 if (!strcasecmp(v->name, "serveraddr"))
956                                         ast_copy_string(global_server, v->value, sizeof(global_server));
957                                 else if (!strcasecmp(v->name, "serveriface")) {
958                                         struct in_addr addr;
959                                         lookup_iface(v->value, &addr);
960                                         ast_copy_string(global_server, ast_inet_ntoa(addr), sizeof(global_server));
961                                 } else if (!strcasecmp(v->name, "serverport"))
962                                         ast_copy_string(global_serverport, v->value, sizeof(global_serverport));
963                                 else if (!strcasecmp(v->name, "default_profile"))
964                                         ast_copy_string(global_default_profile, v->value, sizeof(global_default_profile));
965                         }
966                 } else
967                         build_profile(cat, ast_variable_browse(phoneprov_cfg, cat));
968         }
969
970         ast_config_destroy(phoneprov_cfg);
971
972         cat = NULL;
973         while ((cat = ast_category_browse(cfg, cat))) {
974                 const char *tmp, *mac;
975                 struct user *user;
976                 struct phone_profile *profile;
977                 struct extension *exten;
978
979                 if (!strcasecmp(cat, "general")) {
980                         continue;
981                 }
982
983                 if (!strcasecmp(cat, "authentication"))
984                         continue;
985
986                 if (!((tmp = ast_variable_retrieve(cfg, cat, "autoprov")) && ast_true(tmp)))
987                         continue;
988
989                 if (!(mac = ast_variable_retrieve(cfg, cat, "macaddress"))) {
990                         ast_log(LOG_WARNING, "autoprov set for %s, but no mac address - skipping.\n", cat);
991                         continue;
992                 }
993
994                 tmp = S_OR(ast_variable_retrieve(cfg, cat, "profile"), global_default_profile);
995                 if (ast_strlen_zero(tmp)) {
996                         ast_log(LOG_WARNING, "No profile for user [%s] with mac '%s' - skipping\n", cat, mac);
997                         continue;
998                 }
999
1000                 if (!(user = find_user(mac))) {
1001                         if (!(profile = find_profile(tmp))) {
1002                                 ast_log(LOG_WARNING, "Could not look up profile '%s' - skipping.\n", tmp);
1003                                 continue;
1004                         }
1005
1006                         if (!(user = build_user(mac, profile))) {
1007                                 ast_log(LOG_WARNING, "Could not create user for '%s' - skipping\n", user->macaddress);
1008                                 continue;
1009                         }
1010
1011                         if (!(exten = build_extension(cfg, cat))) {
1012                                 ast_log(LOG_WARNING, "Could not create extension for %s - skipping\n", user->macaddress);
1013                                 user = unref_user(user);
1014                                 continue;
1015                         }
1016
1017                         if (add_user_extension(user, exten)) {
1018                                 ast_log(LOG_WARNING, "Could not add extension '%s' to user '%s'\n", exten->name, user->macaddress);
1019                                 user = unref_user(user);
1020                                 exten = delete_extension(exten);
1021                                 continue;
1022                         }
1023
1024                         if (build_user_routes(user)) {
1025                                 ast_log(LOG_WARNING, "Could not create http routes for %s - skipping\n", user->macaddress);
1026                                 user = unref_user(user);
1027                                 continue;
1028                         }
1029
1030                         ao2_link(users, user);
1031                         user = unref_user(user);
1032                 } else {
1033                         if (!(exten = build_extension(cfg, cat))) {
1034                                 ast_log(LOG_WARNING, "Could not create extension for %s - skipping\n", user->macaddress);
1035                                 user = unref_user(user);
1036                                 continue;
1037                         }
1038
1039                         if (add_user_extension(user, exten)) {
1040                                 ast_log(LOG_WARNING, "Could not add extension '%s' to user '%s'\n", exten->name, user->macaddress);
1041                                 user = unref_user(user);
1042                                 exten = delete_extension(exten);
1043                                 continue;
1044                         }
1045
1046                         user = unref_user(user);
1047                 }
1048         }
1049
1050         ast_config_destroy(cfg);
1051
1052         return 0;
1053 }
1054
1055 /*! \brief Delete all http routes, freeing their memory */
1056 static void delete_routes(void)
1057 {
1058         struct ao2_iterator i;
1059         struct http_route *route;
1060
1061         i = ao2_iterator_init(http_routes, 0);
1062         while ((route = ao2_iterator_next(&i))) {
1063                 ao2_unlink(http_routes, route);
1064                 route = unref_route(route);
1065         }
1066 }
1067
1068 /*! \brief Delete all phone profiles, freeing their memory */
1069 static void delete_profiles(void)
1070 {
1071         struct ao2_iterator i;
1072         struct phone_profile *profile;
1073
1074         i = ao2_iterator_init(profiles, 0);
1075         while ((profile = ao2_iterator_next(&i))) {
1076                 ao2_unlink(profiles, profile);
1077                 profile = unref_profile(profile);
1078         }
1079 }
1080
1081 /*! \brief A dialplan function that can be used to print a string for each phoneprov user */
1082 static int pp_each_user_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1083 {
1084         char *tmp, expand_buf[VAR_BUF_SIZE] = {0,};
1085         struct ao2_iterator i;
1086         struct user *user;
1087         AST_DECLARE_APP_ARGS(args,
1088                 AST_APP_ARG(string);
1089                 AST_APP_ARG(exclude_mac);
1090         );
1091         AST_STANDARD_APP_ARGS(args, data);
1092
1093         /* Fix data by turning %{ into ${ */
1094         while ((tmp = strstr(args.string, "%{")))
1095                 *tmp = '$';
1096
1097         i = ao2_iterator_init(users, 0);
1098         while ((user = ao2_iterator_next(&i))) {
1099                 if (!ast_strlen_zero(args.exclude_mac) && !strcasecmp(user->macaddress, args.exclude_mac)) {
1100                         continue;
1101                 }
1102                 pbx_substitute_variables_varshead(AST_LIST_FIRST(&user->extensions)->headp, args.string, expand_buf, sizeof(expand_buf));
1103                 ast_build_string(&buf, &len, "%s", expand_buf);
1104                 user = unref_user(user);
1105         }
1106
1107         return 0;
1108 }
1109
1110 static struct ast_custom_function pp_each_user_function = {
1111         .name = "PP_EACH_USER",
1112         .synopsis = "Generate a string for each phoneprov user",
1113         .syntax = "PP_EACH_USER(<string>|<exclude_mac>)",
1114         .desc =
1115                 "Pass in a string, with phoneprov variables you want substituted in the format of\n"
1116                 "%{VARNAME}, and you will get the string rendered for each user in phoneprov\n"
1117                 "excluding ones with MAC address <exclude_mac>. Probably not useful outside of\n"
1118                 "res_phoneprov.\n"
1119                 "\nExample: ${PP_EACH_USER(<item><fn>%{DISPLAY_NAME}</fn></item>|${MAC})",
1120         .read = pp_each_user_exec,
1121 };
1122
1123 /*! \brief A dialplan function that can be used to output a template for each extension attached to a user */
1124 static int pp_each_extension_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1125 {
1126         struct user *user;
1127         struct extension *exten;
1128         char path[PATH_MAX];
1129         char *file;
1130         int filelen;
1131         AST_DECLARE_APP_ARGS(args,
1132                 AST_APP_ARG(mac);
1133                 AST_APP_ARG(template);
1134         );
1135
1136         AST_STANDARD_APP_ARGS(args, data);
1137
1138         if (ast_strlen_zero(args.mac) || ast_strlen_zero(args.template)) {
1139                 ast_log(LOG_WARNING, "PP_EACH_EXTENSION requries both a macaddress and template filename.\n");
1140                 return 0;
1141         }
1142
1143         if (!(user = find_user(args.mac))) {
1144                 ast_log(LOG_WARNING, "Could not find user with mac = '%s'\n", args.mac);
1145                 return 0;
1146         }
1147
1148         snprintf(path, sizeof(path), "%s/phoneprov/%s", ast_config_AST_DATA_DIR, args.template);
1149         filelen = load_file(path, &file);
1150         if (filelen < 0) {
1151                 ast_log(LOG_WARNING, "Could not load file: %s (%d)\n", path, filelen);
1152                 if (file) {
1153                         ast_free(file);
1154                 }
1155                 return 0;
1156         }
1157
1158         if (!file) {
1159                 return 0;
1160         }
1161
1162         AST_LIST_TRAVERSE(&user->extensions, exten, entry) {
1163                 char expand_buf[VAR_BUF_SIZE] = {0,};
1164                 pbx_substitute_variables_varshead(exten->headp, file, expand_buf, sizeof(expand_buf));
1165                 ast_build_string(&buf, &len, "%s", expand_buf);
1166         }
1167
1168         ast_free(file);
1169
1170         user = unref_user(user);
1171
1172         return 0;
1173 }
1174
1175 static struct ast_custom_function pp_each_extension_function = {
1176         .name = "PP_EACH_EXTENSION",
1177         .synopsis = "Execute specified template for each extension",
1178         .syntax = "PP_EACH_EXTENSION(<mac>|<template>)",
1179         .desc =
1180                 "Output the specified template for each extension associated with the specified\n"
1181                 "MAC address.",
1182         .read = pp_each_extension_exec,
1183 };
1184
1185 /*! \brief CLI command to list static and dynamic routes */
1186 static char *handle_show_routes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1187 {
1188 #define FORMAT "%-40.40s  %-30.30s\n"
1189         struct ao2_iterator i;
1190         struct http_route *route;
1191
1192         switch(cmd) {
1193         case CLI_INIT:
1194                 e->command = "phoneprov show routes";
1195                 e->usage =
1196                         "Usage: phoneprov show routes\n"
1197                         "       Lists all registered phoneprov http routes.\n";
1198                 return NULL;
1199         case CLI_GENERATE:
1200                 return NULL;
1201         }
1202
1203         /* This currently iterates over routes twice, but it is the only place I've needed
1204          * to really separate static an dynamic routes, so I've just left it this way. */
1205         ast_cli(a->fd, "Static routes\n\n");
1206         ast_cli(a->fd, FORMAT, "Relative URI", "Physical location");
1207         i = ao2_iterator_init(http_routes, 0);
1208         while ((route = ao2_iterator_next(&i))) {
1209                 if (!route->user)
1210                         ast_cli(a->fd, FORMAT, route->uri, route->file->template);
1211                 route = unref_route(route);
1212         }
1213
1214         ast_cli(a->fd, "\nDynamic routes\n\n");
1215         ast_cli(a->fd, FORMAT, "Relative URI", "Template");
1216
1217         i = ao2_iterator_init(http_routes, 0);
1218         while ((route = ao2_iterator_next(&i))) {
1219                 if (route->user)
1220                         ast_cli(a->fd, FORMAT, route->uri, route->file->template);
1221                 route = unref_route(route);
1222         }
1223
1224         return CLI_SUCCESS;
1225 }
1226
1227 static struct ast_cli_entry pp_cli[] = {
1228         AST_CLI_DEFINE(handle_show_routes, "Show registered phoneprov http routes"),
1229 };
1230
1231 static struct ast_http_uri phoneprovuri = {
1232         .callback = phoneprov_callback,
1233         .description = "Asterisk HTTP Phone Provisioning Tool",
1234         .uri = "phoneprov",
1235         .has_subtree = 1,
1236         .supports_get = 1,
1237         .data = NULL,
1238         .key = __FILE__,
1239 };
1240
1241 static int load_module(void)
1242 {
1243         profiles = ao2_container_alloc(MAX_PROFILE_BUCKETS, profile_hash_fn, profile_cmp_fn);
1244
1245         http_routes = ao2_container_alloc(MAX_ROUTE_BUCKETS, routes_hash_fn, routes_cmp_fn);
1246
1247         users = ao2_container_alloc(MAX_USER_BUCKETS, users_hash_fn, users_cmp_fn);
1248
1249         AST_LIST_HEAD_INIT_NOLOCK(&global_variables);
1250         ast_mutex_init(&globals_lock);
1251
1252         ast_custom_function_register(&pp_each_user_function);
1253         ast_custom_function_register(&pp_each_extension_function);
1254         ast_cli_register_multiple(pp_cli, ARRAY_LEN(pp_cli));
1255
1256         set_config();
1257         ast_http_uri_link(&phoneprovuri);
1258
1259         return 0;
1260 }
1261
1262 static int unload_module(void)
1263 {
1264         struct ast_var_t *var;
1265
1266         ast_http_uri_unlink(&phoneprovuri);
1267         ast_custom_function_unregister(&pp_each_user_function);
1268         ast_custom_function_unregister(&pp_each_extension_function);
1269         ast_cli_unregister_multiple(pp_cli, ARRAY_LEN(pp_cli));
1270
1271         delete_routes();
1272         delete_users();
1273         delete_profiles();
1274         ao2_ref(profiles, -1);
1275         ao2_ref(http_routes, -1);
1276         ao2_ref(users, -1);
1277
1278         ast_mutex_lock(&globals_lock);
1279         while ((var = AST_LIST_REMOVE_HEAD(&global_variables, entries))) {
1280                 ast_var_delete(var);
1281         }
1282         ast_mutex_unlock(&globals_lock);
1283
1284         ast_mutex_destroy(&globals_lock);
1285
1286         return 0;
1287 }
1288
1289 static int reload(void)
1290 {
1291         struct ast_var_t *var;
1292
1293         delete_routes();
1294         delete_users();
1295         delete_profiles();
1296
1297         ast_mutex_lock(&globals_lock);
1298         while ((var = AST_LIST_REMOVE_HEAD(&global_variables, entries))) {
1299                 ast_var_delete(var);
1300         }
1301         ast_mutex_unlock(&globals_lock);
1302
1303         set_config();
1304
1305         return 0;
1306 }
1307
1308 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "HTTP Phone Provisioning",
1309                 .load = load_module,
1310                 .unload = unload_module,
1311                 .reload = reload,
1312         );