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