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