* Fix accept/decline DTMF buffer overwrite in FollowMe.
[asterisk/asterisk.git] / apps / app_followme.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * A full-featured Find-Me/Follow-Me Application
5  * 
6  * Copyright (C) 2005-2006, BJ Weschke All Rights Reserved.
7  *
8  * BJ Weschke <bweschke@btwtech.com>
9  *
10  * This code is released by the author with no restrictions on usage.
11  *
12  * See http://www.asterisk.org for more information about
13  * the Asterisk project. Please do not directly contact
14  * any of the maintainers of this project for assistance;
15  * the project provides a web site, mailing lists and IRC
16  * channels for your use.
17  *
18  */
19
20 /*! \file
21  *
22  * \brief Find-Me Follow-Me application
23  *
24  * \author BJ Weschke <bweschke@btwtech.com>
25  *
26  * \arg See \ref Config_followme
27  *
28  * \ingroup applications
29  */
30
31 /*** MODULEINFO
32         <depend>chan_local</depend>
33         <support_level>core</support_level>
34  ***/
35
36 #include "asterisk.h"
37
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39
40 #include <signal.h>
41
42 #include "asterisk/paths.h"     /* use ast_config_AST_SPOOL_DIR */
43 #include "asterisk/lock.h"
44 #include "asterisk/file.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/pbx.h"
47 #include "asterisk/module.h"
48 #include "asterisk/translate.h"
49 #include "asterisk/say.h"
50 #include "asterisk/features.h"
51 #include "asterisk/musiconhold.h"
52 #include "asterisk/cli.h"
53 #include "asterisk/manager.h"
54 #include "asterisk/config.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/causes.h"
57 #include "asterisk/astdb.h"
58 #include "asterisk/dsp.h"
59 #include "asterisk/app.h"
60
61 /*** DOCUMENTATION
62         <application name="FollowMe" language="en_US">
63                 <synopsis>
64                         Find-Me/Follow-Me application.
65                 </synopsis>
66                 <syntax>
67                         <parameter name="followmeid" required="true" />
68                         <parameter name="options">
69                                 <optionlist>
70                                         <option name="a">
71                                                 <para>Record the caller's name so it can be announced to the
72                                                 callee on each step.</para>
73                                         </option>
74                                         <option name="d">
75                                                 <para>Disable the 'Please hold while we try to connect your call' announcement.</para>
76                                         </option>
77                                         <option name="I">
78                                                 <para>Asterisk will ignore any connected line update requests
79                                                 it may receive on this dial attempt.</para>
80                                         </option>
81                                         <option name="l">
82                                                 <para>Disable local call optimization so that applications with
83                                                 audio hooks between the local bridge don't get dropped when the
84                                                 calls get joined directly.</para>
85                                         </option>
86                                         <option name="N">
87                                                 <para>Don't answer the incoming call until we're ready to
88                                                 connect the caller or give up.</para>
89                                                 <note>
90                                                         <para>This option is ignored if the call is already answered.</para>
91                                                 </note>
92                                                 <note>
93                                                         <para>If the call is not already answered, the 'a' and 's'
94                                                         options are ignored while the 'd' option is implicitly enabled.</para>
95                                                 </note>
96                                         </option>
97                                         <option name="n">
98                                                 <para>Playback the unreachable status message if we've run out
99                                                 of steps or the callee has elected not to be reachable.</para>
100                                         </option>
101                                         <option name="s">
102                                                 <para>Playback the incoming status message prior to starting
103                                                 the follow-me step(s)</para>
104                                         </option>
105                                 </optionlist>
106                         </parameter>
107                 </syntax>
108                 <description>
109                         <para>This application performs Find-Me/Follow-Me functionality for the caller
110                         as defined in the profile matching the <replaceable>followmeid</replaceable> parameter in
111                         <filename>followme.conf</filename>. If the specified <replaceable>followmeid</replaceable>
112                         profile doesn't exist in <filename>followme.conf</filename>, execution will be returned
113                         to the dialplan and call execution will continue at the next priority.</para>
114                         <para>Returns -1 on hangup.</para>
115                 </description>
116         </application>
117  ***/
118
119 static char *app = "FollowMe";
120
121 /*! Maximum accept/decline DTMF string plus terminator. */
122 #define MAX_YN_STRING           20
123
124 /*! \brief Number structure */
125 struct number {
126         char number[512];       /*!< Phone Number(s) and/or Extension(s) */
127         long timeout;           /*!< Dial Timeout, if used. */
128         int order;              /*!< The order to dial in */
129         AST_LIST_ENTRY(number) entry; /*!< Next Number record */
130 };
131
132 /*! \brief Data structure for followme scripts */
133 struct call_followme {
134         ast_mutex_t lock;
135         char name[AST_MAX_EXTENSION];   /*!< Name - FollowMeID */
136         char moh[MAX_MUSICCLASS];       /*!< Music On Hold Class to be used */
137         char context[AST_MAX_CONTEXT];  /*!< Context to dial from */
138         unsigned int active;            /*!< Profile is active (1), or disabled (0). */
139         int realtime;           /*!< Cached from realtime */
140         char takecall[MAX_YN_STRING];   /*!< Digit mapping to take a call */
141         char nextindp[MAX_YN_STRING];   /*!< Digit mapping to decline a call */
142         char callfromprompt[PATH_MAX];  /*!< Sound prompt name and path */
143         char norecordingprompt[PATH_MAX];       /*!< Sound prompt name and path */
144         char optionsprompt[PATH_MAX];   /*!< Sound prompt name and path */
145         char plsholdprompt[PATH_MAX];   /*!< Sound prompt name and path */
146         char statusprompt[PATH_MAX];    /*!< Sound prompt name and path */
147         char sorryprompt[PATH_MAX];     /*!< Sound prompt name and path */
148
149         AST_LIST_HEAD_NOLOCK(numbers, number) numbers;     /*!< Head of the list of follow-me numbers */
150         AST_LIST_HEAD_NOLOCK(blnumbers, number) blnumbers; /*!< Head of the list of black-listed numbers */
151         AST_LIST_HEAD_NOLOCK(wlnumbers, number) wlnumbers; /*!< Head of the list of white-listed numbers */
152         AST_LIST_ENTRY(call_followme) entry;           /*!< Next Follow-Me record */
153 };
154
155 struct fm_args {
156         /*! Inbound (caller) channel */
157         struct ast_channel *chan;
158         char *mohclass;
159         AST_LIST_HEAD_NOLOCK(cnumbers, number) cnumbers;
160         /*! Winning outbound (callee) channel */
161         struct ast_channel *outbound;
162         /*! Accumulated connected line information from inbound call. */
163         struct ast_party_connected_line connected_in;
164         /*! Accumulated connected line information from outbound call. */
165         struct ast_party_connected_line connected_out;
166         /*! TRUE if connected line information from inbound call changed. */
167         unsigned int pending_in_connected_update:1;
168         /*! TRUE if connected line information from outbound call is available. */
169         unsigned int pending_out_connected_update:1;
170         int status;
171         char context[AST_MAX_CONTEXT];
172         char namerecloc[AST_MAX_CONTEXT];
173         char takecall[MAX_YN_STRING];   /*!< Digit mapping to take a call */
174         char nextindp[MAX_YN_STRING];   /*!< Digit mapping to decline a call */
175         char callfromprompt[PATH_MAX];  /*!< Sound prompt name and path */
176         char norecordingprompt[PATH_MAX];       /*!< Sound prompt name and path */
177         char optionsprompt[PATH_MAX];   /*!< Sound prompt name and path */
178         char plsholdprompt[PATH_MAX];   /*!< Sound prompt name and path */
179         char statusprompt[PATH_MAX];    /*!< Sound prompt name and path */
180         char sorryprompt[PATH_MAX];     /*!< Sound prompt name and path */
181         struct ast_flags followmeflags;
182 };
183
184 struct findme_user {
185         struct ast_channel *ochan;
186         /*! Accumulated connected line information from outgoing call. */
187         struct ast_party_connected_line connected;
188         long digts;
189         int ynidx;
190         int state;
191         char dialarg[256];
192         /*! Collected digits to accept/decline the call. */
193         char yn[MAX_YN_STRING];
194         /*! TRUE if call cleared. */
195         unsigned int cleared:1;
196         /*! TRUE if connected line information is available. */
197         unsigned int pending_connected_update:1;
198         AST_LIST_ENTRY(findme_user) entry;
199 };
200
201 enum {
202         FOLLOWMEFLAG_STATUSMSG = (1 << 0),
203         FOLLOWMEFLAG_RECORDNAME = (1 << 1),
204         FOLLOWMEFLAG_UNREACHABLEMSG = (1 << 2),
205         FOLLOWMEFLAG_DISABLEHOLDPROMPT = (1 << 3),
206         FOLLOWMEFLAG_NOANSWER = (1 << 4),
207         FOLLOWMEFLAG_DISABLEOPTIMIZATION = (1 << 5),
208         FOLLOWMEFLAG_IGNORE_CONNECTEDLINE = (1 << 6),
209 };
210
211 AST_APP_OPTIONS(followme_opts, {
212         AST_APP_OPTION('a', FOLLOWMEFLAG_RECORDNAME),
213         AST_APP_OPTION('d', FOLLOWMEFLAG_DISABLEHOLDPROMPT),
214         AST_APP_OPTION('I', FOLLOWMEFLAG_IGNORE_CONNECTEDLINE),
215         AST_APP_OPTION('l', FOLLOWMEFLAG_DISABLEOPTIMIZATION),
216         AST_APP_OPTION('N', FOLLOWMEFLAG_NOANSWER),
217         AST_APP_OPTION('n', FOLLOWMEFLAG_UNREACHABLEMSG),
218         AST_APP_OPTION('s', FOLLOWMEFLAG_STATUSMSG),
219 });
220
221 static const char *featuredigittostr;
222 static int featuredigittimeout = 5000;          /*!< Feature Digit Timeout */
223 static const char *defaultmoh = "default";      /*!< Default Music-On-Hold Class */
224
225 static char takecall[MAX_YN_STRING] = "1";
226 static char nextindp[MAX_YN_STRING] = "2";
227 static char callfromprompt[PATH_MAX] = "followme/call-from";
228 static char norecordingprompt[PATH_MAX] = "followme/no-recording";
229 static char optionsprompt[PATH_MAX] = "followme/options";
230 static char plsholdprompt[PATH_MAX] = "followme/pls-hold-while-try";
231 static char statusprompt[PATH_MAX] = "followme/status";
232 static char sorryprompt[PATH_MAX] = "followme/sorry";
233
234
235 static AST_RWLIST_HEAD_STATIC(followmes, call_followme);
236 AST_LIST_HEAD_NOLOCK(findme_user_listptr, findme_user);
237
238 static void free_numbers(struct call_followme *f)
239 {
240         /* Free numbers attached to the profile */
241         struct number *prev;
242
243         while ((prev = AST_LIST_REMOVE_HEAD(&f->numbers, entry)))
244                 /* Free the number */
245                 ast_free(prev);
246         AST_LIST_HEAD_INIT_NOLOCK(&f->numbers);
247
248         while ((prev = AST_LIST_REMOVE_HEAD(&f->blnumbers, entry)))
249                 /* Free the blacklisted number */
250                 ast_free(prev);
251         AST_LIST_HEAD_INIT_NOLOCK(&f->blnumbers);
252
253         while ((prev = AST_LIST_REMOVE_HEAD(&f->wlnumbers, entry)))
254                 /* Free the whitelisted number */
255                 ast_free(prev);
256         AST_LIST_HEAD_INIT_NOLOCK(&f->wlnumbers);
257 }
258
259
260 /*! \brief Allocate and initialize followme profile */
261 static struct call_followme *alloc_profile(const char *fmname)
262 {
263         struct call_followme *f;
264
265         if (!(f = ast_calloc(1, sizeof(*f))))
266                 return NULL;
267
268         ast_mutex_init(&f->lock);
269         ast_copy_string(f->name, fmname, sizeof(f->name));
270         f->moh[0] = '\0';
271         f->context[0] = '\0';
272         ast_copy_string(f->takecall, takecall, sizeof(f->takecall));
273         ast_copy_string(f->nextindp, nextindp, sizeof(f->nextindp));
274         ast_copy_string(f->callfromprompt, callfromprompt, sizeof(f->callfromprompt));
275         ast_copy_string(f->norecordingprompt, norecordingprompt, sizeof(f->norecordingprompt));
276         ast_copy_string(f->optionsprompt, optionsprompt, sizeof(f->optionsprompt));
277         ast_copy_string(f->plsholdprompt, plsholdprompt, sizeof(f->plsholdprompt));
278         ast_copy_string(f->statusprompt, statusprompt, sizeof(f->statusprompt));
279         ast_copy_string(f->sorryprompt, sorryprompt, sizeof(f->sorryprompt));
280         AST_LIST_HEAD_INIT_NOLOCK(&f->numbers);
281         AST_LIST_HEAD_INIT_NOLOCK(&f->blnumbers);
282         AST_LIST_HEAD_INIT_NOLOCK(&f->wlnumbers);
283         return f;
284 }
285
286 static void init_profile(struct call_followme *f)
287 {
288         f->active = 1;
289         ast_copy_string(f->moh, defaultmoh, sizeof(f->moh));
290 }
291
292    
293    
294 /*! \brief Set parameter in profile from configuration file */
295 static void profile_set_param(struct call_followme *f, const char *param, const char *val, int linenum, int failunknown)
296 {
297
298         if (!strcasecmp(param, "musicclass") || !strcasecmp(param, "musiconhold") || !strcasecmp(param, "music")) 
299                 ast_copy_string(f->moh, val, sizeof(f->moh));
300         else if (!strcasecmp(param, "context")) 
301                 ast_copy_string(f->context, val, sizeof(f->context));
302         else if (!strcasecmp(param, "takecall"))
303                 ast_copy_string(f->takecall, val, sizeof(f->takecall));
304         else if (!strcasecmp(param, "declinecall"))
305                 ast_copy_string(f->nextindp, val, sizeof(f->nextindp));
306         else if (!strcasecmp(param, "call-from-prompt") || !strcasecmp(param, "call_from_prompt"))
307                 ast_copy_string(f->callfromprompt, val, sizeof(f->callfromprompt));
308         else if (!strcasecmp(param, "followme-norecording-prompt") || !strcasecmp(param, "norecording_prompt")) 
309                 ast_copy_string(f->norecordingprompt, val, sizeof(f->norecordingprompt));
310         else if (!strcasecmp(param, "followme-options-prompt") || !strcasecmp(param, "options_prompt")) 
311                 ast_copy_string(f->optionsprompt, val, sizeof(f->optionsprompt));
312         else if (!strcasecmp(param, "followme-pls-hold-prompt") || !strcasecmp(param, "pls_hold_prompt"))
313                 ast_copy_string(f->plsholdprompt, val, sizeof(f->plsholdprompt));
314         else if (!strcasecmp(param, "followme-status-prompt") || !strcasecmp(param, "status_prompt")) 
315                 ast_copy_string(f->statusprompt, val, sizeof(f->statusprompt));
316         else if (!strcasecmp(param, "followme-sorry-prompt") || !strcasecmp(param, "sorry_prompt")) 
317                 ast_copy_string(f->sorryprompt, val, sizeof(f->sorryprompt));
318         else if (failunknown) {
319                 if (linenum >= 0)
320                         ast_log(LOG_WARNING, "Unknown keyword in profile '%s': %s at line %d of followme.conf\n", f->name, param, linenum);
321                 else
322                         ast_log(LOG_WARNING, "Unknown keyword in profile '%s': %s\n", f->name, param);
323         }
324 }
325
326 /*! \brief Add a new number */
327 static struct number *create_followme_number(const char *number, int timeout, int numorder)
328 {
329         struct number *cur;
330         char *buf = ast_strdupa(number);
331         char *tmp;
332
333         if (!(cur = ast_calloc(1, sizeof(*cur))))
334                 return NULL;
335
336         cur->timeout = timeout;
337         if ((tmp = strchr(buf, ',')))
338                 *tmp = '\0';
339         ast_copy_string(cur->number, buf, sizeof(cur->number));
340         cur->order = numorder;
341         ast_debug(1, "Created a number, %s, order of , %d, with a timeout of %ld.\n", cur->number, cur->order, cur->timeout);
342
343         return cur;
344 }
345
346 /*! \brief Reload followme application module */
347 static int reload_followme(int reload)
348 {
349         struct call_followme *f;
350         struct ast_config *cfg;
351         char *cat = NULL, *tmp;
352         struct ast_variable *var;
353         struct number *cur, *nm;
354         char numberstr[90];
355         int timeout;
356         int numorder;
357         const char *takecallstr;
358         const char *declinecallstr;
359         const char *tmpstr;
360         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
361
362         if (!(cfg = ast_config_load("followme.conf", config_flags))) {
363                 ast_log(LOG_WARNING, "No follow me config file (followme.conf), so no follow me\n");
364                 return 0;
365         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
366                 return 0;
367         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
368                 ast_log(LOG_ERROR, "Config file followme.conf is in an invalid format.  Aborting.\n");
369                 return 0;
370         }
371
372         AST_RWLIST_WRLOCK(&followmes);
373
374         /* Reset Global Var Values */
375         featuredigittimeout = 5000;
376
377         /* Mark all profiles as inactive for the moment */
378         AST_RWLIST_TRAVERSE(&followmes, f, entry) {
379                 f->active = 0;
380         }
381
382         featuredigittostr = ast_variable_retrieve(cfg, "general", "featuredigittimeout");
383
384         if (!ast_strlen_zero(featuredigittostr)) {
385                 if (!sscanf(featuredigittostr, "%30d", &featuredigittimeout))
386                         featuredigittimeout = 5000;
387         }
388
389         if ((takecallstr = ast_variable_retrieve(cfg, "general", "takecall")) && !ast_strlen_zero(takecallstr)) {
390                 ast_copy_string(takecall, takecallstr, sizeof(takecall));
391         }
392
393         if ((declinecallstr = ast_variable_retrieve(cfg, "general", "declinecall")) && !ast_strlen_zero(declinecallstr)) {
394                 ast_copy_string(nextindp, declinecallstr, sizeof(nextindp));
395         }
396
397         if ((tmpstr = ast_variable_retrieve(cfg, "general", "call-from-prompt")) && !ast_strlen_zero(tmpstr)) {
398                 ast_copy_string(callfromprompt, tmpstr, sizeof(callfromprompt));
399         } else if ((tmpstr = ast_variable_retrieve(cfg, "general", "call_from_prompt")) && !ast_strlen_zero(tmpstr)) {
400                 ast_copy_string(callfromprompt, tmpstr, sizeof(callfromprompt));
401         }
402
403         if ((tmpstr = ast_variable_retrieve(cfg, "general", "norecording-prompt")) && !ast_strlen_zero(tmpstr)) {
404                 ast_copy_string(norecordingprompt, tmpstr, sizeof(norecordingprompt));
405         } else if ((tmpstr = ast_variable_retrieve(cfg, "general", "norecording_prompt")) && !ast_strlen_zero(tmpstr)) {
406                 ast_copy_string(norecordingprompt, tmpstr, sizeof(norecordingprompt));
407         }
408
409
410         if ((tmpstr = ast_variable_retrieve(cfg, "general", "options-prompt")) && !ast_strlen_zero(tmpstr)) {
411                 ast_copy_string(optionsprompt, tmpstr, sizeof(optionsprompt));
412         } else if ((tmpstr = ast_variable_retrieve(cfg, "general", "options_prompt")) && !ast_strlen_zero(tmpstr)) {
413                 ast_copy_string(optionsprompt, tmpstr, sizeof(optionsprompt));
414         }
415
416         if ((tmpstr = ast_variable_retrieve(cfg, "general", "pls-hold-prompt")) && !ast_strlen_zero(tmpstr)) {
417                 ast_copy_string(plsholdprompt, tmpstr, sizeof(plsholdprompt));
418         } else if ((tmpstr = ast_variable_retrieve(cfg, "general", "pls_hold_prompt")) && !ast_strlen_zero(tmpstr)) {
419                 ast_copy_string(plsholdprompt, tmpstr, sizeof(plsholdprompt));
420         }
421
422         if ((tmpstr = ast_variable_retrieve(cfg, "general", "status-prompt")) && !ast_strlen_zero(tmpstr)) {
423                 ast_copy_string(statusprompt, tmpstr, sizeof(statusprompt));
424         } else if ((tmpstr = ast_variable_retrieve(cfg, "general", "status_prompt")) && !ast_strlen_zero(tmpstr)) {
425                 ast_copy_string(statusprompt, tmpstr, sizeof(statusprompt));
426         }
427
428         if ((tmpstr = ast_variable_retrieve(cfg, "general", "sorry-prompt")) && !ast_strlen_zero(tmpstr)) {
429                 ast_copy_string(sorryprompt, tmpstr, sizeof(sorryprompt));
430         } else if ((tmpstr = ast_variable_retrieve(cfg, "general", "sorry_prompt")) && !ast_strlen_zero(tmpstr)) {
431                 ast_copy_string(sorryprompt, tmpstr, sizeof(sorryprompt));
432         }
433
434         /* Chug through config file */
435         while ((cat = ast_category_browse(cfg, cat))) {
436                 int new = 0;
437
438                 if (!strcasecmp(cat, "general"))
439                         continue;
440
441                 /* Look for an existing one */
442                 AST_LIST_TRAVERSE(&followmes, f, entry) {
443                         if (!strcasecmp(f->name, cat))
444                                 break;
445                 }
446
447                 ast_debug(1, "New profile %s.\n", cat);
448
449                 if (!f) {
450                         /* Make one then */
451                         f = alloc_profile(cat);
452                         new = 1;
453                 }
454
455                 /* Totally fail if we fail to find/create an entry */
456                 if (!f)
457                         continue;
458
459                 if (!new)
460                         ast_mutex_lock(&f->lock);
461                 /* Re-initialize the profile */
462                 init_profile(f);
463                 free_numbers(f);
464                 var = ast_variable_browse(cfg, cat);
465                 while (var) {
466                         if (!strcasecmp(var->name, "number")) {
467                                 int idx = 0;
468
469                                 /* Add a new number */
470                                 ast_copy_string(numberstr, var->value, sizeof(numberstr));
471                                 if ((tmp = strchr(numberstr, ','))) {
472                                         *tmp++ = '\0';
473                                         timeout = atoi(tmp);
474                                         if (timeout < 0) {
475                                                 timeout = 25;
476                                         }
477                                         if ((tmp = strchr(tmp, ','))) {
478                                                 *tmp++ = '\0';
479                                                 numorder = atoi(tmp);
480                                                 if (numorder < 0)
481                                                         numorder = 0;
482                                         } else 
483                                                 numorder = 0;
484                                 } else {
485                                         timeout = 25;
486                                         numorder = 0;
487                                 }
488
489                                 if (!numorder) {
490                                         idx = 1;
491                                         AST_LIST_TRAVERSE(&f->numbers, nm, entry) 
492                                                 idx++;
493                                         numorder = idx;
494                                 }
495                                 cur = create_followme_number(numberstr, timeout, numorder);
496                                 if (cur) {
497                                         AST_LIST_INSERT_TAIL(&f->numbers, cur, entry);
498                                 }
499                         } else {
500                                 profile_set_param(f, var->name, var->value, var->lineno, 1);
501                                 ast_debug(2, "Logging parameter %s with value %s from lineno %d\n", var->name, var->value, var->lineno);
502                         }
503                         var = var->next;
504                 } /* End while(var) loop */
505
506                 if (!new) 
507                         ast_mutex_unlock(&f->lock);
508                 else
509                         AST_RWLIST_INSERT_HEAD(&followmes, f, entry);
510         }
511
512         ast_config_destroy(cfg);
513
514         AST_RWLIST_UNLOCK(&followmes);
515
516         return 1;
517 }
518
519 static void clear_caller(struct findme_user *tmpuser)
520 {
521         struct ast_channel *outbound;
522
523         if (tmpuser && tmpuser->ochan && tmpuser->state >= 0) {
524                 outbound = tmpuser->ochan;
525                 ast_channel_lock(outbound);
526                 if (!ast_channel_cdr(outbound)) {
527                         ast_channel_cdr_set(outbound, ast_cdr_alloc());
528                         if (ast_channel_cdr(outbound)) {
529                                 ast_cdr_init(ast_channel_cdr(outbound), outbound);
530                         }
531                 }
532                 if (ast_channel_cdr(outbound)) {
533                         char tmp[256];
534
535                         snprintf(tmp, sizeof(tmp), "%s/%s", "Local", tmpuser->dialarg);
536                         ast_cdr_setapp(ast_channel_cdr(outbound), "FollowMe", tmp);
537                         ast_cdr_update(outbound);
538                         ast_cdr_start(ast_channel_cdr(outbound));
539                         ast_cdr_end(ast_channel_cdr(outbound));
540                         /* If the cause wasn't handled properly */
541                         if (ast_cdr_disposition(ast_channel_cdr(outbound), ast_channel_hangupcause(outbound))) {
542                                 ast_cdr_failed(ast_channel_cdr(outbound));
543                         }
544                 } else {
545                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
546                 }
547                 ast_channel_unlock(outbound);
548                 ast_hangup(outbound);
549                 tmpuser->ochan = NULL;
550         }
551 }
552
553 static void clear_calling_tree(struct findme_user_listptr *findme_user_list) 
554 {
555         struct findme_user *tmpuser;
556
557         AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry) {
558                 clear_caller(tmpuser);
559                 tmpuser->cleared = 1;
560         }
561 }
562
563 static void destroy_calling_tree(struct findme_user_listptr *findme_user_list)
564 {
565         struct findme_user *fmuser;
566
567         while ((fmuser = AST_LIST_REMOVE_HEAD(findme_user_list, entry))) {
568                 if (!fmuser->cleared) {
569                         clear_caller(fmuser);
570                 }
571                 ast_party_connected_line_free(&fmuser->connected);
572                 ast_free(fmuser);
573         }
574         ast_free(findme_user_list);
575 }
576
577 static struct ast_channel *wait_for_winner(struct findme_user_listptr *findme_user_list, struct number *nm, struct ast_channel *caller, char *namerecloc, struct fm_args *tpargs)
578 {
579         struct ast_party_connected_line connected;
580         struct ast_channel *watchers[256];
581         int pos;
582         struct ast_channel *winner;
583         struct ast_frame *f;
584         int ctstatus = 0;
585         int dg;
586         struct findme_user *tmpuser;
587         int to = 0;
588         int livechannels = 0;
589         int tmpto;
590         long totalwait = 0, wtd = 0, towas = 0;
591         char *callfromname;
592         char *pressbuttonname;
593
594         /* ------------ wait_for_winner_channel start --------------- */ 
595
596         callfromname = ast_strdupa(tpargs->callfromprompt);
597         pressbuttonname = ast_strdupa(tpargs->optionsprompt);
598
599         if (AST_LIST_EMPTY(findme_user_list)) {
600                 ast_verb(3, "couldn't reach at this number.\n");
601                 return NULL;
602         }
603
604         if (!caller) {
605                 ast_verb(3, "Original caller hungup. Cleanup.\n");
606                 clear_calling_tree(findme_user_list);
607                 return NULL;
608         }
609
610         totalwait = nm->timeout * 1000;
611
612         while (!ctstatus) {
613                 to = 1000;
614                 pos = 1; 
615                 livechannels = 0;
616                 watchers[0] = caller;
617
618                 dg = 0;
619                 winner = NULL;
620                 AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry) {
621                         if (tmpuser->state >= 0 && tmpuser->ochan) {
622                                 if (tmpuser->state == 3) 
623                                         tmpuser->digts += (towas - wtd);
624                                 if (tmpuser->digts && (tmpuser->digts > featuredigittimeout)) {
625                                         ast_verb(3, "We've been waiting for digits longer than we should have.\n");
626                                         if (!ast_strlen_zero(namerecloc)) {
627                                                 tmpuser->state = 1;
628                                                 tmpuser->digts = 0;
629                                                 if (!ast_streamfile(tmpuser->ochan, callfromname, ast_channel_language(tmpuser->ochan))) {
630                                                         ast_sched_runq(ast_channel_sched(tmpuser->ochan));
631                                                 } else {
632                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", callfromname);
633                                                         return NULL;
634                                                 }
635                                         } else {
636                                                 tmpuser->state = 2;
637                                                 tmpuser->digts = 0;
638                                                 if (!ast_streamfile(tmpuser->ochan, tpargs->norecordingprompt, ast_channel_language(tmpuser->ochan)))
639                                                         ast_sched_runq(ast_channel_sched(tmpuser->ochan));
640                                                 else {
641                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", tpargs->norecordingprompt);
642                                                         return NULL;
643                                                 }
644                                         }
645                                 }
646                                 if (ast_channel_stream(tmpuser->ochan)) {
647                                         ast_sched_runq(ast_channel_sched(tmpuser->ochan));
648                                         tmpto = ast_sched_wait(ast_channel_sched(tmpuser->ochan));
649                                         if (tmpto > 0 && tmpto < to)
650                                                 to = tmpto;
651                                         else if (tmpto < 0 && !ast_channel_timingfunc(tmpuser->ochan)) {
652                                                 ast_stopstream(tmpuser->ochan);
653                                                 if (tmpuser->state == 1) {
654                                                         ast_verb(3, "Playback of the call-from file appears to be done.\n");
655                                                         if (!ast_streamfile(tmpuser->ochan, namerecloc, ast_channel_language(tmpuser->ochan))) {
656                                                                 tmpuser->state = 2;
657                                                         } else {
658                                                                 ast_log(LOG_NOTICE, "Unable to playback %s. Maybe the caller didn't record their name?\n", namerecloc);
659                                                                 memset(tmpuser->yn, 0, sizeof(tmpuser->yn));
660                                                                 tmpuser->ynidx = 0;
661                                                                 if (!ast_streamfile(tmpuser->ochan, pressbuttonname, ast_channel_language(tmpuser->ochan)))
662                                                                         tmpuser->state = 3;
663                                                                 else {
664                                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", pressbuttonname);
665                                                                         return NULL;
666                                                                 } 
667                                                         }
668                                                 } else if (tmpuser->state == 2) {
669                                                         ast_verb(3, "Playback of name file appears to be done.\n");
670                                                         memset(tmpuser->yn, 0, sizeof(tmpuser->yn));
671                                                         tmpuser->ynidx = 0;
672                                                         if (!ast_streamfile(tmpuser->ochan, pressbuttonname, ast_channel_language(tmpuser->ochan))) {
673                                                                 tmpuser->state = 3;
674                                                         } else {
675                                                                 return NULL;
676                                                         } 
677                                                 } else if (tmpuser->state == 3) {
678                                                         ast_verb(3, "Playback of the next step file appears to be done.\n");
679                                                         tmpuser->digts = 0;
680                                                 }
681                                         }
682                                 }
683                                 watchers[pos++] = tmpuser->ochan;
684                                 livechannels++;
685                         }
686                 }
687
688                 tmpto = to;
689                 if (to < 0) {
690                         to = 1000;
691                         tmpto = 1000;
692                 }
693                 towas = to;
694                 winner = ast_waitfor_n(watchers, pos, &to);
695                 tmpto -= to;
696                 totalwait -= tmpto;
697                 wtd = to;
698                 if (totalwait <= 0) {
699                         ast_verb(3, "We've hit our timeout for this step. Drop everyone and move on to the next one. %ld\n", totalwait);
700                         clear_calling_tree(findme_user_list);
701                         return NULL;
702                 }
703                 if (winner) {
704                         /* Need to find out which channel this is */
705                         for (dg = 0; dg < ARRAY_LEN(watchers); ++dg) {
706                                 if (winner == watchers[dg]) {
707                                         break;
708                                 }
709                         }
710                         if (dg) {
711                                 /* The winner is an outgoing channel. */
712                                 AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry) {
713                                         if (tmpuser->ochan == winner) {
714                                                 break;
715                                         }
716                                 }
717                         } else {
718                                 tmpuser = NULL;
719                         }
720                         f = ast_read(winner);
721                         if (f) {
722                                 if (f->frametype == AST_FRAME_CONTROL) {
723                                         switch (f->subclass.integer) {
724                                         case AST_CONTROL_HANGUP:
725                                                 ast_verb(3, "%s received a hangup frame.\n", ast_channel_name(winner));
726                                                 if (f->data.uint32) {
727                                                         ast_channel_hangupcause_set(winner, f->data.uint32);
728                                                 }
729                                                 if (dg == 0) {
730                                                         ast_verb(3, "The calling channel hungup. Need to drop everyone else.\n");
731                                                         clear_calling_tree(findme_user_list);
732                                                         ctstatus = -1;
733                                                 }
734                                                 break;
735                                         case AST_CONTROL_ANSWER:
736                                                 ast_verb(3, "%s answered %s\n", ast_channel_name(winner), ast_channel_name(caller));
737                                                 /* If call has been answered, then the eventual hangup is likely to be normal hangup */ 
738                                                 ast_channel_hangupcause_set(winner, AST_CAUSE_NORMAL_CLEARING);
739                                                 ast_channel_hangupcause_set(caller, AST_CAUSE_NORMAL_CLEARING);
740                                                 ast_verb(3, "Starting playback of %s\n", callfromname);
741                                                 if (dg > 0) {
742                                                         if (!ast_strlen_zero(namerecloc)) {
743                                                                 if (!ast_streamfile(winner, callfromname, ast_channel_language(winner))) {
744                                                                         ast_sched_runq(ast_channel_sched(winner));
745                                                                         tmpuser->state = 1;
746                                                                 } else {
747                                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", callfromname);
748                                                                         ast_frfree(f);
749                                                                         return NULL;
750                                                                 }
751                                                         } else {
752                                                                 tmpuser->state = 2;
753                                                                 if (!ast_streamfile(tmpuser->ochan, tpargs->norecordingprompt, ast_channel_language(tmpuser->ochan)))
754                                                                         ast_sched_runq(ast_channel_sched(tmpuser->ochan));
755                                                                 else {
756                                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", tpargs->norecordingprompt);
757                                                                         ast_frfree(f);
758                                                                         return NULL;
759                                                                 }
760                                                         }
761                                                 }
762                                                 break;
763                                         case AST_CONTROL_BUSY:
764                                                 ast_verb(3, "%s is busy\n", ast_channel_name(winner));
765                                                 break;
766                                         case AST_CONTROL_CONGESTION:
767                                                 ast_verb(3, "%s is circuit-busy\n", ast_channel_name(winner));
768                                                 break;
769                                         case AST_CONTROL_RINGING:
770                                                 ast_verb(3, "%s is ringing\n", ast_channel_name(winner));
771                                                 break;
772                                         case AST_CONTROL_PROGRESS:
773                                                 ast_verb(3, "%s is making progress\n", ast_channel_name(winner));
774                                                 break;
775                                         case AST_CONTROL_VIDUPDATE:
776                                                 ast_verb(3, "%s requested a video update\n", ast_channel_name(winner));
777                                                 break;
778                                         case AST_CONTROL_SRCUPDATE:
779                                                 ast_verb(3, "%s requested a source update\n", ast_channel_name(winner));
780                                                 break;
781                                         case AST_CONTROL_PROCEEDING:
782                                                 ast_verb(3, "%s is proceeding\n", ast_channel_name(winner));
783                                                 break;
784                                         case AST_CONTROL_HOLD:
785                                                 ast_verb(3, "%s placed call on hold\n", ast_channel_name(winner));
786                                                 break;
787                                         case AST_CONTROL_UNHOLD:
788                                                 ast_verb(3, "%s removed call from hold\n", ast_channel_name(winner));
789                                                 break;
790                                         case AST_CONTROL_OFFHOOK:
791                                         case AST_CONTROL_FLASH:
792                                                 /* Ignore going off hook and flash */
793                                                 break;
794                                         case AST_CONTROL_CONNECTED_LINE:
795                                                 if (!tmpuser) {
796                                                         /*
797                                                          * Hold connected line update from caller until we have a
798                                                          * winner.
799                                                          */
800                                                         ast_verb(3,
801                                                                 "%s connected line has changed. Saving it until we have a winner.\n",
802                                                                 ast_channel_name(winner));
803                                                         ast_party_connected_line_set_init(&connected, &tpargs->connected_in);
804                                                         if (!ast_connected_line_parse_data(f->data.ptr, f->datalen, &connected)) {
805                                                                 ast_party_connected_line_set(&tpargs->connected_in,
806                                                                         &connected, NULL);
807                                                                 tpargs->pending_in_connected_update = 1;
808                                                         }
809                                                         ast_party_connected_line_free(&connected);
810                                                         break;
811                                                 }
812                                                 if (ast_test_flag(&tpargs->followmeflags, FOLLOWMEFLAG_IGNORE_CONNECTEDLINE)) {
813                                                         ast_verb(3, "Connected line update from %s prevented.\n",
814                                                                 ast_channel_name(winner));
815                                                 } else {
816                                                         ast_verb(3,
817                                                                 "%s connected line has changed. Saving it until answer.\n",
818                                                                 ast_channel_name(winner));
819                                                         ast_party_connected_line_set_init(&connected, &tmpuser->connected);
820                                                         if (!ast_connected_line_parse_data(f->data.ptr, f->datalen, &connected)) {
821                                                                 ast_party_connected_line_set(&tmpuser->connected,
822                                                                         &connected, NULL);
823                                                                 tmpuser->pending_connected_update = 1;
824                                                         }
825                                                         ast_party_connected_line_free(&connected);
826                                                 }
827                                                 break;
828                                         case AST_CONTROL_REDIRECTING:
829                                                 /*
830                                                  * Ignore because we are masking the FollowMe search progress to
831                                                  * the caller.
832                                                  */
833                                                 break;
834                                         case -1:
835                                                 ast_verb(3, "%s stopped sounds\n", ast_channel_name(winner));
836                                                 break;
837                                         default:
838                                                 ast_debug(1, "Dunno what to do with control type %d from %s\n",
839                                                         f->subclass.integer, ast_channel_name(winner));
840                                                 break;
841                                         }
842                                 } 
843                                 if (tmpuser && tmpuser->state == 3 && f->frametype == AST_FRAME_DTMF) {
844                                         if (ast_channel_stream(winner))
845                                                 ast_stopstream(winner);
846                                         tmpuser->digts = 0;
847                                         ast_debug(1, "DTMF received: %c\n", (char) f->subclass.integer);
848                                         if (tmpuser->ynidx < ARRAY_LEN(tmpuser->yn) - 1) {
849                                                 tmpuser->yn[tmpuser->ynidx++] = (char) f->subclass.integer;
850                                         }
851                                         ast_debug(1, "DTMF string: %s\n", tmpuser->yn);
852                                         if (!strcmp(tmpuser->yn, tpargs->takecall)) {
853                                                 ast_debug(1, "Match to take the call!\n");
854                                                 ast_frfree(f);
855                                                 return tmpuser->ochan;
856                                         }
857                                         if (!strcmp(tmpuser->yn, tpargs->nextindp)) {
858                                                 ast_debug(1, "Next in dial plan step requested.\n");
859                                                 ast_frfree(f);
860                                                 return NULL;
861                                         }
862                                 }
863
864                                 ast_frfree(f);
865                         } else {
866                                 ast_debug(1, "we didn't get a frame. hanging up. dg is %d\n", dg);
867                                 if (!dg) {
868                                         /* Caller hung up. */
869                                         clear_calling_tree(findme_user_list);
870                                         return NULL;
871                                 } else {
872                                         /* Outgoing channel hung up. */
873                                         tmpuser->state = -1;
874                                         tmpuser->ochan = NULL;
875                                         ast_hangup(winner);
876                                         --livechannels;
877                                         ast_debug(1, "live channels left %d\n", livechannels);
878                                         if (!livechannels) {
879                                                 ast_verb(3, "no live channels left. exiting.\n");
880                                                 return NULL;
881                                         }
882                                 }
883                         }
884                 } else {
885                         ast_debug(1, "timed out waiting for action\n");
886                 }
887         }
888
889         /* --- WAIT FOR WINNER NUMBER END! -----------*/
890         return NULL;
891 }
892
893 static void findmeexec(struct fm_args *tpargs)
894 {
895         struct number *nm;
896         struct ast_channel *outbound;
897         struct ast_channel *caller;
898         struct ast_channel *winner = NULL;
899         char dialarg[512];
900         char num[512];
901         int dg, idx;
902         char *rest, *number;
903         struct findme_user *tmpuser;
904         struct findme_user *fmuser;
905         struct findme_user_listptr *findme_user_list;
906
907         findme_user_list = ast_calloc(1, sizeof(*findme_user_list));
908         if (!findme_user_list) {
909                 ast_log(LOG_WARNING, "Failed to allocate memory for findme_user_list\n");
910                 return;
911         }
912         AST_LIST_HEAD_INIT_NOLOCK(findme_user_list);
913
914         caller = tpargs->chan;
915         for (idx = 1; !ast_check_hangup(caller); ++idx) {
916                 /* Find next followme numbers to dial. */
917                 AST_LIST_TRAVERSE(&tpargs->cnumbers, nm, entry) {
918                         if (nm->order == idx) {
919                                 break;
920                         }
921                 }
922                 if (!nm) {
923                         break;
924                 }
925
926                 ast_debug(2, "Number %s timeout %ld\n", nm->number,nm->timeout);
927
928                 ast_copy_string(num, nm->number, sizeof(num));
929                 for (number = num; number; number = rest) {
930                         rest = strchr(number, '&');
931                         if (rest) {
932                                 *rest++ = 0;
933                         }
934
935                         /* We check if the extension exists, before creating the ast_channel struct */
936                         if (!ast_exists_extension(caller, tpargs->context, number, 1, S_COR(ast_channel_caller(caller)->id.number.valid, ast_channel_caller(caller)->id.number.str, NULL))) {
937                                 ast_log(LOG_ERROR, "Extension '%s@%s' doesn't exist\n", number, tpargs->context);
938                                 continue;
939                         }
940
941                         if (!strcmp(tpargs->context, "")) {
942                                 snprintf(dialarg, sizeof(dialarg), "%s%s", number, ast_test_flag(&tpargs->followmeflags, FOLLOWMEFLAG_DISABLEOPTIMIZATION) ? "/n" : "");
943                         } else {
944                                 snprintf(dialarg, sizeof(dialarg), "%s@%s%s", number, tpargs->context, ast_test_flag(&tpargs->followmeflags, FOLLOWMEFLAG_DISABLEOPTIMIZATION) ? "/n" : "");
945                         }
946
947                         tmpuser = ast_calloc(1, sizeof(*tmpuser));
948                         if (!tmpuser) {
949                                 continue;
950                         }
951
952                         outbound = ast_request("Local", ast_channel_nativeformats(caller), caller, dialarg, &dg);
953                         if (outbound) {
954                                 ast_channel_lock_both(caller, outbound);
955                                 ast_connected_line_copy_from_caller(ast_channel_connected(outbound), ast_channel_caller(caller));
956                                 ast_channel_inherit_variables(caller, outbound);
957                                 ast_channel_datastore_inherit(caller, outbound);
958                                 ast_channel_language_set(outbound, ast_channel_language(caller));
959                                 ast_channel_accountcode_set(outbound, ast_channel_accountcode(caller));
960                                 ast_channel_musicclass_set(outbound, ast_channel_musicclass(caller));
961                                 ast_channel_unlock(outbound);
962                                 ast_channel_unlock(caller);
963                                 ast_verb(3, "calling Local/%s\n", dialarg);
964                                 if (!ast_call(outbound, dialarg, 0)) {
965                                         tmpuser->ochan = outbound;
966                                         tmpuser->state = 0;
967                                         tmpuser->cleared = 0;
968                                         ast_copy_string(tmpuser->dialarg, dialarg, sizeof(dialarg));
969                                         AST_LIST_INSERT_TAIL(findme_user_list, tmpuser, entry);
970                                 } else {
971                                         ast_verb(3, "couldn't reach at this number.\n");
972                                         ast_channel_lock(outbound);
973                                         if (!ast_channel_cdr(outbound)) {
974                                                 ast_channel_cdr_set(outbound, ast_cdr_alloc());
975                                         }
976                                         if (ast_channel_cdr(outbound)) {
977                                                 char tmp[256];
978
979                                                 ast_cdr_init(ast_channel_cdr(outbound), outbound);
980                                                 snprintf(tmp, sizeof(tmp), "%s/%s", "Local", dialarg);
981                                                 ast_cdr_setapp(ast_channel_cdr(outbound), "FollowMe", tmp);
982                                                 ast_cdr_update(outbound);
983                                                 ast_cdr_start(ast_channel_cdr(outbound));
984                                                 ast_cdr_end(ast_channel_cdr(outbound));
985                                                 /* If the cause wasn't handled properly */
986                                                 if (ast_cdr_disposition(ast_channel_cdr(outbound), ast_channel_hangupcause(outbound))) {
987                                                         ast_cdr_failed(ast_channel_cdr(outbound));
988                                                 }
989                                         } else {
990                                                 ast_log(LOG_ERROR, "Unable to create Call Detail Record\n");
991                                         }
992                                         ast_channel_unlock(outbound);
993                                         ast_hangup(outbound);
994                                         ast_free(tmpuser);
995                                 }
996                         } else {
997                                 ast_log(LOG_WARNING, "Unable to allocate a channel for Local/%s cause: %s\n", dialarg, ast_cause2str(dg));
998                                 ast_free(tmpuser);
999                         }
1000                 }
1001
1002                 if (AST_LIST_EMPTY(findme_user_list)) {
1003                         continue;
1004                 }
1005
1006                 winner = wait_for_winner(findme_user_list, nm, caller, tpargs->namerecloc, tpargs);
1007                 if (!winner) {
1008                         continue;
1009                 }
1010
1011                 /* Destroy losing calls up to the winner.  The rest will be destroyed later. */
1012                 while ((fmuser = AST_LIST_REMOVE_HEAD(findme_user_list, entry))) {
1013                         if (fmuser->ochan == winner) {
1014                                 /* Pass any connected line info up. */
1015                                 tpargs->connected_out = fmuser->connected;
1016                                 tpargs->pending_out_connected_update = fmuser->pending_connected_update;
1017                                 ast_free(fmuser);
1018                                 break;
1019                         } else {
1020                                 /* Destroy losing call. */
1021                                 if (!fmuser->cleared) {
1022                                         clear_caller(fmuser);
1023                                 }
1024                                 ast_party_connected_line_free(&fmuser->connected);
1025                                 ast_free(fmuser);
1026                         }
1027                 }
1028                 break;
1029         }
1030         destroy_calling_tree(findme_user_list);
1031         if (!winner) {
1032                 tpargs->status = 1;
1033         } else {
1034                 tpargs->status = 100;
1035                 tpargs->outbound = winner;
1036         }
1037 }
1038
1039 static struct call_followme *find_realtime(const char *name)
1040 {
1041         struct ast_variable *var;
1042         struct ast_variable *v;
1043         struct ast_config *cfg;
1044         const char *catg;
1045         struct call_followme *new_follower;
1046         struct ast_str *str;
1047
1048         str = ast_str_create(16);
1049         if (!str) {
1050                 return NULL;
1051         }
1052
1053         var = ast_load_realtime("followme", "name", name, SENTINEL);
1054         if (!var) {
1055                 ast_free(str);
1056                 return NULL;
1057         }
1058
1059         if (!(new_follower = alloc_profile(name))) {
1060                 ast_variables_destroy(var);
1061                 ast_free(str);
1062                 return NULL;
1063         }
1064
1065         for (v = var; v; v = v->next) {
1066                 if (!strcasecmp(v->name, "active")) {
1067                         if (ast_false(v->value)) {
1068                                 ast_mutex_destroy(&new_follower->lock);
1069                                 ast_free(new_follower);
1070                                 ast_variables_destroy(var);
1071                                 ast_free(str);
1072                                 return NULL;
1073                         }
1074                 } else {
1075                         profile_set_param(new_follower, v->name, v->value, 0, 0);
1076                 }
1077         }
1078
1079         ast_variables_destroy(var);
1080         new_follower->realtime = 1;
1081
1082         /* Load numbers */
1083         cfg = ast_load_realtime_multientry("followme_numbers", "ordinal LIKE", "%", "name",
1084                 name, SENTINEL);
1085         if (!cfg) {
1086                 ast_mutex_destroy(&new_follower->lock);
1087                 ast_free(new_follower);
1088                 ast_free(str);
1089                 return NULL;
1090         }
1091
1092         for (catg = ast_category_browse(cfg, NULL); catg; catg = ast_category_browse(cfg, catg)) {
1093                 const char *numstr;
1094                 const char *timeoutstr;
1095                 const char *ordstr;
1096                 int timeout;
1097                 struct number *cur;
1098
1099                 if (!(numstr = ast_variable_retrieve(cfg, catg, "phonenumber"))) {
1100                         continue;
1101                 }
1102                 if (!(timeoutstr = ast_variable_retrieve(cfg, catg, "timeout"))
1103                         || sscanf(timeoutstr, "%30d", &timeout) != 1
1104                         || timeout < 1) {
1105                         timeout = 25;
1106                 }
1107                 /* This one has to exist; it was part of the query */
1108                 ordstr = ast_variable_retrieve(cfg, catg, "ordinal");
1109                 ast_str_set(&str, 0, "%s", numstr);
1110                 if ((cur = create_followme_number(ast_str_buffer(str), timeout, atoi(ordstr)))) {
1111                         AST_LIST_INSERT_TAIL(&new_follower->numbers, cur, entry);
1112                 }
1113         }
1114         ast_config_destroy(cfg);
1115
1116         ast_free(str);
1117         return new_follower;
1118 }
1119
1120 static void end_bridge_callback(void *data)
1121 {
1122         char buf[80];
1123         time_t end;
1124         struct ast_channel *chan = data;
1125
1126         time(&end);
1127
1128         ast_channel_lock(chan);
1129         if (ast_channel_cdr(chan)->answer.tv_sec) {
1130                 snprintf(buf, sizeof(buf), "%ld", (long) end - ast_channel_cdr(chan)->answer.tv_sec);
1131                 pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", buf);
1132         }
1133
1134         if (ast_channel_cdr(chan)->start.tv_sec) {
1135                 snprintf(buf, sizeof(buf), "%ld", (long) end - ast_channel_cdr(chan)->start.tv_sec);
1136                 pbx_builtin_setvar_helper(chan, "DIALEDTIME", buf);
1137         }
1138         ast_channel_unlock(chan);
1139 }
1140
1141 static void end_bridge_callback_data_fixup(struct ast_bridge_config *bconfig, struct ast_channel *originator, struct ast_channel *terminator)
1142 {
1143         bconfig->end_bridge_callback_data = originator;
1144 }
1145
1146 static int app_exec(struct ast_channel *chan, const char *data)
1147 {
1148         struct fm_args targs = { 0, };
1149         struct ast_bridge_config config;
1150         struct call_followme *f;
1151         struct number *nm, *newnm;
1152         int res = 0;
1153         char *argstr;
1154         char namerecloc[255];
1155         struct ast_channel *caller;
1156         struct ast_channel *outbound;
1157         AST_DECLARE_APP_ARGS(args,
1158                 AST_APP_ARG(followmeid);
1159                 AST_APP_ARG(options);
1160         );
1161
1162         if (ast_strlen_zero(data)) {
1163                 ast_log(LOG_WARNING, "%s requires an argument (followmeid)\n", app);
1164                 return -1;
1165         }
1166
1167         argstr = ast_strdupa((char *) data);
1168
1169         AST_STANDARD_APP_ARGS(args, argstr);
1170
1171         if (ast_strlen_zero(args.followmeid)) {
1172                 ast_log(LOG_WARNING, "%s requires an argument (followmeid)\n", app);
1173                 return -1;
1174         }
1175
1176         AST_RWLIST_RDLOCK(&followmes);
1177         AST_RWLIST_TRAVERSE(&followmes, f, entry) {
1178                 if (!strcasecmp(f->name, args.followmeid) && (f->active))
1179                         break;
1180         }
1181         AST_RWLIST_UNLOCK(&followmes);
1182
1183         ast_debug(1, "New profile %s.\n", args.followmeid);
1184
1185         if (!f) {
1186                 f = find_realtime(args.followmeid);
1187         }
1188
1189         if (!f) {
1190                 ast_log(LOG_WARNING, "Profile requested, %s, not found in the configuration.\n", args.followmeid);
1191                 return 0;
1192         }
1193
1194         /* XXX TODO: Reinsert the db check value to see whether or not follow-me is on or off */
1195         if (args.options) 
1196                 ast_app_parse_options(followme_opts, &targs.followmeflags, NULL, args.options);
1197
1198         /* Lock the profile lock and copy out everything we need to run with before unlocking it again */
1199         ast_mutex_lock(&f->lock);
1200         targs.mohclass = ast_strdupa(f->moh);
1201         ast_copy_string(targs.context, f->context, sizeof(targs.context));
1202         ast_copy_string(targs.takecall, f->takecall, sizeof(targs.takecall));
1203         ast_copy_string(targs.nextindp, f->nextindp, sizeof(targs.nextindp));
1204         ast_copy_string(targs.callfromprompt, f->callfromprompt, sizeof(targs.callfromprompt));
1205         ast_copy_string(targs.norecordingprompt, f->norecordingprompt, sizeof(targs.norecordingprompt));
1206         ast_copy_string(targs.optionsprompt, f->optionsprompt, sizeof(targs.optionsprompt));
1207         ast_copy_string(targs.plsholdprompt, f->plsholdprompt, sizeof(targs.plsholdprompt));
1208         ast_copy_string(targs.statusprompt, f->statusprompt, sizeof(targs.statusprompt));
1209         ast_copy_string(targs.sorryprompt, f->sorryprompt, sizeof(targs.sorryprompt));
1210         /* Copy the numbers we're going to use into another list in case the master list should get modified 
1211            (and locked) while we're trying to do a follow-me */
1212         AST_LIST_HEAD_INIT_NOLOCK(&targs.cnumbers);
1213         AST_LIST_TRAVERSE(&f->numbers, nm, entry) {
1214                 newnm = create_followme_number(nm->number, nm->timeout, nm->order);
1215                 if (newnm) {
1216                         AST_LIST_INSERT_TAIL(&targs.cnumbers, newnm, entry);
1217                 }
1218         }
1219         ast_mutex_unlock(&f->lock);
1220
1221         /* Forget the 'N' option if the call is already up. */
1222         if (ast_channel_state(chan) == AST_STATE_UP) {
1223                 ast_clear_flag(&targs.followmeflags, FOLLOWMEFLAG_NOANSWER);
1224         }
1225
1226         namerecloc[0] = '\0';
1227         if (ast_test_flag(&targs.followmeflags, FOLLOWMEFLAG_NOANSWER)) {
1228                 ast_indicate(chan, AST_CONTROL_RINGING);
1229         } else {
1230                 /* Answer the call */
1231                 if (ast_channel_state(chan) != AST_STATE_UP) {
1232                         ast_answer(chan);
1233                 }
1234
1235                 if (ast_test_flag(&targs.followmeflags, FOLLOWMEFLAG_STATUSMSG)) 
1236                         ast_stream_and_wait(chan, targs.statusprompt, "");
1237
1238                 if (ast_test_flag(&targs.followmeflags, FOLLOWMEFLAG_RECORDNAME)) {
1239                         int duration = 5;
1240
1241                         snprintf(namerecloc, sizeof(namerecloc), "%s/followme.%s",
1242                                 ast_config_AST_SPOOL_DIR, ast_channel_uniqueid(chan));
1243                         if (ast_play_and_record(chan, "vm-rec-name", namerecloc, 5, "sln", &duration,
1244                                 NULL, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE), 0, NULL) < 0) {
1245                                 goto outrun;
1246                         }
1247                         if (!ast_fileexists(namerecloc, NULL, ast_channel_language(chan))) {
1248                                 namerecloc[0] = '\0';
1249                         }
1250                 }
1251
1252                 if (!ast_test_flag(&targs.followmeflags, FOLLOWMEFLAG_DISABLEHOLDPROMPT)) {
1253                         if (ast_streamfile(chan, targs.plsholdprompt, ast_channel_language(chan)))
1254                                 goto outrun;
1255                         if (ast_waitstream(chan, "") < 0)
1256                                 goto outrun;
1257                 }
1258                 ast_moh_start(chan, S_OR(targs.mohclass, NULL), NULL);
1259         }
1260
1261         targs.status = 0;
1262         targs.chan = chan;
1263         ast_copy_string(targs.namerecloc, namerecloc, sizeof(targs.namerecloc));
1264         ast_channel_lock(chan);
1265         ast_connected_line_copy_from_caller(&targs.connected_in, ast_channel_caller(chan));
1266         ast_channel_unlock(chan);
1267
1268         findmeexec(&targs);
1269
1270         while ((nm = AST_LIST_REMOVE_HEAD(&targs.cnumbers, entry)))
1271                 ast_free(nm);
1272
1273         if (!ast_strlen_zero(namerecloc))
1274                 unlink(namerecloc);
1275
1276         if (targs.status != 100) {
1277                 if (ast_test_flag(&targs.followmeflags, FOLLOWMEFLAG_NOANSWER)) {
1278                         if (ast_channel_state(chan) != AST_STATE_UP) {
1279                                 ast_answer(chan);
1280                         }
1281                 } else {
1282                         ast_moh_stop(chan);
1283                 }
1284
1285                 if (ast_test_flag(&targs.followmeflags, FOLLOWMEFLAG_UNREACHABLEMSG)) 
1286                         ast_stream_and_wait(chan, targs.sorryprompt, "");
1287                 res = 0;
1288         } else {
1289                 caller = chan;
1290                 outbound = targs.outbound;
1291                 /* Bridge the two channels. */
1292
1293                 memset(&config, 0, sizeof(config));
1294                 ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
1295                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
1296                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
1297                 config.end_bridge_callback = end_bridge_callback;
1298                 config.end_bridge_callback_data = chan;
1299                 config.end_bridge_callback_data_fixup = end_bridge_callback_data_fixup;
1300
1301                 /* Update connected line to caller if available. */
1302                 if (targs.pending_out_connected_update) {
1303                         if (ast_channel_connected_line_sub(outbound, caller, &targs.connected_out, 0) &&
1304                                 ast_channel_connected_line_macro(outbound, caller, &targs.connected_out, 1, 0)) {
1305                                 ast_channel_update_connected_line(caller, &targs.connected_out, NULL);
1306                         }
1307                 }
1308
1309                 if (ast_test_flag(&targs.followmeflags, FOLLOWMEFLAG_NOANSWER)) {
1310                         if (ast_channel_state(caller) != AST_STATE_UP) {
1311                                 ast_answer(caller);
1312                         }
1313                 } else {
1314                         ast_moh_stop(caller);
1315                 }
1316
1317                 /* Be sure no generators are left on it */
1318                 ast_deactivate_generator(caller);
1319                 /* Make sure channels are compatible */
1320                 res = ast_channel_make_compatible(caller, outbound);
1321                 if (res < 0) {
1322                         ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", ast_channel_name(caller), ast_channel_name(outbound));
1323                         ast_hangup(outbound);
1324                         goto outrun;
1325                 }
1326
1327                 /* Update connected line to winner if changed. */
1328                 if (targs.pending_in_connected_update) {
1329                         if (ast_channel_connected_line_sub(caller, outbound, &targs.connected_in, 0) &&
1330                                 ast_channel_connected_line_macro(caller, outbound, &targs.connected_in, 0, 0)) {
1331                                 ast_channel_update_connected_line(outbound, &targs.connected_in, NULL);
1332                         }
1333                 }
1334
1335                 res = ast_bridge_call(caller, outbound, &config);
1336                 ast_hangup(outbound);
1337         }
1338
1339 outrun:
1340         ast_party_connected_line_free(&targs.connected_in);
1341         ast_party_connected_line_free(&targs.connected_out);
1342         if (f->realtime) {
1343                 /* Not in list */
1344                 free_numbers(f);
1345                 ast_free(f);
1346         }
1347
1348         return res;
1349 }
1350
1351 static int unload_module(void)
1352 {
1353         struct call_followme *f;
1354
1355         ast_unregister_application(app);
1356
1357         /* Free Memory. Yeah! I'm free! */
1358         AST_RWLIST_WRLOCK(&followmes);
1359         while ((f = AST_RWLIST_REMOVE_HEAD(&followmes, entry))) {
1360                 free_numbers(f);
1361                 ast_free(f);
1362         }
1363
1364         AST_RWLIST_UNLOCK(&followmes);
1365
1366         return 0;
1367 }
1368
1369 static int load_module(void)
1370 {
1371         if(!reload_followme(0))
1372                 return AST_MODULE_LOAD_DECLINE;
1373
1374         return ast_register_application_xml(app, app_exec);
1375 }
1376
1377 static int reload(void)
1378 {
1379         reload_followme(1);
1380
1381         return 0;
1382 }
1383
1384 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Find-Me/Follow-Me Application",
1385                 .load = load_module,
1386                 .unload = unload_module,
1387                 .reload = reload,
1388                );