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