5a68c206e0294392a28c1f1c86f1279b15c2f880
[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 }
570
571 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)
572 {
573         struct ast_party_connected_line connected;
574         struct ast_channel *watchers[256];
575         int pos;
576         struct ast_channel *winner;
577         struct ast_frame *f;
578         int ctstatus = 0;
579         int dg;
580         struct findme_user *tmpuser;
581         int to = 0;
582         int livechannels = 0;
583         int tmpto;
584         long totalwait = 0, wtd = 0, towas = 0;
585         char *callfromname;
586         char *pressbuttonname;
587
588         /* ------------ wait_for_winner_channel start --------------- */ 
589
590         callfromname = ast_strdupa(tpargs->callfromprompt);
591         pressbuttonname = ast_strdupa(tpargs->optionsprompt);
592
593         if (AST_LIST_EMPTY(findme_user_list)) {
594                 ast_verb(3, "couldn't reach at this number.\n");
595                 return NULL;
596         }
597
598         if (!caller) {
599                 ast_verb(3, "Original caller hungup. Cleanup.\n");
600                 clear_calling_tree(findme_user_list);
601                 return NULL;
602         }
603
604         totalwait = nm->timeout * 1000;
605
606         while (!ctstatus) {
607                 to = 1000;
608                 pos = 1; 
609                 livechannels = 0;
610                 watchers[0] = caller;
611
612                 dg = 0;
613                 winner = NULL;
614                 AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry) {
615                         if (tmpuser->state >= 0 && tmpuser->ochan) {
616                                 if (tmpuser->state == 3) 
617                                         tmpuser->digts += (towas - wtd);
618                                 if (tmpuser->digts && (tmpuser->digts > featuredigittimeout)) {
619                                         ast_verb(3, "We've been waiting for digits longer than we should have.\n");
620                                         if (!ast_strlen_zero(namerecloc)) {
621                                                 tmpuser->state = 1;
622                                                 tmpuser->digts = 0;
623                                                 if (!ast_streamfile(tmpuser->ochan, callfromname, ast_channel_language(tmpuser->ochan))) {
624                                                         ast_sched_runq(ast_channel_sched(tmpuser->ochan));
625                                                 } else {
626                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", callfromname);
627                                                         return NULL;
628                                                 }
629                                         } else {
630                                                 tmpuser->state = 2;
631                                                 tmpuser->digts = 0;
632                                                 if (!ast_streamfile(tmpuser->ochan, tpargs->norecordingprompt, ast_channel_language(tmpuser->ochan)))
633                                                         ast_sched_runq(ast_channel_sched(tmpuser->ochan));
634                                                 else {
635                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", tpargs->norecordingprompt);
636                                                         return NULL;
637                                                 }
638                                         }
639                                 }
640                                 if (ast_channel_stream(tmpuser->ochan)) {
641                                         ast_sched_runq(ast_channel_sched(tmpuser->ochan));
642                                         tmpto = ast_sched_wait(ast_channel_sched(tmpuser->ochan));
643                                         if (tmpto > 0 && tmpto < to)
644                                                 to = tmpto;
645                                         else if (tmpto < 0 && !ast_channel_timingfunc(tmpuser->ochan)) {
646                                                 ast_stopstream(tmpuser->ochan);
647                                                 if (tmpuser->state == 1) {
648                                                         ast_verb(3, "Playback of the call-from file appears to be done.\n");
649                                                         if (!ast_streamfile(tmpuser->ochan, namerecloc, ast_channel_language(tmpuser->ochan))) {
650                                                                 tmpuser->state = 2;
651                                                         } else {
652                                                                 ast_log(LOG_NOTICE, "Unable to playback %s. Maybe the caller didn't record their name?\n", namerecloc);
653                                                                 memset(tmpuser->yn, 0, sizeof(tmpuser->yn));
654                                                                 tmpuser->ynidx = 0;
655                                                                 if (!ast_streamfile(tmpuser->ochan, pressbuttonname, ast_channel_language(tmpuser->ochan)))
656                                                                         tmpuser->state = 3;
657                                                                 else {
658                                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", pressbuttonname);
659                                                                         return NULL;
660                                                                 } 
661                                                         }
662                                                 } else if (tmpuser->state == 2) {
663                                                         ast_verb(3, "Playback of name file appears to be done.\n");
664                                                         memset(tmpuser->yn, 0, sizeof(tmpuser->yn));
665                                                         tmpuser->ynidx = 0;
666                                                         if (!ast_streamfile(tmpuser->ochan, pressbuttonname, ast_channel_language(tmpuser->ochan))) {
667                                                                 tmpuser->state = 3;
668                                                         } else {
669                                                                 return NULL;
670                                                         } 
671                                                 } else if (tmpuser->state == 3) {
672                                                         ast_verb(3, "Playback of the next step file appears to be done.\n");
673                                                         tmpuser->digts = 0;
674                                                 }
675                                         }
676                                 }
677                                 watchers[pos++] = tmpuser->ochan;
678                                 livechannels++;
679                         }
680                 }
681
682                 tmpto = to;
683                 if (to < 0) {
684                         to = 1000;
685                         tmpto = 1000;
686                 }
687                 towas = to;
688                 winner = ast_waitfor_n(watchers, pos, &to);
689                 tmpto -= to;
690                 totalwait -= tmpto;
691                 wtd = to;
692                 if (totalwait <= 0) {
693                         ast_verb(3, "We've hit our timeout for this step. Drop everyone and move on to the next one. %ld\n", totalwait);
694                         clear_calling_tree(findme_user_list);
695                         return NULL;
696                 }
697                 if (winner) {
698                         /* Need to find out which channel this is */
699                         for (dg = 0; dg < ARRAY_LEN(watchers); ++dg) {
700                                 if (winner == watchers[dg]) {
701                                         break;
702                                 }
703                         }
704                         if (dg) {
705                                 /* The winner is an outgoing channel. */
706                                 AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry) {
707                                         if (tmpuser->ochan == winner) {
708                                                 break;
709                                         }
710                                 }
711                         } else {
712                                 tmpuser = NULL;
713                         }
714                         f = ast_read(winner);
715                         if (f) {
716                                 if (f->frametype == AST_FRAME_CONTROL) {
717                                         switch (f->subclass.integer) {
718                                         case AST_CONTROL_HANGUP:
719                                                 ast_verb(3, "%s received a hangup frame.\n", ast_channel_name(winner));
720                                                 if (f->data.uint32) {
721                                                         ast_channel_hangupcause_set(winner, f->data.uint32);
722                                                 }
723                                                 if (dg == 0) {
724                                                         ast_verb(3, "The calling channel hungup. Need to drop everyone else.\n");
725                                                         clear_calling_tree(findme_user_list);
726                                                         ctstatus = -1;
727                                                 }
728                                                 break;
729                                         case AST_CONTROL_ANSWER:
730                                                 ast_verb(3, "%s answered %s\n", ast_channel_name(winner), ast_channel_name(caller));
731                                                 /* If call has been answered, then the eventual hangup is likely to be normal hangup */ 
732                                                 ast_channel_hangupcause_set(winner, AST_CAUSE_NORMAL_CLEARING);
733                                                 ast_channel_hangupcause_set(caller, AST_CAUSE_NORMAL_CLEARING);
734                                                 ast_verb(3, "Starting playback of %s\n", callfromname);
735                                                 if (dg > 0) {
736                                                         if (!ast_strlen_zero(namerecloc)) {
737                                                                 if (!ast_streamfile(winner, callfromname, ast_channel_language(winner))) {
738                                                                         ast_sched_runq(ast_channel_sched(winner));
739                                                                         tmpuser->state = 1;
740                                                                 } else {
741                                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", callfromname);
742                                                                         ast_frfree(f);
743                                                                         return NULL;
744                                                                 }
745                                                         } else {
746                                                                 tmpuser->state = 2;
747                                                                 if (!ast_streamfile(tmpuser->ochan, tpargs->norecordingprompt, ast_channel_language(tmpuser->ochan)))
748                                                                         ast_sched_runq(ast_channel_sched(tmpuser->ochan));
749                                                                 else {
750                                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", tpargs->norecordingprompt);
751                                                                         ast_frfree(f);
752                                                                         return NULL;
753                                                                 }
754                                                         }
755                                                 }
756                                                 break;
757                                         case AST_CONTROL_BUSY:
758                                                 ast_verb(3, "%s is busy\n", ast_channel_name(winner));
759                                                 break;
760                                         case AST_CONTROL_CONGESTION:
761                                                 ast_verb(3, "%s is circuit-busy\n", ast_channel_name(winner));
762                                                 break;
763                                         case AST_CONTROL_RINGING:
764                                                 ast_verb(3, "%s is ringing\n", ast_channel_name(winner));
765                                                 break;
766                                         case AST_CONTROL_PROGRESS:
767                                                 ast_verb(3, "%s is making progress\n", ast_channel_name(winner));
768                                                 break;
769                                         case AST_CONTROL_VIDUPDATE:
770                                                 ast_verb(3, "%s requested a video update\n", ast_channel_name(winner));
771                                                 break;
772                                         case AST_CONTROL_SRCUPDATE:
773                                                 ast_verb(3, "%s requested a source update\n", ast_channel_name(winner));
774                                                 break;
775                                         case AST_CONTROL_PROCEEDING:
776                                                 ast_verb(3, "%s is proceeding\n", ast_channel_name(winner));
777                                                 break;
778                                         case AST_CONTROL_HOLD:
779                                                 ast_verb(3, "%s placed call on hold\n", ast_channel_name(winner));
780                                                 break;
781                                         case AST_CONTROL_UNHOLD:
782                                                 ast_verb(3, "%s removed call from hold\n", ast_channel_name(winner));
783                                                 break;
784                                         case AST_CONTROL_OFFHOOK:
785                                         case AST_CONTROL_FLASH:
786                                                 /* Ignore going off hook and flash */
787                                                 break;
788                                         case AST_CONTROL_CONNECTED_LINE:
789                                                 if (!tmpuser) {
790                                                         /*
791                                                          * Hold connected line update from caller until we have a
792                                                          * winner.
793                                                          */
794                                                         ast_verb(3,
795                                                                 "%s connected line has changed. Saving it until we have a winner.\n",
796                                                                 ast_channel_name(winner));
797                                                         ast_party_connected_line_set_init(&connected, &tpargs->connected_in);
798                                                         if (!ast_connected_line_parse_data(f->data.ptr, f->datalen, &connected)) {
799                                                                 ast_party_connected_line_set(&tpargs->connected_in,
800                                                                         &connected, NULL);
801                                                                 tpargs->pending_in_connected_update = 1;
802                                                         }
803                                                         ast_party_connected_line_free(&connected);
804                                                         break;
805                                                 }
806                                                 if (ast_test_flag(&tpargs->followmeflags, FOLLOWMEFLAG_IGNORE_CONNECTEDLINE)) {
807                                                         ast_verb(3, "Connected line update from %s prevented.\n",
808                                                                 ast_channel_name(winner));
809                                                 } else {
810                                                         ast_verb(3,
811                                                                 "%s connected line has changed. Saving it until answer.\n",
812                                                                 ast_channel_name(winner));
813                                                         ast_party_connected_line_set_init(&connected, &tmpuser->connected);
814                                                         if (!ast_connected_line_parse_data(f->data.ptr, f->datalen, &connected)) {
815                                                                 ast_party_connected_line_set(&tmpuser->connected,
816                                                                         &connected, NULL);
817                                                                 tmpuser->pending_connected_update = 1;
818                                                         }
819                                                         ast_party_connected_line_free(&connected);
820                                                 }
821                                                 break;
822                                         case AST_CONTROL_REDIRECTING:
823                                                 /*
824                                                  * Ignore because we are masking the FollowMe search progress to
825                                                  * the caller.
826                                                  */
827                                                 break;
828                                         case -1:
829                                                 ast_verb(3, "%s stopped sounds\n", ast_channel_name(winner));
830                                                 break;
831                                         default:
832                                                 ast_debug(1, "Dunno what to do with control type %d from %s\n",
833                                                         f->subclass.integer, ast_channel_name(winner));
834                                                 break;
835                                         }
836                                 } 
837                                 if (tmpuser && tmpuser->state == 3 && f->frametype == AST_FRAME_DTMF) {
838                                         if (ast_channel_stream(winner))
839                                                 ast_stopstream(winner);
840                                         tmpuser->digts = 0;
841                                         ast_debug(1, "DTMF received: %c\n", (char) f->subclass.integer);
842                                         if (tmpuser->ynidx < ARRAY_LEN(tmpuser->yn) - 1) {
843                                                 tmpuser->yn[tmpuser->ynidx++] = (char) f->subclass.integer;
844                                         }
845                                         ast_debug(1, "DTMF string: %s\n", tmpuser->yn);
846                                         if (!strcmp(tmpuser->yn, tpargs->takecall)) {
847                                                 ast_debug(1, "Match to take the call!\n");
848                                                 ast_frfree(f);
849                                                 return tmpuser->ochan;
850                                         }
851                                         if (!strcmp(tmpuser->yn, tpargs->nextindp)) {
852                                                 ast_debug(1, "Next in dial plan step requested.\n");
853                                                 ast_frfree(f);
854                                                 return NULL;
855                                         }
856                                 }
857
858                                 ast_frfree(f);
859                         } else {
860                                 ast_debug(1, "we didn't get a frame. hanging up. dg is %d\n", dg);
861                                 if (!dg) {
862                                         /* Caller hung up. */
863                                         clear_calling_tree(findme_user_list);
864                                         return NULL;
865                                 } else {
866                                         /* Outgoing channel hung up. */
867                                         tmpuser->state = -1;
868                                         tmpuser->ochan = NULL;
869                                         ast_hangup(winner);
870                                         --livechannels;
871                                         ast_debug(1, "live channels left %d\n", livechannels);
872                                         if (!livechannels) {
873                                                 ast_verb(3, "no live channels left. exiting.\n");
874                                                 return NULL;
875                                         }
876                                 }
877                         }
878                 } else {
879                         ast_debug(1, "timed out waiting for action\n");
880                 }
881         }
882
883         /* --- WAIT FOR WINNER NUMBER END! -----------*/
884         return NULL;
885 }
886
887 /*!
888  * \internal
889  * \brief Find an extension willing to take the call.
890  *
891  * \param tpargs Active Followme config.
892  * \param caller Channel initiating the outgoing calls.
893  *
894  * \retval winner Winning outgoing call.
895  * \retval NULL if could not find someone to take the call.
896  */
897 static struct ast_channel *findmeexec(struct fm_args *tpargs, struct ast_channel *caller)
898 {
899         struct number *nm;
900         struct ast_channel *outbound;
901         struct ast_channel *winner = NULL;
902         char dialarg[512];
903         char num[512];
904         int dg, idx;
905         char *rest, *number;
906         struct findme_user *tmpuser;
907         struct findme_user *fmuser;
908         struct findme_user_listptr findme_user_list = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
909
910         for (idx = 1; !ast_check_hangup(caller); ++idx) {
911                 /* Find next followme numbers to dial. */
912                 AST_LIST_TRAVERSE(&tpargs->cnumbers, nm, entry) {
913                         if (nm->order == idx) {
914                                 break;
915                         }
916                 }
917                 if (!nm) {
918                         break;
919                 }
920
921                 ast_debug(2, "Number %s timeout %ld\n", nm->number,nm->timeout);
922
923                 ast_copy_string(num, nm->number, sizeof(num));
924                 for (number = num; number; number = rest) {
925                         rest = strchr(number, '&');
926                         if (rest) {
927                                 *rest++ = 0;
928                         }
929
930                         /* We check if the extension exists, before creating the ast_channel struct */
931                         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))) {
932                                 ast_log(LOG_ERROR, "Extension '%s@%s' doesn't exist\n", number, tpargs->context);
933                                 continue;
934                         }
935
936                         if (!strcmp(tpargs->context, "")) {
937                                 snprintf(dialarg, sizeof(dialarg), "%s%s", number, ast_test_flag(&tpargs->followmeflags, FOLLOWMEFLAG_DISABLEOPTIMIZATION) ? "/n" : "");
938                         } else {
939                                 snprintf(dialarg, sizeof(dialarg), "%s@%s%s", number, tpargs->context, ast_test_flag(&tpargs->followmeflags, FOLLOWMEFLAG_DISABLEOPTIMIZATION) ? "/n" : "");
940                         }
941
942                         tmpuser = ast_calloc(1, sizeof(*tmpuser));
943                         if (!tmpuser) {
944                                 continue;
945                         }
946
947                         outbound = ast_request("Local", ast_channel_nativeformats(caller), caller, dialarg, &dg);
948                         if (outbound) {
949                                 ast_channel_lock_both(caller, outbound);
950                                 ast_connected_line_copy_from_caller(ast_channel_connected(outbound), ast_channel_caller(caller));
951                                 ast_channel_inherit_variables(caller, outbound);
952                                 ast_channel_datastore_inherit(caller, outbound);
953                                 ast_channel_language_set(outbound, ast_channel_language(caller));
954                                 ast_channel_accountcode_set(outbound, ast_channel_accountcode(caller));
955                                 ast_channel_musicclass_set(outbound, ast_channel_musicclass(caller));
956                                 ast_channel_unlock(outbound);
957                                 ast_channel_unlock(caller);
958                                 ast_verb(3, "calling Local/%s\n", dialarg);
959                                 if (!ast_call(outbound, dialarg, 0)) {
960                                         tmpuser->ochan = outbound;
961                                         tmpuser->state = 0;
962                                         tmpuser->cleared = 0;
963                                         ast_copy_string(tmpuser->dialarg, dialarg, sizeof(dialarg));
964                                         AST_LIST_INSERT_TAIL(&findme_user_list, tmpuser, entry);
965                                 } else {
966                                         ast_verb(3, "couldn't reach at this number.\n");
967                                         ast_channel_lock(outbound);
968                                         if (!ast_channel_cdr(outbound)) {
969                                                 ast_channel_cdr_set(outbound, ast_cdr_alloc());
970                                         }
971                                         if (ast_channel_cdr(outbound)) {
972                                                 char tmp[256];
973
974                                                 ast_cdr_init(ast_channel_cdr(outbound), outbound);
975                                                 snprintf(tmp, sizeof(tmp), "%s/%s", "Local", dialarg);
976                                                 ast_cdr_setapp(ast_channel_cdr(outbound), "FollowMe", tmp);
977                                                 ast_cdr_update(outbound);
978                                                 ast_cdr_start(ast_channel_cdr(outbound));
979                                                 ast_cdr_end(ast_channel_cdr(outbound));
980                                                 /* If the cause wasn't handled properly */
981                                                 if (ast_cdr_disposition(ast_channel_cdr(outbound), ast_channel_hangupcause(outbound))) {
982                                                         ast_cdr_failed(ast_channel_cdr(outbound));
983                                                 }
984                                         } else {
985                                                 ast_log(LOG_ERROR, "Unable to create Call Detail Record\n");
986                                         }
987                                         ast_channel_unlock(outbound);
988                                         ast_hangup(outbound);
989                                         ast_free(tmpuser);
990                                 }
991                         } else {
992                                 ast_log(LOG_WARNING, "Unable to allocate a channel for Local/%s cause: %s\n", dialarg, ast_cause2str(dg));
993                                 ast_free(tmpuser);
994                         }
995                 }
996
997                 if (AST_LIST_EMPTY(&findme_user_list)) {
998                         continue;
999                 }
1000
1001                 winner = wait_for_winner(&findme_user_list, nm, caller, tpargs->namerecloc, tpargs);
1002                 if (!winner) {
1003                         continue;
1004                 }
1005
1006                 /* Destroy losing calls up to the winner.  The rest will be destroyed later. */
1007                 while ((fmuser = AST_LIST_REMOVE_HEAD(&findme_user_list, entry))) {
1008                         if (fmuser->ochan == winner) {
1009                                 /* Pass any connected line info up. */
1010                                 tpargs->connected_out = fmuser->connected;
1011                                 tpargs->pending_out_connected_update = fmuser->pending_connected_update;
1012                                 ast_free(fmuser);
1013                                 break;
1014                         } else {
1015                                 /* Destroy losing call. */
1016                                 if (!fmuser->cleared) {
1017                                         clear_caller(fmuser);
1018                                 }
1019                                 ast_party_connected_line_free(&fmuser->connected);
1020                                 ast_free(fmuser);
1021                         }
1022                 }
1023                 break;
1024         }
1025         destroy_calling_tree(&findme_user_list);
1026         return winner;
1027 }
1028
1029 static struct call_followme *find_realtime(const char *name)
1030 {
1031         struct ast_variable *var;
1032         struct ast_variable *v;
1033         struct ast_config *cfg;
1034         const char *catg;
1035         struct call_followme *new_follower;
1036         struct ast_str *str;
1037
1038         str = ast_str_create(16);
1039         if (!str) {
1040                 return NULL;
1041         }
1042
1043         var = ast_load_realtime("followme", "name", name, SENTINEL);
1044         if (!var) {
1045                 ast_free(str);
1046                 return NULL;
1047         }
1048
1049         if (!(new_follower = alloc_profile(name))) {
1050                 ast_variables_destroy(var);
1051                 ast_free(str);
1052                 return NULL;
1053         }
1054
1055         for (v = var; v; v = v->next) {
1056                 if (!strcasecmp(v->name, "active")) {
1057                         if (ast_false(v->value)) {
1058                                 ast_mutex_destroy(&new_follower->lock);
1059                                 ast_free(new_follower);
1060                                 ast_variables_destroy(var);
1061                                 ast_free(str);
1062                                 return NULL;
1063                         }
1064                 } else {
1065                         profile_set_param(new_follower, v->name, v->value, 0, 0);
1066                 }
1067         }
1068
1069         ast_variables_destroy(var);
1070         new_follower->realtime = 1;
1071
1072         /* Load numbers */
1073         cfg = ast_load_realtime_multientry("followme_numbers", "ordinal LIKE", "%", "name",
1074                 name, SENTINEL);
1075         if (!cfg) {
1076                 ast_mutex_destroy(&new_follower->lock);
1077                 ast_free(new_follower);
1078                 ast_free(str);
1079                 return NULL;
1080         }
1081
1082         for (catg = ast_category_browse(cfg, NULL); catg; catg = ast_category_browse(cfg, catg)) {
1083                 const char *numstr;
1084                 const char *timeoutstr;
1085                 const char *ordstr;
1086                 int timeout;
1087                 struct number *cur;
1088
1089                 if (!(numstr = ast_variable_retrieve(cfg, catg, "phonenumber"))) {
1090                         continue;
1091                 }
1092                 if (!(timeoutstr = ast_variable_retrieve(cfg, catg, "timeout"))
1093                         || sscanf(timeoutstr, "%30d", &timeout) != 1
1094                         || timeout < 1) {
1095                         timeout = 25;
1096                 }
1097                 /* This one has to exist; it was part of the query */
1098                 ordstr = ast_variable_retrieve(cfg, catg, "ordinal");
1099                 ast_str_set(&str, 0, "%s", numstr);
1100                 if ((cur = create_followme_number(ast_str_buffer(str), timeout, atoi(ordstr)))) {
1101                         AST_LIST_INSERT_TAIL(&new_follower->numbers, cur, entry);
1102                 }
1103         }
1104         ast_config_destroy(cfg);
1105
1106         ast_free(str);
1107         return new_follower;
1108 }
1109
1110 static void end_bridge_callback(void *data)
1111 {
1112         char buf[80];
1113         time_t end;
1114         struct ast_channel *chan = data;
1115
1116         time(&end);
1117
1118         ast_channel_lock(chan);
1119         if (ast_channel_cdr(chan)->answer.tv_sec) {
1120                 snprintf(buf, sizeof(buf), "%ld", (long) end - ast_channel_cdr(chan)->answer.tv_sec);
1121                 pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", buf);
1122         }
1123
1124         if (ast_channel_cdr(chan)->start.tv_sec) {
1125                 snprintf(buf, sizeof(buf), "%ld", (long) end - ast_channel_cdr(chan)->start.tv_sec);
1126                 pbx_builtin_setvar_helper(chan, "DIALEDTIME", buf);
1127         }
1128         ast_channel_unlock(chan);
1129 }
1130
1131 static void end_bridge_callback_data_fixup(struct ast_bridge_config *bconfig, struct ast_channel *originator, struct ast_channel *terminator)
1132 {
1133         bconfig->end_bridge_callback_data = originator;
1134 }
1135
1136 static int app_exec(struct ast_channel *chan, const char *data)
1137 {
1138         struct fm_args *targs;
1139         struct ast_bridge_config config;
1140         struct call_followme *f;
1141         struct number *nm, *newnm;
1142         int res = 0;
1143         char *argstr;
1144         struct ast_channel *caller;
1145         struct ast_channel *outbound;
1146         AST_DECLARE_APP_ARGS(args,
1147                 AST_APP_ARG(followmeid);
1148                 AST_APP_ARG(options);
1149         );
1150
1151         if (ast_strlen_zero(data)) {
1152                 ast_log(LOG_WARNING, "%s requires an argument (followmeid)\n", app);
1153                 return -1;
1154         }
1155
1156         argstr = ast_strdupa((char *) data);
1157
1158         AST_STANDARD_APP_ARGS(args, argstr);
1159
1160         if (ast_strlen_zero(args.followmeid)) {
1161                 ast_log(LOG_WARNING, "%s requires an argument (followmeid)\n", app);
1162                 return -1;
1163         }
1164
1165         targs = ast_calloc(1, sizeof(*targs));
1166         if (!targs) {
1167                 return -1;
1168         }
1169
1170         AST_RWLIST_RDLOCK(&followmes);
1171         AST_RWLIST_TRAVERSE(&followmes, f, entry) {
1172                 if (!strcasecmp(f->name, args.followmeid) && (f->active))
1173                         break;
1174         }
1175         AST_RWLIST_UNLOCK(&followmes);
1176
1177         ast_debug(1, "New profile %s.\n", args.followmeid);
1178
1179         if (!f) {
1180                 f = find_realtime(args.followmeid);
1181         }
1182
1183         if (!f) {
1184                 ast_log(LOG_WARNING, "Profile requested, %s, not found in the configuration.\n", args.followmeid);
1185                 ast_free(targs);
1186                 return 0;
1187         }
1188
1189         /* XXX TODO: Reinsert the db check value to see whether or not follow-me is on or off */
1190         if (args.options) {
1191                 ast_app_parse_options(followme_opts, &targs->followmeflags, NULL, args.options);
1192         }
1193
1194         /* Lock the profile lock and copy out everything we need to run with before unlocking it again */
1195         ast_mutex_lock(&f->lock);
1196         targs->mohclass = ast_strdupa(f->moh);
1197         ast_copy_string(targs->context, f->context, sizeof(targs->context));
1198         ast_copy_string(targs->takecall, f->takecall, sizeof(targs->takecall));
1199         ast_copy_string(targs->nextindp, f->nextindp, sizeof(targs->nextindp));
1200         ast_copy_string(targs->callfromprompt, f->callfromprompt, sizeof(targs->callfromprompt));
1201         ast_copy_string(targs->norecordingprompt, f->norecordingprompt, sizeof(targs->norecordingprompt));
1202         ast_copy_string(targs->optionsprompt, f->optionsprompt, sizeof(targs->optionsprompt));
1203         ast_copy_string(targs->plsholdprompt, f->plsholdprompt, sizeof(targs->plsholdprompt));
1204         ast_copy_string(targs->statusprompt, f->statusprompt, sizeof(targs->statusprompt));
1205         ast_copy_string(targs->sorryprompt, f->sorryprompt, sizeof(targs->sorryprompt));
1206         /* Copy the numbers we're going to use into another list in case the master list should get modified 
1207            (and locked) while we're trying to do a follow-me */
1208         AST_LIST_HEAD_INIT_NOLOCK(&targs->cnumbers);
1209         AST_LIST_TRAVERSE(&f->numbers, nm, entry) {
1210                 newnm = create_followme_number(nm->number, nm->timeout, nm->order);
1211                 if (newnm) {
1212                         AST_LIST_INSERT_TAIL(&targs->cnumbers, newnm, entry);
1213                 }
1214         }
1215         ast_mutex_unlock(&f->lock);
1216
1217         /* Forget the 'N' option if the call is already up. */
1218         if (ast_channel_state(chan) == AST_STATE_UP) {
1219                 ast_clear_flag(&targs->followmeflags, FOLLOWMEFLAG_NOANSWER);
1220         }
1221
1222         if (ast_test_flag(&targs->followmeflags, FOLLOWMEFLAG_NOANSWER)) {
1223                 ast_indicate(chan, AST_CONTROL_RINGING);
1224         } else {
1225                 /* Answer the call */
1226                 if (ast_channel_state(chan) != AST_STATE_UP) {
1227                         ast_answer(chan);
1228                 }
1229
1230                 if (ast_test_flag(&targs->followmeflags, FOLLOWMEFLAG_STATUSMSG)) {
1231                         ast_stream_and_wait(chan, targs->statusprompt, "");
1232                 }
1233
1234                 if (ast_test_flag(&targs->followmeflags, FOLLOWMEFLAG_RECORDNAME)) {
1235                         int duration = 5;
1236
1237                         snprintf(targs->namerecloc, sizeof(targs->namerecloc), "%s/followme.%s",
1238                                 ast_config_AST_SPOOL_DIR, ast_channel_uniqueid(chan));
1239                         if (ast_play_and_record(chan, "vm-rec-name", targs->namerecloc, 5, "sln", &duration,
1240                                 NULL, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE), 0, NULL) < 0) {
1241                                 goto outrun;
1242                         }
1243                         if (!ast_fileexists(targs->namerecloc, NULL, ast_channel_language(chan))) {
1244                                 targs->namerecloc[0] = '\0';
1245                         }
1246                 }
1247
1248                 if (!ast_test_flag(&targs->followmeflags, FOLLOWMEFLAG_DISABLEHOLDPROMPT)) {
1249                         if (ast_streamfile(chan, targs->plsholdprompt, ast_channel_language(chan))) {
1250                                 goto outrun;
1251                         }
1252                         if (ast_waitstream(chan, "") < 0)
1253                                 goto outrun;
1254                 }
1255                 ast_moh_start(chan, S_OR(targs->mohclass, NULL), NULL);
1256         }
1257
1258         ast_channel_lock(chan);
1259         ast_connected_line_copy_from_caller(&targs->connected_in, ast_channel_caller(chan));
1260         ast_channel_unlock(chan);
1261
1262         outbound = findmeexec(targs, chan);
1263         if (!outbound) {
1264                 if (ast_test_flag(&targs->followmeflags, FOLLOWMEFLAG_NOANSWER)) {
1265                         if (ast_channel_state(chan) != AST_STATE_UP) {
1266                                 ast_answer(chan);
1267                         }
1268                 } else {
1269                         ast_moh_stop(chan);
1270                 }
1271
1272                 if (ast_test_flag(&targs->followmeflags, FOLLOWMEFLAG_UNREACHABLEMSG)) {
1273                         ast_stream_and_wait(chan, targs->sorryprompt, "");
1274                 }
1275                 res = 0;
1276         } else {
1277                 caller = chan;
1278                 /* Bridge the two channels. */
1279
1280                 memset(&config, 0, sizeof(config));
1281                 ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
1282                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
1283                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
1284                 config.end_bridge_callback = end_bridge_callback;
1285                 config.end_bridge_callback_data = chan;
1286                 config.end_bridge_callback_data_fixup = end_bridge_callback_data_fixup;
1287
1288                 /* Update connected line to caller if available. */
1289                 if (targs->pending_out_connected_update) {
1290                         if (ast_channel_connected_line_sub(outbound, caller, &targs->connected_out, 0) &&
1291                                 ast_channel_connected_line_macro(outbound, caller, &targs->connected_out, 1, 0)) {
1292                                 ast_channel_update_connected_line(caller, &targs->connected_out, NULL);
1293                         }
1294                 }
1295
1296                 if (ast_test_flag(&targs->followmeflags, FOLLOWMEFLAG_NOANSWER)) {
1297                         if (ast_channel_state(caller) != AST_STATE_UP) {
1298                                 ast_answer(caller);
1299                         }
1300                 } else {
1301                         ast_moh_stop(caller);
1302                 }
1303
1304                 /* Be sure no generators are left on it */
1305                 ast_deactivate_generator(caller);
1306                 /* Make sure channels are compatible */
1307                 res = ast_channel_make_compatible(caller, outbound);
1308                 if (res < 0) {
1309                         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));
1310                         ast_hangup(outbound);
1311                         goto outrun;
1312                 }
1313
1314                 /* Update connected line to winner if changed. */
1315                 if (targs->pending_in_connected_update) {
1316                         if (ast_channel_connected_line_sub(caller, outbound, &targs->connected_in, 0) &&
1317                                 ast_channel_connected_line_macro(caller, outbound, &targs->connected_in, 0, 0)) {
1318                                 ast_channel_update_connected_line(outbound, &targs->connected_in, NULL);
1319                         }
1320                 }
1321
1322                 res = ast_bridge_call(caller, outbound, &config);
1323                 ast_hangup(outbound);
1324         }
1325
1326 outrun:
1327         while ((nm = AST_LIST_REMOVE_HEAD(&targs->cnumbers, entry))) {
1328                 ast_free(nm);
1329         }
1330         if (!ast_strlen_zero(targs->namerecloc)) {
1331                 unlink(targs->namerecloc);
1332         }
1333         ast_party_connected_line_free(&targs->connected_in);
1334         ast_party_connected_line_free(&targs->connected_out);
1335         ast_free(targs);
1336
1337         if (f->realtime) {
1338                 /* Not in list */
1339                 free_numbers(f);
1340                 ast_free(f);
1341         }
1342
1343         return res;
1344 }
1345
1346 static int unload_module(void)
1347 {
1348         struct call_followme *f;
1349
1350         ast_unregister_application(app);
1351
1352         /* Free Memory. Yeah! I'm free! */
1353         AST_RWLIST_WRLOCK(&followmes);
1354         while ((f = AST_RWLIST_REMOVE_HEAD(&followmes, entry))) {
1355                 free_numbers(f);
1356                 ast_free(f);
1357         }
1358
1359         AST_RWLIST_UNLOCK(&followmes);
1360
1361         return 0;
1362 }
1363
1364 static int load_module(void)
1365 {
1366         if(!reload_followme(0))
1367                 return AST_MODULE_LOAD_DECLINE;
1368
1369         return ast_register_application_xml(app, app_exec);
1370 }
1371
1372 static int reload(void)
1373 {
1374         reload_followme(1);
1375
1376         return 0;
1377 }
1378
1379 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Find-Me/Follow-Me Application",
1380                 .load = load_module,
1381                 .unload = unload_module,
1382                 .reload = reload,
1383                );