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