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