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