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