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