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