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