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