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