57f440b3116c98e3f955096087adf2d1470e8756
[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 #include "asterisk.h"
32
33 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34
35 #include <signal.h>
36
37 #include "asterisk/lock.h"
38 #include "asterisk/file.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/pbx.h"
41 #include "asterisk/options.h"
42 #include "asterisk/module.h"
43 #include "asterisk/translate.h"
44 #include "asterisk/say.h"
45 #include "asterisk/features.h"
46 #include "asterisk/musiconhold.h"
47 #include "asterisk/cli.h"
48 #include "asterisk/manager.h"
49 #include "asterisk/config.h"
50 #include "asterisk/monitor.h"
51 #include "asterisk/utils.h"
52 #include "asterisk/causes.h"
53 #include "asterisk/astdb.h"
54 #include "asterisk/app.h"
55
56 static char *app = "FollowMe";
57 static char *synopsis = "Find-Me/Follow-Me application";
58 static char *descrip = 
59 "  FollowMe(followmeid[,options]):\n"
60 "This application performs Find-Me/Follow-Me functionality for the caller\n"
61 "as defined in the profile matching the <followmeid> parameter in\n"
62 "followme.conf. If the specified <followmeid> profile doesn't exist in\n"
63 "followme.conf, execution will be returned to the dialplan and call\n"
64 "execution will continue at the next priority.\n\n"
65 "  Options:\n"
66 "    s    - Playback the incoming status message prior to starting the follow-me step(s)\n"
67 "    a    - Record the caller's name so it can be announced to the callee on each step\n" 
68 "    n    - Playback the unreachable status message if we've run out of steps to reach the\n"
69 "           or the callee has elected not to be reachable.\n"
70 "Returns -1 on hangup\n";
71
72 /*! \brief Number structure */
73 struct number {
74         char number[512];       /*!< Phone Number(s) and/or Extension(s) */
75         long timeout;           /*!< Dial Timeout, if used. */
76         int order;              /*!< The order to dial in */
77         AST_LIST_ENTRY(number) entry; /*!< Next Number record */
78 };
79
80 /*! \brief Data structure for followme scripts */
81 struct call_followme {
82         ast_mutex_t lock;
83         char name[AST_MAX_EXTENSION];   /*!< Name - FollowMeID */
84         char moh[AST_MAX_CONTEXT];      /*!< Music On Hold Class to be used */
85         char context[AST_MAX_CONTEXT];  /*!< Context to dial from */
86         unsigned int active;            /*!< Profile is active (1), or disabled (0). */
87         char takecall[20];              /*!< Digit mapping to take a call */
88         char nextindp[20];              /*!< Digit mapping to decline a call */
89         char callfromprompt[PATH_MAX];  /*!< Sound prompt name and path */
90         char norecordingprompt[PATH_MAX];       /*!< Sound prompt name and path */
91         char optionsprompt[PATH_MAX];   /*!< Sound prompt name and path */
92         char plsholdprompt[PATH_MAX];   /*!< Sound prompt name and path */
93         char statusprompt[PATH_MAX];    /*!< Sound prompt name and path */
94         char sorryprompt[PATH_MAX];     /*!< Sound prompt name and path */
95
96         AST_LIST_HEAD_NOLOCK(numbers, number) numbers;     /*!< Head of the list of follow-me numbers */
97         AST_LIST_HEAD_NOLOCK(blnumbers, number) blnumbers; /*!< Head of the list of black-listed numbers */
98         AST_LIST_HEAD_NOLOCK(wlnumbers, number) wlnumbers; /*!< Head of the list of white-listed numbers */
99         AST_LIST_ENTRY(call_followme) entry;           /*!< Next Follow-Me record */
100 };
101
102 struct fm_args {
103         struct ast_channel *chan;
104         char *mohclass;
105         AST_LIST_HEAD_NOLOCK(cnumbers, number) cnumbers;
106         int status;
107         char context[AST_MAX_CONTEXT];
108         char namerecloc[AST_MAX_CONTEXT];
109         struct ast_channel *outbound;
110         char takecall[20];              /*!< Digit mapping to take a call */
111         char nextindp[20];              /*!< Digit mapping to decline a call */
112         char callfromprompt[PATH_MAX];  /*!< Sound prompt name and path */
113         char norecordingprompt[PATH_MAX];       /*!< Sound prompt name and path */
114         char optionsprompt[PATH_MAX];   /*!< Sound prompt name and path */
115         char plsholdprompt[PATH_MAX];   /*!< Sound prompt name and path */
116         char statusprompt[PATH_MAX];    /*!< Sound prompt name and path */
117         char sorryprompt[PATH_MAX];     /*!< Sound prompt name and path */
118         struct ast_flags followmeflags;
119 };
120
121 struct findme_user {
122         struct ast_channel *ochan;
123         int state;
124         char dialarg[256];
125         char yn[10];
126         int ynidx; 
127         long digts;
128         int cleared;
129         AST_LIST_ENTRY(findme_user) entry;      
130 };
131
132 enum {
133         FOLLOWMEFLAG_STATUSMSG = (1 << 0),
134         FOLLOWMEFLAG_RECORDNAME = (1 << 1),
135         FOLLOWMEFLAG_UNREACHABLEMSG = (1 << 2)
136 };
137
138 AST_APP_OPTIONS(followme_opts, {
139         AST_APP_OPTION('s', FOLLOWMEFLAG_STATUSMSG ),
140         AST_APP_OPTION('a', FOLLOWMEFLAG_RECORDNAME ),
141         AST_APP_OPTION('n', FOLLOWMEFLAG_UNREACHABLEMSG ),
142 });
143
144 static int ynlongest = 0;
145 static time_t start_time, answer_time, end_time;
146
147 static const char *featuredigittostr;
148 static int featuredigittimeout = 5000;          /*!< Feature Digit Timeout */
149 static const char *defaultmoh = "default";      /*!< Default Music-On-Hold Class */
150
151 static char takecall[20] = "1", nextindp[20] = "2";
152 static char callfromprompt[PATH_MAX] = "followme/call-from";
153 static char norecordingprompt[PATH_MAX] = "followme/no-recording";
154 static char optionsprompt[PATH_MAX] = "followme/options";
155 static char plsholdprompt[PATH_MAX] = "followme/pls-hold-while-try";
156 static char statusprompt[PATH_MAX] = "followme/status";
157 static char sorryprompt[PATH_MAX] = "followme/sorry";
158
159
160 static AST_RWLIST_HEAD_STATIC(followmes, call_followme);
161 AST_LIST_HEAD_NOLOCK(findme_user_listptr, findme_user);
162
163 static void free_numbers(struct call_followme *f)
164 {
165         /* Free numbers attached to the profile */
166         struct number *prev;
167
168         while ((prev = AST_LIST_REMOVE_HEAD(&f->numbers, entry)))
169                 /* Free the number */
170                 ast_free(prev);
171         AST_LIST_HEAD_INIT_NOLOCK(&f->numbers);
172
173         while ((prev = AST_LIST_REMOVE_HEAD(&f->blnumbers, entry)))
174                 /* Free the blacklisted number */
175                 ast_free(prev);
176         AST_LIST_HEAD_INIT_NOLOCK(&f->blnumbers);
177
178         while ((prev = AST_LIST_REMOVE_HEAD(&f->wlnumbers, entry)))
179                 /* Free the whitelisted number */
180                 ast_free(prev);
181         AST_LIST_HEAD_INIT_NOLOCK(&f->wlnumbers);
182         
183 }
184
185
186 /*! \brief Allocate and initialize followme profile */
187 static struct call_followme *alloc_profile(const char *fmname)
188 {
189         struct call_followme *f;
190
191         if (!(f = ast_calloc(1, sizeof(*f))))
192                 return NULL;
193
194         ast_mutex_init(&f->lock);
195         ast_copy_string(f->name, fmname, sizeof(f->name));
196         f->moh[0] = '\0';
197         f->context[0] = '\0';
198         ast_copy_string(f->takecall, takecall, sizeof(f->takecall));
199         ast_copy_string(f->nextindp, nextindp, sizeof(f->nextindp));
200         ast_copy_string(f->callfromprompt, callfromprompt, sizeof(f->callfromprompt));
201         ast_copy_string(f->norecordingprompt, norecordingprompt, sizeof(f->norecordingprompt));
202         ast_copy_string(f->optionsprompt, optionsprompt, sizeof(f->optionsprompt));
203         ast_copy_string(f->plsholdprompt, plsholdprompt, sizeof(f->plsholdprompt));
204         ast_copy_string(f->statusprompt, statusprompt, sizeof(f->statusprompt));
205         ast_copy_string(f->sorryprompt, sorryprompt, sizeof(f->sorryprompt));
206         AST_LIST_HEAD_INIT_NOLOCK(&f->numbers);
207         AST_LIST_HEAD_INIT_NOLOCK(&f->blnumbers);
208         AST_LIST_HEAD_INIT_NOLOCK(&f->wlnumbers);
209         return f;
210 }
211
212 static void init_profile(struct call_followme *f)
213 {
214         f->active = 1;
215         ast_copy_string(f->moh, defaultmoh, sizeof(f->moh));
216 }
217
218    
219    
220 /*! \brief Set parameter in profile from configuration file */
221 static void profile_set_param(struct call_followme *f, const char *param, const char *val, int linenum, int failunknown)
222 {
223
224         if (!strcasecmp(param, "musicclass") || !strcasecmp(param, "musiconhold") || !strcasecmp(param, "music")) 
225                 ast_copy_string(f->moh, val, sizeof(f->moh));
226         else if (!strcasecmp(param, "context")) 
227                 ast_copy_string(f->context, val, sizeof(f->context));
228         else if (!strcasecmp(param, "takecall"))
229                 ast_copy_string(f->takecall, val, sizeof(f->takecall));
230         else if (!strcasecmp(param, "declinecall"))
231                 ast_copy_string(f->nextindp, val, sizeof(f->nextindp));
232         else if (!strcasecmp(param, "call-from-prompt"))
233                 ast_copy_string(f->callfromprompt, val, sizeof(f->callfromprompt));
234         else if (!strcasecmp(param, "followme-norecording-prompt")) 
235                 ast_copy_string(f->norecordingprompt, val, sizeof(f->norecordingprompt));
236         else if (!strcasecmp(param, "followme-options-prompt")) 
237                 ast_copy_string(f->optionsprompt, val, sizeof(f->optionsprompt));
238         else if (!strcasecmp(param, "followme-pls-hold-prompt"))
239                 ast_copy_string(f->plsholdprompt, val, sizeof(f->plsholdprompt));
240         else if (!strcasecmp(param, "followme-status-prompt")) 
241                 ast_copy_string(f->statusprompt, val, sizeof(f->statusprompt));
242         else if (!strcasecmp(param, "followme-sorry-prompt")) 
243                 ast_copy_string(f->sorryprompt, val, sizeof(f->sorryprompt));
244         else if (failunknown) {
245                 if (linenum >= 0)
246                         ast_log(LOG_WARNING, "Unknown keyword in profile '%s': %s at line %d of followme.conf\n", f->name, param, linenum);
247                 else
248                         ast_log(LOG_WARNING, "Unknown keyword in profile '%s': %s\n", f->name, param);
249         }
250 }
251
252 /*! \brief Add a new number */
253 static struct number *create_followme_number(char *number, int timeout, int numorder)
254 {
255         struct number *cur;
256         char *tmp;
257         
258
259         if (!(cur = ast_calloc(1, sizeof(*cur))))
260                 return NULL;
261
262         cur->timeout = timeout;
263         if ((tmp = strchr(number, ','))) 
264                 *tmp = '\0';
265         ast_copy_string(cur->number, number, sizeof(cur->number));
266         cur->order = numorder;
267         ast_debug(1, "Created a number, %s, order of , %d, with a timeout of %ld.\n", cur->number, cur->order, cur->timeout);
268
269         return cur;
270 }
271
272 /*! \brief Reload followme application module */
273 static int reload_followme(int reload)
274 {
275         struct call_followme *f;
276         struct ast_config *cfg;
277         char *cat = NULL, *tmp;
278         struct ast_variable *var;
279         struct number *cur, *nm;
280         char numberstr[90];
281         int timeout;
282         char *timeoutstr;
283         int numorder;   
284         const char *takecallstr;
285         const char *declinecallstr;
286         const char *tmpstr;
287         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
288
289         if (!(cfg = ast_config_load("followme.conf", config_flags))) {
290                 ast_log(LOG_WARNING, "No follow me config file (followme.conf), so no follow me\n");
291                 return 0;
292         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
293                 return 0;
294
295         AST_RWLIST_WRLOCK(&followmes);
296
297         /* Reset Global Var Values */
298         featuredigittimeout = 5000;
299
300         /* Mark all profiles as inactive for the moment */
301         AST_RWLIST_TRAVERSE(&followmes, f, entry) {
302                 f->active = 0;
303         }
304
305         featuredigittostr = ast_variable_retrieve(cfg, "general", "featuredigittimeout");
306         
307         if (!ast_strlen_zero(featuredigittostr)) {
308                 if (!sscanf(featuredigittostr, "%d", &featuredigittimeout))
309                         featuredigittimeout = 5000;
310         }
311
312         takecallstr = ast_variable_retrieve(cfg, "general", "takecall");
313         if (!ast_strlen_zero(takecallstr))
314                 ast_copy_string(takecall, takecallstr, sizeof(takecall));
315         
316         declinecallstr = ast_variable_retrieve(cfg, "general", "declinecall");
317         if (!ast_strlen_zero(declinecallstr))
318                 ast_copy_string(nextindp, declinecallstr, sizeof(nextindp));
319
320         tmpstr = ast_variable_retrieve(cfg, "general", "call-from-prompt");
321         if (!ast_strlen_zero(tmpstr))
322                 ast_copy_string(callfromprompt, tmpstr, sizeof(callfromprompt));
323
324         tmpstr = ast_variable_retrieve(cfg, "general", "norecording-prompt");
325         if (!ast_strlen_zero(tmpstr))
326                 ast_copy_string(norecordingprompt, tmpstr, sizeof(norecordingprompt));
327
328         tmpstr = ast_variable_retrieve(cfg, "general", "options-prompt");
329         if (!ast_strlen_zero(tmpstr))
330                 ast_copy_string(optionsprompt, tmpstr, sizeof(optionsprompt));
331
332         tmpstr = ast_variable_retrieve(cfg, "general", "pls-hold-prompt");
333         if (!ast_strlen_zero(tmpstr))
334                 ast_copy_string(plsholdprompt, tmpstr, sizeof(plsholdprompt));
335
336         tmpstr = ast_variable_retrieve(cfg, "general", "status-prompt");
337         if (!ast_strlen_zero(tmpstr))
338                 ast_copy_string(statusprompt, tmpstr, sizeof(statusprompt));
339
340         tmpstr = ast_variable_retrieve(cfg, "general", "sorry-prompt");
341         if (!ast_strlen_zero(tmpstr))
342                 ast_copy_string(sorryprompt, tmpstr, sizeof(sorryprompt));
343
344         /* Chug through config file */
345         while ((cat = ast_category_browse(cfg, cat))) {
346                 int new = 0;
347
348                 if (!strcasecmp(cat, "general"))
349                         continue;
350
351                 /* Look for an existing one */
352                 AST_LIST_TRAVERSE(&followmes, f, entry) {
353                         if (!strcasecmp(f->name, cat))
354                                 break;
355                 }
356
357                 ast_debug(1, "New profile %s.\n", cat);
358
359                 if (!f) {
360                         /* Make one then */
361                         f = alloc_profile(cat);
362                         new = 1;
363                 }
364
365                 /* Totally fail if we fail to find/create an entry */
366                 if (!f)
367                         continue;
368                 
369                 if (!new)
370                         ast_mutex_lock(&f->lock);
371                 /* Re-initialize the profile */
372                 init_profile(f);
373                 free_numbers(f);
374                 var = ast_variable_browse(cfg, cat);
375                 while(var) {
376                         if (!strcasecmp(var->name, "number")) {
377                                 int idx = 0;
378
379                                 /* Add a new number */
380                                 ast_copy_string(numberstr, var->value, sizeof(numberstr));
381                                 if ((tmp = strchr(numberstr, ','))) {
382                                         *tmp++ = '\0';
383                                         timeoutstr = ast_strdupa(tmp);
384                                         if ((tmp = strchr(timeoutstr, ','))) {
385                                                 *tmp++ = '\0';
386                                                 numorder = atoi(tmp);
387                                                 if (numorder < 0)
388                                                         numorder = 0;
389                                         } else 
390                                                 numorder = 0;
391                                         timeout = atoi(timeoutstr);
392                                         if (timeout < 0) 
393                                                 timeout = 25;
394                                 } else {
395                                         timeout = 25;
396                                         numorder = 0;
397                                 }
398                                 
399                                 if (!numorder) {        
400                                         idx = 1;
401                                         AST_LIST_TRAVERSE(&f->numbers, nm, entry) 
402                                                 idx++;
403                                         numorder = idx;
404                                 }
405                                 cur = create_followme_number(numberstr, timeout, numorder);
406                                 AST_LIST_INSERT_TAIL(&f->numbers, cur, entry);
407                         } else {
408                                 profile_set_param(f, var->name, var->value, var->lineno, 1);
409                                 ast_debug(2, "Logging parameter %s with value %s from lineno %d\n", var->name, var->value, var->lineno);
410                         }
411                         var = var->next;
412                 } /* End while(var) loop */
413                 
414                 if (!new) 
415                         ast_mutex_unlock(&f->lock);
416                 else
417                         AST_RWLIST_INSERT_HEAD(&followmes, f, entry);
418         }
419
420         ast_config_destroy(cfg);
421
422         AST_RWLIST_UNLOCK(&followmes);
423
424         return 1;
425 }
426
427 static void clear_caller(struct findme_user *tmpuser)
428 {
429         struct ast_channel *outbound;
430         
431         if (tmpuser && tmpuser->ochan && tmpuser->state >= 0) {
432                 outbound = tmpuser->ochan;
433                 if (!outbound->cdr) {
434                         outbound->cdr = ast_cdr_alloc();
435                         if (outbound->cdr)
436                                 ast_cdr_init(outbound->cdr, outbound);
437                 }
438                 if (outbound->cdr) {
439                         char tmp[256];
440
441                         snprintf(tmp, sizeof(tmp), "%s/%s", "Local", tmpuser->dialarg);
442                         ast_cdr_setapp(outbound->cdr, "FollowMe", tmp);
443                         ast_cdr_update(outbound);
444                         ast_cdr_start(outbound->cdr);
445                         ast_cdr_end(outbound->cdr);
446                         /* If the cause wasn't handled properly */
447                         if (ast_cdr_disposition(outbound->cdr, outbound->hangupcause))
448                                 ast_cdr_failed(outbound->cdr);
449                 } else
450                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
451                 ast_hangup(tmpuser->ochan);
452         }
453
454 }
455
456 static void clear_calling_tree(struct findme_user_listptr *findme_user_list) 
457 {
458         struct findme_user *tmpuser;
459         
460         AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry) {
461                 clear_caller(tmpuser);
462                 tmpuser->cleared = 1;
463         }
464         
465 }
466
467
468
469 static struct ast_channel *wait_for_winner(struct findme_user_listptr *findme_user_list, struct number *nm, struct ast_channel *caller, char *namerecloc, int *status, struct fm_args *tpargs) 
470 {
471         struct ast_channel *watchers[256];
472         int pos;
473         struct ast_channel *winner;
474         struct ast_frame *f;
475         int ctstatus = 0;
476         int dg;
477         struct findme_user *tmpuser;
478         int to = 0;
479         int livechannels = 0;
480         int tmpto;
481         long totalwait = 0, wtd = 0, towas = 0;
482         char *callfromname;
483         char *pressbuttonname;
484
485         /* ------------ wait_for_winner_channel start --------------- */ 
486
487         callfromname = ast_strdupa(tpargs->callfromprompt);
488         pressbuttonname = ast_strdupa(tpargs->optionsprompt);   
489
490         if (AST_LIST_EMPTY(findme_user_list)) {
491                 ast_verb(3, "couldn't reach at this number.\n");
492                 return NULL;
493         }
494         
495         if (!caller) {
496                 ast_verb(3, "Original caller hungup. Cleanup.\n");
497                 clear_calling_tree(findme_user_list);
498                 return NULL;
499         }
500         
501         totalwait = nm->timeout * 1000;
502         
503         while (!ctstatus) {
504                 to = 1000;
505                 pos = 1; 
506                 livechannels = 0;
507                 watchers[0] = caller;
508                 
509                 dg = 0; 
510                 winner = NULL;  
511                 AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry) {
512                         if (tmpuser->state >= 0 && tmpuser->ochan) {
513                                 if (tmpuser->state == 3) 
514                                         tmpuser->digts += (towas - wtd);
515                                 if (tmpuser->digts && (tmpuser->digts > featuredigittimeout)) {
516                                         ast_verb(3, "We've been waiting for digits longer than we should have.\n");
517                                         if (!ast_strlen_zero(namerecloc)) {
518                                                 tmpuser->state = 1;
519                                                 tmpuser->digts = 0;
520                                                 if (!ast_streamfile(tmpuser->ochan, callfromname, tmpuser->ochan->language)) {
521                                                         ast_sched_runq(tmpuser->ochan->sched);
522                                                 } else {
523                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", callfromname);
524                                                         return NULL;
525                                                 }                                                       
526                                         } else {
527                                                 tmpuser->state = 2;
528                                                 tmpuser->digts = 0;
529                                                 if (!ast_streamfile(tmpuser->ochan, tpargs->norecordingprompt, tmpuser->ochan->language))
530                                                         ast_sched_runq(tmpuser->ochan->sched);
531                                                 else {
532                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", tpargs->norecordingprompt);
533                                                         return NULL;
534                                                 }
535                                         }
536                                 }
537                                 if (tmpuser->ochan->stream) {
538                                         ast_sched_runq(tmpuser->ochan->sched);
539                                         tmpto = ast_sched_wait(tmpuser->ochan->sched);
540                                         if (tmpto > 0 && tmpto < to)
541                                                 to = tmpto;
542                                         else if (tmpto < 0 && !tmpuser->ochan->timingfunc) {
543                                                 ast_stopstream(tmpuser->ochan);
544                                                 if (tmpuser->state == 1) {
545                                                         ast_verb(3, "Playback of the call-from file appears to be done.\n");
546                                                         if (!ast_streamfile(tmpuser->ochan, namerecloc, tmpuser->ochan->language)) {
547                                                                 tmpuser->state = 2;
548                                                         } else {
549                                                                 ast_log(LOG_NOTICE, "Unable to playback %s. Maybe the caller didn't record their name?\n", namerecloc);
550                                                                 memset(tmpuser->yn, 0, sizeof(tmpuser->yn));
551                                                                 tmpuser->ynidx = 0;
552                                                                 if (!ast_streamfile(tmpuser->ochan, pressbuttonname, tmpuser->ochan->language))
553                                                                         tmpuser->state = 3;
554                                                                 else {
555                                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", pressbuttonname);
556                                                                         return NULL;
557                                                                 } 
558                                                         }
559                                                 } else if (tmpuser->state == 2) {
560                                                         ast_verb(3, "Playback of name file appears to be done.\n");
561                                                         memset(tmpuser->yn, 0, sizeof(tmpuser->yn));
562                                                         tmpuser->ynidx = 0;
563                                                         if (!ast_streamfile(tmpuser->ochan, pressbuttonname, tmpuser->ochan->language)) {
564                                                                 tmpuser->state = 3;
565                                                                 
566                                                         } else {
567                                                                 return NULL;
568                                                         } 
569                                                 } else if (tmpuser->state == 3) {
570                                                         ast_verb(3, "Playback of the next step file appears to be done.\n");
571                                                         tmpuser->digts = 0;
572                                                 }
573                                         }
574                                 }
575                                 watchers[pos++] = tmpuser->ochan;
576                                 livechannels++;
577                         }
578                 }
579                 
580                 tmpto = to;
581                 if (to < 0) {
582                         to = 1000;
583                         tmpto = 1000;
584                 }
585                 towas = to;
586                 winner = ast_waitfor_n(watchers, pos, &to);
587                 tmpto -= to;
588                 totalwait -= tmpto;
589                 wtd = to;       
590                 if (totalwait <= 0) {
591                         ast_verb(3, "We've hit our timeout for this step. Drop everyone and move on to the next one. %ld\n", totalwait);
592                         clear_calling_tree(findme_user_list);
593                         return NULL;
594                 }
595                 if (winner) {
596                         /* Need to find out which channel this is */
597                         dg = 0;
598                         while ((winner != watchers[dg]) && (dg < 256))
599                                 dg++;
600                         AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry)
601                                 if (tmpuser->ochan == winner)
602                                         break;
603                         f = ast_read(winner);
604                         if (f) {
605                                 if (f->frametype == AST_FRAME_CONTROL) {
606                                         switch(f->subclass) {
607                                         case AST_CONTROL_HANGUP:
608                                                 if (option_verbose > 2)
609                                                         ast_verb(3, "%s received a hangup frame.\n", winner->name);
610                                                 if (dg == 0) {
611                                                         ast_verb(3, "The calling channel hungup. Need to drop everyone else.\n");
612                                                         clear_calling_tree(findme_user_list);
613                                                         ctstatus = -1;
614                                                 }
615                                                 break;
616                                         case AST_CONTROL_ANSWER:
617                                                 if (option_verbose > 2)
618                                                         ast_verb(3, "%s answered %s\n", winner->name, caller->name);
619                                                 /* If call has been answered, then the eventual hangup is likely to be normal hangup */ 
620                                                 winner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
621                                                 caller->hangupcause = AST_CAUSE_NORMAL_CLEARING;
622                                                 ast_verb(3, "Starting playback of %s\n", callfromname);
623                                                 if (dg > 0) {
624                                                         if (!ast_strlen_zero(namerecloc)) {
625                                                                 if (!ast_streamfile(winner, callfromname, winner->language)) {
626                                                                         ast_sched_runq(winner->sched);
627                                                                         tmpuser->state = 1;
628                                                                 } else {
629                                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", callfromname);
630                                                                         ast_frfree(f);
631                                                                         return NULL;
632                                                                 }                               
633                                                         } else {                        
634                                                                 tmpuser->state = 2;
635                                                                 if (!ast_streamfile(tmpuser->ochan, tpargs->norecordingprompt, tmpuser->ochan->language))
636                                                                         ast_sched_runq(tmpuser->ochan->sched);
637                                                                 else {
638                                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", tpargs->norecordingprompt);
639                                                                         ast_frfree(f);
640                                                                         return NULL;
641                                                                 }
642                                                         }
643                                                 }
644                                                 break;
645                                         case AST_CONTROL_BUSY:
646                                                 ast_verb(3, "%s is busy\n", winner->name);
647                                                 break;
648                                         case AST_CONTROL_CONGESTION:
649                                                 ast_verb(3, "%s is circuit-busy\n", winner->name);
650                                                 break;
651                                         case AST_CONTROL_RINGING:
652                                                 ast_verb(3, "%s is ringing\n", winner->name);
653                                                 break;
654                                         case AST_CONTROL_PROGRESS:
655                                                 ast_verb(3, "%s is making progress passing it to %s\n", winner->name, caller->name);
656                                                 break;
657                                         case AST_CONTROL_VIDUPDATE:
658                                                 ast_verb(3, "%s requested a video update, passing it to %s\n", winner->name, caller->name);
659                                                 break;
660                                         case AST_CONTROL_PROCEEDING:
661                                                 ast_verb(3, "%s is proceeding passing it to %s\n", winner->name,caller->name);
662                                                 break;
663                                         case AST_CONTROL_HOLD:
664                                                 ast_verb(3, "Call on %s placed on hold\n", winner->name);
665                                                 break;
666                                         case AST_CONTROL_UNHOLD:
667                                                 ast_verb(3, "Call on %s left from hold\n", winner->name);
668                                                 break;
669                                         case AST_CONTROL_OFFHOOK:
670                                         case AST_CONTROL_FLASH:
671                                                 /* Ignore going off hook and flash */
672                                                 break;
673                                         case -1:
674                                                 ast_verb(3, "%s stopped sounds\n", winner->name);
675                                                 break;
676                                         default:
677                                                 ast_debug(1, "Dunno what to do with control type %d\n", f->subclass);
678                                                 break;
679                                         }
680                                 } 
681                                 if (tmpuser && tmpuser->state == 3 && f->frametype == AST_FRAME_DTMF) {
682                                         if (winner->stream)
683                                                 ast_stopstream(winner);
684                                         tmpuser->digts = 0;
685                                         ast_debug(1, "DTMF received: %c\n",(char) f->subclass);
686                                         tmpuser->yn[tmpuser->ynidx] = (char) f->subclass;
687                                         tmpuser->ynidx++;
688                                         ast_debug(1, "DTMF string: %s\n", tmpuser->yn);
689                                         if (tmpuser->ynidx >= ynlongest) {
690                                                 ast_debug(1, "reached longest possible match - doing evals\n");
691                                                 if (!strcmp(tmpuser->yn, tpargs->takecall)) {
692                                                         ast_debug(1, "Match to take the call!\n");
693                                                         ast_frfree(f);
694                                                         return tmpuser->ochan;  
695                                                 }
696                                                 if (!strcmp(tmpuser->yn, tpargs->nextindp)) {
697                                                         ast_debug(1, "Next in dial plan step requested.\n");
698                                                         *status = 1;
699                                                         ast_frfree(f);
700                                                         return NULL;
701                                                 }       
702                                                 
703                                         }
704                                 }
705                                 
706                                 ast_frfree(f);
707                         } else {
708                                 if (winner) {
709                                         ast_debug(1, "we didn't get a frame. hanging up. dg is %d\n",dg);                                             
710                                         if (!dg) {
711                                                 clear_calling_tree(findme_user_list);
712                                                 return NULL;
713                                         } else {
714                                                 tmpuser->state = -1;
715                                                 ast_hangup(winner);  
716                                                 livechannels--;
717                                                 ast_debug(1, "live channels left %d\n", livechannels);
718                                                 if (!livechannels) {
719                                                         ast_verb(3, "no live channels left. exiting.\n");
720                                                         return NULL;
721                                                 }
722                                         }
723                                 }
724                         }                                       
725                         
726                 } else
727                         ast_debug(1, "timed out waiting for action\n");
728         }
729         
730         /* --- WAIT FOR WINNER NUMBER END! -----------*/
731         return NULL;
732 }
733
734 static void findmeexec(struct fm_args *tpargs)
735 {
736         struct number *nm;
737         struct ast_channel *outbound;
738         struct ast_channel *caller;
739         struct ast_channel *winner = NULL;
740         char dialarg[512];
741         int dg, idx;
742         char *rest, *number;
743         struct findme_user *tmpuser;
744         struct findme_user *fmuser;
745         struct findme_user *headuser;
746         struct findme_user_listptr *findme_user_list;
747         int status;
748
749         findme_user_list = ast_calloc(1, sizeof(*findme_user_list));            
750         AST_LIST_HEAD_INIT_NOLOCK(findme_user_list);
751
752         /* We're going to figure out what the longest possible string of digits to collect is */
753         ynlongest = 0;
754         if (strlen(tpargs->takecall) > ynlongest)
755                 ynlongest = strlen(tpargs->takecall);
756         if (strlen(tpargs->nextindp) > ynlongest)
757                 ynlongest = strlen(tpargs->nextindp);
758
759         idx = 1;
760         caller = tpargs->chan;
761         AST_LIST_TRAVERSE(&tpargs->cnumbers, nm, entry)
762                 if (nm->order == idx)
763                         break;
764
765         while (nm) {
766
767                 ast_debug(2, "Number %s timeout %ld\n", nm->number,nm->timeout);
768                 time(&start_time);
769
770                 number = ast_strdupa(nm->number);
771                 ast_debug(3, "examining %s\n", number);
772                 do {
773                         rest = strchr(number, '&');
774                         if (rest) {
775                                 *rest = 0;
776                                 rest++;
777                         }
778
779                         if (!strcmp(tpargs->context, ""))
780                                 sprintf(dialarg, "%s", number);
781                         else
782                                 sprintf(dialarg, "%s@%s", number, tpargs->context);
783                                         
784                         tmpuser = ast_calloc(1, sizeof(*tmpuser));
785                         if (!tmpuser) {
786                                 ast_log(LOG_WARNING, "Out of memory!\n");
787                                 ast_free(findme_user_list);
788                                 return;
789                         }
790                                         
791                         outbound = ast_request("Local", ast_best_codec(caller->nativeformats), dialarg, &dg);
792                         if (outbound) {
793                                 ast_set_callerid(outbound, caller->cid.cid_num, caller->cid.cid_name, caller->cid.cid_num);
794                                 ast_channel_inherit_variables(tpargs->chan, outbound);
795                                 ast_verb(3, "calling %s\n", dialarg);
796                                 if (!ast_call(outbound,dialarg,0)) {
797                                         tmpuser->ochan = outbound;
798                                         tmpuser->state = 0;
799                                         tmpuser->cleared = 0;
800                                         ast_copy_string(tmpuser->dialarg, dialarg, sizeof(dialarg));
801                                         AST_LIST_INSERT_TAIL(findme_user_list, tmpuser, entry);
802                                 } else {
803                                         ast_verb(3, "couldn't reach at this number.\n"); 
804                                         if (outbound) {
805                                                 if (!outbound->cdr) 
806                                                         outbound->cdr = ast_cdr_alloc();
807                                                 if (outbound->cdr) {
808                                                         char tmp[256];
809
810                                                         ast_cdr_init(outbound->cdr, outbound);
811                                                         snprintf(tmp, sizeof(tmp), "%s/%s", "Local", dialarg);
812                                                         ast_cdr_setapp(outbound->cdr, "FollowMe", tmp);
813                                                         ast_cdr_update(outbound);
814                                                         ast_cdr_start(outbound->cdr);
815                                                         ast_cdr_end(outbound->cdr);
816                                                         /* If the cause wasn't handled properly */
817                                                         if (ast_cdr_disposition(outbound->cdr,outbound->hangupcause))
818                                                                 ast_cdr_failed(outbound->cdr);
819                                                 } else {
820                                                         ast_log(LOG_ERROR, "Unable to create Call Detail Record\n");
821                                                         ast_hangup(outbound);
822                                                         outbound = NULL;
823                                                 }
824                                         }
825                                                 
826                                 }
827                         } else 
828                                 ast_log(LOG_WARNING, "Unable to allocate a channel for Local/%s cause: %s\n", dialarg, ast_cause2str(dg));
829                                         
830                         number = rest;
831                 } while (number);
832                                 
833                 status = 0;     
834                 if (!AST_LIST_EMPTY(findme_user_list))
835                         winner = wait_for_winner(findme_user_list, nm, caller, tpargs->namerecloc, &status, tpargs);
836                 
837                                         
838                 while ((fmuser = AST_LIST_REMOVE_HEAD(findme_user_list, entry))) {
839                         if (!fmuser->cleared && fmuser->ochan != winner)
840                                 clear_caller(fmuser);
841                         ast_free(fmuser);
842                 }
843
844                 fmuser = NULL;
845                 tmpuser = NULL;
846                 headuser = NULL;        
847                 if (winner)
848                         break;
849
850                 if (!caller) {
851                         tpargs->status = 1;
852                         ast_free(findme_user_list);
853                         return; 
854                 }
855
856                 idx++;
857                 AST_LIST_TRAVERSE(&tpargs->cnumbers, nm, entry)
858                         if (nm->order == idx)
859                                 break;
860
861         }
862         ast_free(findme_user_list);
863         if (!winner) 
864                 tpargs->status = 1;
865         else {
866                 tpargs->status = 100;
867                 tpargs->outbound = winner;
868         }
869
870         
871         return;
872                 
873 }
874
875 static int app_exec(struct ast_channel *chan, void *data)
876 {
877         struct fm_args targs;
878         struct ast_bridge_config config;
879         struct call_followme *f;
880         struct number *nm, *newnm;
881         int res = 0;
882         char *argstr;
883         char namerecloc[255];
884         int duration = 0;
885         struct ast_channel *caller;
886         struct ast_channel *outbound;
887         static char toast[80];
888         
889         AST_DECLARE_APP_ARGS(args,
890                 AST_APP_ARG(followmeid);
891                 AST_APP_ARG(options);
892         );
893
894         if (ast_strlen_zero(data)) {
895                 ast_log(LOG_WARNING, "%s requires an argument (followmeid)\n", app);
896                 return -1;
897         }
898         
899         if (!(argstr = ast_strdupa((char *)data))) {
900                 ast_log(LOG_ERROR, "Out of memory!\n");
901                 return -1;
902         }
903
904         AST_STANDARD_APP_ARGS(args, argstr);
905
906         if (ast_strlen_zero(args.followmeid)) {
907                 ast_log(LOG_WARNING, "%s requires an argument (followmeid)\n", app);
908                 return -1;
909         }
910
911         AST_RWLIST_RDLOCK(&followmes);
912         AST_RWLIST_TRAVERSE(&followmes, f, entry) {
913                 if (!strcasecmp(f->name, args.followmeid) && (f->active))
914                         break;
915         }
916         AST_RWLIST_UNLOCK(&followmes);
917         
918         ast_debug(1, "New profile %s.\n", args.followmeid);
919
920         if (!f) {
921                 ast_log(LOG_WARNING, "Profile requested, %s, not found in the configuration.\n", args.followmeid);
922                 return 0;
923         }
924
925         /* XXX TODO: Reinsert the db check value to see whether or not follow-me is on or off */
926         if (args.options) 
927                 ast_app_parse_options(followme_opts, &targs.followmeflags, NULL, args.options);
928         
929         /* Lock the profile lock and copy out everything we need to run with before unlocking it again */
930         ast_mutex_lock(&f->lock);
931         targs.mohclass = ast_strdupa(f->moh);
932         ast_copy_string(targs.context, f->context, sizeof(targs.context));
933         ast_copy_string(targs.takecall, f->takecall, sizeof(targs.takecall));
934         ast_copy_string(targs.nextindp, f->nextindp, sizeof(targs.nextindp));
935         ast_copy_string(targs.callfromprompt, f->callfromprompt, sizeof(targs.callfromprompt));
936         ast_copy_string(targs.norecordingprompt, f->norecordingprompt, sizeof(targs.norecordingprompt));
937         ast_copy_string(targs.optionsprompt, f->optionsprompt, sizeof(targs.optionsprompt));
938         ast_copy_string(targs.plsholdprompt, f->plsholdprompt, sizeof(targs.plsholdprompt));
939         ast_copy_string(targs.statusprompt, f->statusprompt, sizeof(targs.statusprompt));
940         ast_copy_string(targs.sorryprompt, f->sorryprompt, sizeof(targs.sorryprompt));
941         /* Copy the numbers we're going to use into another list in case the master list should get modified 
942            (and locked) while we're trying to do a follow-me */
943         AST_LIST_HEAD_INIT_NOLOCK(&targs.cnumbers);
944         AST_LIST_TRAVERSE(&f->numbers, nm, entry) {
945                 newnm = create_followme_number(nm->number, nm->timeout, nm->order);
946                 AST_LIST_INSERT_TAIL(&targs.cnumbers, newnm, entry);
947         }
948         ast_mutex_unlock(&f->lock);
949         
950         if (ast_test_flag(&targs.followmeflags, FOLLOWMEFLAG_STATUSMSG)) 
951                 ast_stream_and_wait(chan, targs.statusprompt, "");
952         
953         snprintf(namerecloc,sizeof(namerecloc),"%s/followme.%s",ast_config_AST_SPOOL_DIR,chan->uniqueid);
954         duration = 5;
955         
956         if (ast_test_flag(&targs.followmeflags, FOLLOWMEFLAG_RECORDNAME)) 
957                 if (ast_play_and_record(chan, "vm-rec-name", namerecloc, 5, "sln", &duration, 128, 0, NULL) < 0)
958                         goto outrun;
959         
960         if (!ast_fileexists(namerecloc, NULL, chan->language))
961                 ast_copy_string(namerecloc, "", sizeof(namerecloc));                                    
962         
963         if (ast_streamfile(chan, targs.plsholdprompt, chan->language))
964                 goto outrun;
965         if (ast_waitstream(chan, "") < 0)
966                 goto outrun;
967         ast_moh_start(chan, S_OR(targs.mohclass, NULL), NULL);
968         
969         targs.status = 0;
970         targs.chan = chan;
971         ast_copy_string(targs.namerecloc, namerecloc, sizeof(targs.namerecloc));
972         
973         findmeexec(&targs);             
974         
975         while ((nm = AST_LIST_REMOVE_HEAD(&targs.cnumbers, entry)))
976                 ast_free(nm);
977                 
978         if (!ast_strlen_zero(namerecloc))
979                 unlink(namerecloc);     
980         
981         if (targs.status != 100) {
982                 ast_moh_stop(chan);
983                 if (ast_test_flag(&targs.followmeflags, FOLLOWMEFLAG_UNREACHABLEMSG)) 
984                         ast_stream_and_wait(chan, targs.sorryprompt, "");
985                 res = 0;
986         } else {
987                 caller = chan;
988                 outbound = targs.outbound;
989                 /* Bridge the two channels. */
990                 
991                 memset(&config,0,sizeof(struct ast_bridge_config));
992                 ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
993                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
994                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
995                 
996                 ast_moh_stop(caller);
997                 /* Be sure no generators are left on it */
998                 ast_deactivate_generator(caller);
999                 /* Make sure channels are compatible */
1000                 res = ast_channel_make_compatible(caller, outbound);
1001                 if (res < 0) {
1002                         ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", caller->name, outbound->name);
1003                         ast_hangup(outbound);
1004                         goto outrun;
1005                 }
1006                 time(&answer_time);
1007                 res = ast_bridge_call(caller,outbound,&config);
1008                 time(&end_time);
1009                 snprintf(toast, sizeof(toast), "%ld", (long)(end_time - start_time));
1010                 pbx_builtin_setvar_helper(caller, "DIALEDTIME", toast);
1011                 snprintf(toast, sizeof(toast), "%ld", (long)(end_time - answer_time));
1012                 pbx_builtin_setvar_helper(caller, "ANSWEREDTIME", toast);
1013                 if (outbound)
1014                         ast_hangup(outbound);
1015                 res = 1;
1016         }
1017
1018         outrun:
1019         
1020         return res;
1021 }
1022
1023 static int unload_module(void)
1024 {
1025         struct call_followme *f;
1026
1027         ast_unregister_application(app);
1028
1029         /* Free Memory. Yeah! I'm free! */
1030         AST_RWLIST_WRLOCK(&followmes);
1031         while ((f = AST_RWLIST_REMOVE_HEAD(&followmes, entry))) {
1032                 free_numbers(f);
1033                 ast_free(f);
1034         }
1035
1036         AST_RWLIST_UNLOCK(&followmes);
1037
1038         return 0;
1039 }
1040
1041 static int load_module(void)
1042 {
1043         if(!reload_followme(0))
1044                 return AST_MODULE_LOAD_DECLINE;
1045
1046         return ast_register_application(app, app_exec, synopsis, descrip);
1047 }
1048
1049 static int reload(void)
1050 {
1051         reload_followme(1);
1052
1053         return 0;       
1054 }
1055
1056 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Find-Me/Follow-Me Application",
1057                 .load = load_module,
1058                 .unload = unload_module,
1059                 .reload = reload,
1060                );