move a variable declaration to the beginning of a block
[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 static 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 ((tmp = strchr(number, ','))) { 
268                         *tmp = '\0';
269                 }
270                 ast_copy_string(cur->number, number, sizeof(cur->number));
271                 cur->order = numorder;
272                 if (option_debug)
273                         ast_log(LOG_DEBUG, "Created a number, %s, order of , %d, with a timeout of %ld.\n", cur->number, cur->order, cur->timeout);
274         }
275
276         return cur;
277 }
278
279 static int reload_followme(void)
280 {
281         struct ast_call_followme *f;
282         struct ast_config *cfg;
283         char *cat, *tmp;
284         struct ast_variable *var;
285         struct number *cur, *nm;
286         int new, idx;
287         char numberstr[90];
288         int timeout;
289         char *timeoutstr;
290         int numorder;   
291         char *takecallstr;
292         char *declinecallstr;
293         char *tmpstr;
294
295         cfg = ast_config_load("followme.conf");
296         if (!cfg) {
297                 ast_log(LOG_WARNING, "No follow me config file (followme.conf), so no follow me\n");
298                 return 0;
299         }
300
301         AST_LIST_LOCK(&followmes);
302
303         /* Reset Global Var Values */
304         featuredigittimeout = 5000;
305
306         /* Mark all profiles as inactive for the moment */
307         AST_LIST_TRAVERSE(&followmes, f, entry) {
308                 f->active = 0;
309         }
310         featuredigittostr = ast_variable_retrieve(cfg, "general", "featuredigittimeout");
311         
312         if (!ast_strlen_zero(featuredigittostr)) 
313                 if (!scanf("%d", &featuredigittimeout))
314                         featuredigittimeout = 5000;
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", "followme-norecording-prompt");
329         if (!ast_strlen_zero(tmpstr))
330                 ast_copy_string(norecordingprompt, tmpstr, sizeof(norecordingprompt));
331
332         tmpstr = ast_variable_retrieve(cfg, "general", "followme-options-prompt");
333         if (!ast_strlen_zero(tmpstr))
334                 ast_copy_string(optionsprompt, tmpstr, sizeof(optionsprompt));
335
336         tmpstr = ast_variable_retrieve(cfg, "general", "followme-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", "followme-status-prompt");
341         if (!ast_strlen_zero(tmpstr))
342                 ast_copy_string(statusprompt, tmpstr, sizeof(statusprompt));
343
344         tmpstr = ast_variable_retrieve(cfg, "general", "followme-sorry-prompt");
345         if (!ast_strlen_zero(tmpstr))
346                 ast_copy_string(sorryprompt, tmpstr, sizeof(sorryprompt));
347
348         /* Chug through config file */
349         cat = ast_category_browse(cfg, NULL);
350         while(cat) {
351                 /* Define a new profile */
352                 /* Look for an existing one */
353                 AST_LIST_TRAVERSE(&followmes, f, entry) {
354                         if (!strcasecmp(f->name, cat))
355                                 break;
356                 }
357                 if (option_debug)
358                         ast_log(LOG_DEBUG, "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                                         if (option_debug)
408                                                 ast_log(LOG_DEBUG, "Logging parameter %s with value %s from lineno %d\n", var->name, var->value, var->lineno);
409                                 }
410                                 var = var->next;
411                         } /* End while(var) loop */
412
413                         if (!new) 
414                                 ast_mutex_unlock(&f->lock);
415                         if (new) {
416                                 AST_LIST_INSERT_HEAD(&followmes, f, entry);
417                         }
418                 }
419                 cat = ast_category_browse(cfg, cat);
420         }
421         ast_config_destroy(cfg);
422
423         AST_LIST_UNLOCK(&followmes);
424
425         return 1;
426 }
427
428 static void clear_caller(struct findme_user *tmpuser)
429 {
430         struct ast_channel *outbound;
431         
432         if (tmpuser && tmpuser->ochan && tmpuser->state >= 0) {
433                 outbound = tmpuser->ochan;
434                 if (!outbound->cdr) {
435                         outbound->cdr = ast_cdr_alloc();
436                         if (outbound->cdr)
437                                 ast_cdr_init(outbound->cdr, outbound);
438                 }
439                 if (outbound->cdr) {
440                         char tmp[256];
441                         snprintf(tmp, sizeof(tmp), "%s/%s", "Local", tmpuser->dialarg);
442                         ast_cdr_setapp(outbound->cdr,"FollowMe",tmp);
443                         ast_cdr_update(outbound);
444                         ast_cdr_start(outbound->cdr);
445                         ast_cdr_end(outbound->cdr);
446                         /* If the cause wasn't handled properly */
447                         if (ast_cdr_disposition(outbound->cdr,outbound->hangupcause))
448                                 ast_cdr_failed(outbound->cdr);
449                 } else
450                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
451                 ast_hangup(tmpuser->ochan);
452         }
453
454 }
455
456 static void clear_calling_tree(struct findme_user_listptr *findme_user_list) 
457 {
458         struct findme_user *tmpuser;
459         
460         AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry) {
461                 clear_caller(tmpuser);
462                 tmpuser->cleared = 1;
463         }
464         
465 }
466
467
468
469 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) 
470 {
471         struct ast_channel *watchers[256];
472         int pos;
473         struct ast_channel *winner;
474         struct ast_frame *f;
475         int ctstatus;
476         int dg;
477         struct findme_user *tmpuser;
478         int to = 0;
479         int livechannels = 0;
480         int tmpto;
481         long totalwait = 0, wtd, towas = 0;
482         char *callfromname;
483         char *pressbuttonname;
484
485         /* ------------ wait_for_winner_channel start --------------- */ 
486
487         callfromname = ast_strdupa(tpargs->callfromprompt);
488         pressbuttonname = ast_strdupa(tpargs->optionsprompt);   
489
490         if (!AST_LIST_EMPTY(findme_user_list))
491         {
492                 if (!caller) {
493                         if (option_verbose > 2)
494                                 ast_verbose(VERBOSE_PREFIX_3 "Original caller hungup. Cleanup.\n");
495                         clear_calling_tree(findme_user_list);
496                         return NULL;
497                 }
498                 ctstatus = 0;
499                 totalwait = nm->timeout * 1000;
500                 wtd = 0;
501                 while (!ctstatus) {
502                         to = 1000;
503                         pos = 1; 
504                         livechannels = 0;
505                         watchers[0] = caller;
506                 
507                         dg = 0; 
508                         winner = NULL;  
509                         AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry) {
510                                 if (tmpuser->state >= 0 && tmpuser->ochan) {
511                                         if (tmpuser->state == 3) {
512                                                 tmpuser->digts += (towas - wtd);
513                                         }
514                                         if (tmpuser->digts && (tmpuser->digts > featuredigittimeout)) {
515                                                 if (option_verbose > 2)
516                                                         ast_verbose(VERBOSE_PREFIX_3 "We've been waiting for digits longer than we should have.\n");
517                                                 if (!ast_strlen_zero(namerecloc)) {
518                                                         tmpuser->state = 1;
519                                                         tmpuser->digts = 0;
520                                                         if (!ast_streamfile(tmpuser->ochan, callfromname, tmpuser->ochan->language)) {
521                                                                 ast_sched_runq(tmpuser->ochan->sched);
522                                                         } else {
523                                                                 ast_log(LOG_WARNING, "Unable to playback %s.\n", callfromname);
524                                                                 return NULL;
525                                                         }                                                       
526                                                 } else {
527                                                         tmpuser->state = 2;
528                                                         tmpuser->digts = 0;
529                                                         if (!ast_streamfile(tmpuser->ochan, tpargs->norecordingprompt, tmpuser->ochan->language))
530                                                                 ast_sched_runq(tmpuser->ochan->sched);
531                                                         else {
532                                                                 ast_log(LOG_WARNING, "Unable to playback %s.\n", tpargs->norecordingprompt);
533                                                                 return NULL;
534                                                         }
535                                                 }
536                                         }
537                                         if (tmpuser->ochan->stream) {
538                                                 ast_sched_runq(tmpuser->ochan->sched);
539                                                 tmpto = ast_sched_wait(tmpuser->ochan->sched);
540                                                 if (tmpto > 0 && tmpto < to)
541                                                         to = tmpto;
542                                                 else if (tmpto < 0 && !tmpuser->ochan->timingfunc) {
543                                                         ast_stopstream(tmpuser->ochan);
544                                                         if (tmpuser->state == 1) {
545                                                                 if (option_verbose > 2)
546                                                                         ast_verbose(VERBOSE_PREFIX_3 "Playback of the call-from file appears to be done.\n");
547                                                                 if (!ast_streamfile(tmpuser->ochan, namerecloc, tmpuser->ochan->language)) {
548                                                                         tmpuser->state = 2;
549                                                                 } else {
550                                                                         ast_log(LOG_NOTICE, "Unable to playback %s. Maybe the caller didn't record their name?\n", namerecloc);
551                                                                         memset(tmpuser->yn, 0, sizeof(tmpuser->yn));
552                                                                         tmpuser->ynidx = 0;
553                                                                         if (!ast_streamfile(tmpuser->ochan, pressbuttonname, tmpuser->ochan->language))
554                                                                                 tmpuser->state = 3;
555                                                                         else {
556                                                                                 ast_log(LOG_WARNING, "Unable to playback %s.\n", pressbuttonname);
557                                                                                 return NULL;
558                                                                         } 
559                                                                 }
560                                                         } else if (tmpuser->state == 2) {
561                                                                 if (option_verbose > 2)
562                                                                         ast_verbose(VERBOSE_PREFIX_3 "Playback of name file appears to be done.\n");
563                                                                 memset(tmpuser->yn, 0, sizeof(tmpuser->yn));
564                                                                 tmpuser->ynidx = 0;
565                                                                 if (!ast_streamfile(tmpuser->ochan, pressbuttonname, tmpuser->ochan->language)) {
566                                                                         tmpuser->state = 3;
567                                                                         
568                                                                 } else {
569                                                                         return NULL;
570                                                                 } 
571                                                         } else if (tmpuser->state == 3) {
572                                                                 if (option_verbose > 2)
573                                                                         ast_verbose(VERBOSE_PREFIX_3 "Playback of the next step file appears to be done.\n");
574                                                                 tmpuser->digts = 0;
575                                                         }
576                                                 }
577                                         }
578                                 watchers[pos++] = tmpuser->ochan;
579                                 livechannels++;
580                                 }
581                         }
582
583                         tmpto = to;
584                         if (to < 0) {
585                                 to = 1000;
586                                 tmpto = 1000;
587                         }
588                         towas = to;
589                         winner = ast_waitfor_n(watchers, pos, &to);
590                         tmpto -= to;
591                         totalwait -= tmpto;
592                         wtd = to;       
593                         if (totalwait <= 0) {
594                                 if (option_verbose > 2) 
595                                         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);
596                                 clear_calling_tree(findme_user_list);
597                                 return NULL;
598                         }
599                         if (winner) {
600                                 /* Need to find out which channel this is */
601                                 dg = 0;
602                                 while ((winner != watchers[dg]) && (dg < 256))
603                                         dg++;
604                                 AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry)
605                                         if (tmpuser->ochan == winner)
606                                                 break;
607                                 f = ast_read(winner);
608                                 if (f) {
609                                         if (f->frametype == AST_FRAME_CONTROL) {
610                                                 switch(f->subclass) {
611                                                 case AST_CONTROL_HANGUP:
612                                                         if (option_verbose > 2)
613                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s received a hangup frame.\n", winner->name);
614                                                         if (dg == 0) {
615                                                                 if (option_verbose > 2)
616                                                                         ast_verbose( VERBOSE_PREFIX_3 "The calling channel hungup. Need to drop everyone else.\n");
617                                                                 clear_calling_tree(findme_user_list);
618                                                                 ctstatus = -1;
619                                                         }
620                                                         break;
621                                                 case AST_CONTROL_ANSWER:
622                                                         if (option_verbose > 2)
623                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", winner->name, caller->name);
624                                                         /* If call has been answered, then the eventual hangup is likely to be normal hangup */ 
625                                                         winner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
626                                                         caller->hangupcause = AST_CAUSE_NORMAL_CLEARING;
627                                                         if (option_verbose > 2)
628                                                                 ast_verbose( VERBOSE_PREFIX_3 "Starting playback of %s\n", callfromname);
629                                                         if (dg > 0) {
630                                                                 if (!ast_strlen_zero(namerecloc)) {
631                                                                         if (!ast_streamfile(winner, callfromname, winner->language)) {
632                                                                                 ast_sched_runq(winner->sched);
633                                                                                 tmpuser->state = 1;
634                                                                         } else {
635                                                                                 ast_log(LOG_WARNING, "Unable to playback %s.\n", callfromname);
636                                                                                 ast_frfree(f);
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                                                                                 ast_frfree(f);
646                                                                                 return NULL;
647                                                                         }
648                                                                 }
649                                                         }
650                                                         break;
651                                                 case AST_CONTROL_BUSY:
652                                                         if (option_verbose > 2)
653                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", winner->name);
654                                                         break;
655                                                 case AST_CONTROL_CONGESTION:
656                                                         if (option_verbose > 2)
657                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", winner->name);
658                                                         break;
659                                                 case AST_CONTROL_RINGING:
660                                                         if (option_verbose > 2)
661                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", winner->name);
662                                                         break;
663                                                 case AST_CONTROL_PROGRESS:
664                                                         if (option_verbose > 2)
665                                                                 ast_verbose ( VERBOSE_PREFIX_3 "%s is making progress passing it to %s\n", winner->name,caller->name);
666                                                         break;
667                                                 case AST_CONTROL_VIDUPDATE:
668                                                         if (option_verbose > 2)
669                                                                 ast_verbose ( VERBOSE_PREFIX_3 "%s requested a video update, passing it to %s\n", winner->name,caller->name);
670                                                         break;
671                                                 case AST_CONTROL_PROCEEDING:
672                                                         if (option_verbose > 2)
673                                                                 ast_verbose ( VERBOSE_PREFIX_3 "%s is proceeding passing it to %s\n", winner->name,caller->name);
674                                                         break;
675                                                 case AST_CONTROL_HOLD:
676                                                         if (option_verbose > 2)
677                                                                 ast_verbose(VERBOSE_PREFIX_3 "Call on %s placed on hold\n", winner->name);
678                                                         break;
679                                                 case AST_CONTROL_UNHOLD:
680                                                         if (option_verbose > 2)
681                                                                 ast_verbose(VERBOSE_PREFIX_3 "Call on %s left from hold\n", winner->name);
682                                                         break;
683                                                 case AST_CONTROL_OFFHOOK:
684                                                 case AST_CONTROL_FLASH:
685                                                         /* Ignore going off hook and flash */
686                                                         break;
687                                                 case -1:
688                                                         if (option_verbose > 2)
689                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s stopped sounds\n", winner->name);
690                                                         break;
691                                                 default:
692                                                         if (option_debug)
693                                                                 ast_log(LOG_DEBUG, "Dunno what to do with control type %d\n", f->subclass);
694                                                         break;
695                                                 }
696                                         } 
697                                         if (tmpuser && tmpuser->state == 3 && f->frametype == AST_FRAME_DTMF) {
698                                                 if (winner->stream)
699                                                         ast_stopstream(winner);
700                                                         tmpuser->digts = 0;
701                                                 if (option_debug)
702                                                         ast_log(LOG_DEBUG, "DTMF received: %c\n",(char) f->subclass);
703                                                 tmpuser->yn[tmpuser->ynidx] = (char) f->subclass;
704                                                 tmpuser->ynidx++;
705                                                 if (option_debug)
706                                                         ast_log(LOG_DEBUG, "DTMF string: %s\n", tmpuser->yn);
707                                                 if (tmpuser->ynidx >= ynlongest) {
708                                                         if (option_debug)
709                                                                 ast_log(LOG_DEBUG, "reached longest possible match - doing evals\n");
710                                                         if (!strcmp(tmpuser->yn, tpargs->takecall)) {
711                                                                 if (option_debug)
712                                                                         ast_log(LOG_DEBUG, "Match to take the call!\n");
713                                                                 ast_frfree(f);
714                                                                 return tmpuser->ochan;  
715                                                         }
716                                                         if (!strcmp(tmpuser->yn, tpargs->nextindp)) {
717                                                                 if (option_debug)
718                                                                         ast_log(LOG_DEBUG, "Next in dial plan step requested.\n");
719                                                                 *status = 1;
720                                                                 ast_frfree(f);
721                                                                 return NULL;
722                                                         }       
723
724                                                 }
725                                         }
726                                         
727                                         ast_frfree(f);
728                                 } else {
729                                         if (winner) {
730                                                 if (option_debug)
731                                                         ast_log(LOG_DEBUG, "we didn't get a frame. hanging up. dg is %d\n",dg);                                       
732                                                 if (!dg) {
733                                                         clear_calling_tree(findme_user_list);
734                                                         return NULL;
735                                                 } else {
736                                                         tmpuser->state = -1;
737                                                         ast_hangup(winner);  
738                                                         livechannels--;
739                                                         if (option_debug)
740                                                                 ast_log(LOG_DEBUG, "live channels left %d\n", livechannels);
741                                                         if (!livechannels) {
742                                                                 if (option_verbose > 2)
743                                                                         ast_verbose(VERBOSE_PREFIX_3 "no live channels left. exiting.\n");
744                                                                 return NULL;
745                                                         }
746                                                 }
747                                         }
748                                 }                                       
749                                 
750                         } else
751                                 if (option_debug)
752                                         ast_log(LOG_DEBUG, "timed out waiting for action\n");
753                 }
754                 
755         }
756         else
757         {
758                 if (option_verbose > 2)
759                         ast_verbose(VERBOSE_PREFIX_3 "couldn't reach at this number.\n");
760         }
761         
762         /* --- WAIT FOR WINNER NUMBER END! -----------*/
763         return NULL;
764 }
765
766 static void findmeexec(struct fm_args *tpargs)
767 {
768         struct number *nm;
769         struct ast_channel *outbound;
770         struct ast_channel *caller;
771         struct ast_channel *winner = NULL;
772         char dialarg[512];
773         int dg, idx;
774         char *rest, *number;
775         struct findme_user *tmpuser;
776         struct findme_user *fmuser;
777         struct findme_user *headuser;
778         struct findme_user_listptr *findme_user_list;
779         int status;
780
781         findme_user_list = ast_calloc(1, sizeof(*findme_user_list));            
782         AST_LIST_HEAD_INIT_NOLOCK(findme_user_list);
783
784         /* We're going to figure out what the longest possible string of digits to collect is */
785         ynlongest = 0;
786         if (strlen(tpargs->takecall) > ynlongest)
787                 ynlongest = strlen(tpargs->takecall);
788         if (strlen(tpargs->nextindp) > ynlongest)
789                 ynlongest = strlen(tpargs->nextindp);
790
791         idx = 1;
792         caller = tpargs->chan;
793         AST_LIST_TRAVERSE(&tpargs->cnumbers, nm, entry)
794                 if (nm->order == idx)
795                         break;
796
797         while (nm) {
798
799                 if (option_debug)       
800                         ast_log(LOG_DEBUG, "Number %s timeout %ld\n",nm->number,nm->timeout);
801                 time(&start_time);
802
803                 number = ast_strdupa(nm->number);
804                 if (option_debug)
805                         ast_log(LOG_DEBUG, "examining %s\n", number);
806                 do {
807                         rest = strchr(number, '&');
808                         if (rest) {
809                                 *rest = 0;
810                                 rest++;
811                         }
812
813                         if (!strcmp(tpargs->context, ""))
814                                 sprintf(dialarg, "%s", number);
815                         else
816                                 sprintf(dialarg, "%s@%s", number, tpargs->context);
817                                         
818                         tmpuser = ast_calloc(1, sizeof(*tmpuser));
819                         if (!tmpuser) {
820                                 ast_log(LOG_WARNING, "Out of memory!\n");
821                                 return;
822                         }
823                                         
824                         outbound = ast_request("Local", ast_best_codec(caller->nativeformats), dialarg, &dg);
825                         if (outbound) {
826                                 ast_set_callerid(outbound, caller->cid.cid_num, caller->cid.cid_name, caller->cid.cid_num);
827                                 ast_channel_inherit_variables(tpargs->chan, outbound);
828                                 if (option_verbose > 2)
829                                         ast_verbose(VERBOSE_PREFIX_3 "calling %s\n", dialarg);
830                                 if (!ast_call(outbound,dialarg,0)) {
831                                         tmpuser->ochan = outbound;
832                                         tmpuser->state = 0;
833                                         tmpuser->cleared = 0;
834                                         ast_copy_string(tmpuser->dialarg, dialarg, sizeof(dialarg));
835                                         AST_LIST_INSERT_TAIL(findme_user_list, tmpuser, entry);
836                                 } else {
837                                         if (option_verbose > 2) 
838                                                 ast_verbose(VERBOSE_PREFIX_3 "couldn't reach at this number.\n"); 
839                                         if (outbound) {
840                                                 if (!outbound->cdr) {
841                                                         outbound->cdr = ast_cdr_alloc();
842                                                 }
843                                                 if (outbound->cdr) {
844                                                         char tmp[256];
845                                                         ast_cdr_init(outbound->cdr, outbound);
846                                                         snprintf(tmp, sizeof(tmp), "%s/%s", "Local", dialarg);
847                                                         ast_cdr_setapp(outbound->cdr, "FollowMe", tmp);
848                                                         ast_cdr_update(outbound);
849                                                         ast_cdr_start(outbound->cdr);
850                                                         ast_cdr_end(outbound->cdr);
851                                                         /* If the cause wasn't handled properly */
852                                                         if (ast_cdr_disposition(outbound->cdr,outbound->hangupcause))
853                                                                 ast_cdr_failed(outbound->cdr);
854                                                 } else {
855                                                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
856                                                         ast_hangup(outbound);
857                                                         outbound = NULL;
858                                                 }
859                                         }
860                                                 
861                                 }
862                         } else 
863                                 ast_log(LOG_WARNING, "Unable to allocate a channel for Local/%s cause: %s\n", dialarg, ast_cause2str(dg));
864                                         
865                         number = rest;
866                 } while (number);
867                                 
868                 status = 0;     
869                 if (!AST_LIST_EMPTY(findme_user_list))
870                         winner = wait_for_winner(findme_user_list, nm, caller, tpargs->namerecloc, &status, tpargs);
871                 
872                                         
873                 AST_LIST_TRAVERSE_SAFE_BEGIN(findme_user_list, fmuser, entry) {
874                         if (!fmuser->cleared && fmuser->ochan != winner)
875                                 clear_caller(fmuser);
876                         AST_LIST_REMOVE_CURRENT(findme_user_list, entry);
877                         free(fmuser);
878                 }
879                 AST_LIST_TRAVERSE_SAFE_END
880                 fmuser = NULL;
881                 tmpuser = NULL;
882                 headuser = NULL;        
883                 if (winner)
884                         break;
885
886                 if (!caller) {
887                         tpargs->status = 1;
888                         return; 
889                 }
890
891                 idx++;
892                 AST_LIST_TRAVERSE(&tpargs->cnumbers, nm, entry)
893                         if (nm->order == idx)
894                                 break;
895
896         }
897         free(findme_user_list);
898         if (!winner) 
899                 tpargs->status = 1;
900         else {
901                 tpargs->status = 100;
902                 tpargs->outbound = winner;
903         }
904
905         
906         return;
907                 
908 }
909
910 static int app_exec(struct ast_channel *chan, void *data)
911 {
912         struct fm_args targs;
913         struct ast_bridge_config config;
914         struct ast_call_followme *f;
915         struct number *nm, *newnm;
916         int res = 0;
917         struct localuser *u;
918         char *argstr;
919         char namerecloc[255];
920         int duration = 0;
921         struct ast_channel *caller;
922         struct ast_channel *outbound;
923         
924         AST_DECLARE_APP_ARGS(args,
925                 AST_APP_ARG(followmeid);
926                 AST_APP_ARG(options);
927         );
928         
929         if (!(argstr = ast_strdupa((char *)data))) {
930                 ast_log(LOG_ERROR, "Out of memory!\n");
931                 return -1;
932         }
933
934         if (!data) {
935                 ast_log(LOG_WARNING, "%s requires an argument (followmeid)\n",app);
936                 return -1;
937         }
938
939         LOCAL_USER_ADD(u);
940
941         AST_STANDARD_APP_ARGS(args, argstr);
942
943         if (!ast_strlen_zero(args.followmeid)) 
944         
945                         AST_LIST_LOCK(&followmes);
946                         AST_LIST_TRAVERSE(&followmes, f, entry) {
947                                 if (!strcasecmp(f->name, args.followmeid) && (f->active))
948                                         break;
949                         }
950                         AST_LIST_UNLOCK(&followmes);
951
952                         if (option_debug)
953                                 ast_log(LOG_DEBUG, "New profile %s.\n", args.followmeid);
954                         if (!f)
955                         { 
956                                 ast_log(LOG_WARNING, "Profile requested, %s, not found in the configuration.", args.followmeid);
957                                 res = -1;
958                         }
959                         else
960                         {
961         
962                                 /* XXX TODO: Reinsert the db check value to see whether or not follow-me is on or off */
963
964
965                                 if (args.options) {
966                                         ast_app_parse_options(followme_opts, &targs.followmeflags, NULL, args.options);
967                                 }
968
969                                 /* Lock the profile lock and copy out everything we need to run with before unlocking it again */
970                                 ast_mutex_lock(&f->lock);
971                                 targs.mohclass = ast_strdupa(f->moh);
972                                 ast_copy_string(targs.context, f->context, sizeof(targs.context));
973                                 ast_copy_string(targs.takecall, f->takecall, sizeof(targs.takecall));
974                                 ast_copy_string(targs.nextindp, f->nextindp, sizeof(targs.nextindp));
975                                 ast_copy_string(targs.callfromprompt, f->callfromprompt, sizeof(targs.callfromprompt));
976                                 ast_copy_string(targs.norecordingprompt, f->norecordingprompt, sizeof(targs.norecordingprompt));
977                                 ast_copy_string(targs.optionsprompt, f->optionsprompt, sizeof(targs.optionsprompt));
978                                 ast_copy_string(targs.plsholdprompt, f->plsholdprompt, sizeof(targs.plsholdprompt));
979                                 ast_copy_string(targs.statusprompt, f->statusprompt, sizeof(targs.statusprompt));
980                                 ast_copy_string(targs.sorryprompt, f->sorryprompt, sizeof(targs.sorryprompt));
981                                 /* Copy the numbers we're going to use into another list in case the master list should get modified 
982                                    (and locked) while we're trying to do a follow-me */
983                                 AST_LIST_HEAD_INIT_NOLOCK(&targs.cnumbers);
984                                 AST_LIST_TRAVERSE(&f->numbers, nm, entry) {
985                                         newnm = create_followme_number(nm->number, nm->timeout, nm->order);
986                                         AST_LIST_INSERT_TAIL(&targs.cnumbers, newnm, entry);
987                                 }
988                                 ast_mutex_unlock(&f->lock);
989
990                                 if (targs.followmeflags.flags & FOLLOWMEFLAG_STATUSMSG) 
991                                         ast_stream_and_wait(chan, targs.statusprompt, chan->language, "");
992
993                                 snprintf(namerecloc,sizeof(namerecloc),"%s/followme.%s",ast_config_AST_SPOOL_DIR,chan->uniqueid);
994                                 duration = 5;
995
996                                 if (targs.followmeflags.flags & FOLLOWMEFLAG_RECORDNAME) 
997                                         if (ast_play_and_record(chan, "vm-rec-name", namerecloc, 5, "sln", &duration, 128, 0, NULL) < 0)
998                                                 goto outrun;
999
1000                                 /* The following call looks like we're going to playback the file, but we're actually   */
1001                                 /* just checking to see if we *can* play it.                                            */
1002                                 if (ast_streamfile(chan, namerecloc, chan->language))
1003                                         ast_copy_string(namerecloc, "", sizeof(namerecloc));                                    
1004                                 else
1005                                         ast_stopstream(chan);
1006
1007                                 if (ast_streamfile(chan, targs.plsholdprompt, chan->language))
1008                                         goto outrun;
1009                                 if (ast_waitstream(chan, "") < 0)
1010                                         goto outrun;
1011                                 if (!strcmp(targs.mohclass, ""))
1012                                         ast_moh_start(chan, NULL);
1013                                 else
1014                                         ast_moh_start(chan, targs.mohclass);
1015
1016
1017                                 targs.status = 0;
1018                                 targs.chan = chan;
1019
1020                                 ast_copy_string(targs.namerecloc, namerecloc, sizeof(targs.namerecloc));
1021
1022                                 findmeexec(&targs);             
1023                                 
1024                                 AST_LIST_TRAVERSE_SAFE_BEGIN(&targs.cnumbers, nm, entry)        {
1025                                         AST_LIST_REMOVE_CURRENT(&targs.cnumbers, entry);
1026                                         free(nm);
1027                                 }
1028                                 AST_LIST_TRAVERSE_SAFE_END
1029         
1030                                 if (!ast_strlen_zero(namerecloc))
1031                                         unlink(namerecloc);     
1032
1033                                 if (targs.status != 100)
1034                                 {
1035                                         ast_moh_stop(chan);
1036                                         if (targs.followmeflags.flags & FOLLOWMEFLAG_UNREACHABLEMSG) 
1037                                                 ast_stream_and_wait(chan, targs.sorryprompt, chan->language, "");
1038                                         res = 0;
1039                                 }
1040                                 else
1041                                 {
1042                                                         
1043                                         caller = chan;
1044                                         outbound = targs.outbound;
1045                                         /* Bridge the two channels. */
1046
1047                                         memset(&config,0,sizeof(struct ast_bridge_config));
1048                                         ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
1049                                         ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
1050                                         ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
1051                                 
1052                                         ast_moh_stop(caller);
1053                                         /* Be sure no generators are left on it */
1054                                         ast_deactivate_generator(caller);
1055                                         /* Make sure channels are compatible */
1056                                         res = ast_channel_make_compatible(caller, outbound);
1057                                         if (res < 0) {
1058                                                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", caller->name, outbound->name);
1059                                                 ast_hangup(outbound);
1060                                                 goto outrun;
1061                                         }
1062                                         time(&answer_time);
1063                                         res = ast_bridge_call(caller,outbound,&config);
1064                                         time(&end_time);
1065                                         snprintf(toast, sizeof(toast), "%ld", (long)(end_time - start_time));
1066                                         pbx_builtin_setvar_helper(caller, "DIALEDTIME", toast);
1067                                         snprintf(toast, sizeof(toast), "%ld", (long)(end_time - answer_time));
1068                                         pbx_builtin_setvar_helper(caller, "ANSWEREDTIME", toast);
1069                                         if (outbound)
1070                                                 ast_hangup(outbound);
1071                                         res = 1;
1072                                         
1073                                 }
1074                                 
1075                         }
1076         outrun:
1077         
1078         LOCAL_USER_REMOVE(u);
1079         return res;
1080 }
1081
1082 static int unload_module(void *mod)
1083 {
1084         struct ast_call_followme *f;
1085         STANDARD_HANGUP_LOCALUSERS;
1086         ast_unregister_application(app);
1087         /* Free Memory. Yeah! I'm free! */
1088         AST_LIST_LOCK(&followmes);
1089         AST_LIST_TRAVERSE_SAFE_BEGIN(&followmes, f, entry) {
1090                 free_numbers(f);
1091                 AST_LIST_REMOVE_CURRENT(&followmes, entry);
1092                 free(f);
1093         }
1094         AST_LIST_TRAVERSE_SAFE_END
1095         AST_LIST_UNLOCK(&followmes);
1096         return 0;
1097 }
1098
1099 static int load_module(void *mod)
1100 {
1101         reload_followme();
1102         return ast_register_application(app, app_exec, synopsis, descrip);
1103 }
1104
1105 static const char *description(void)
1106 {
1107         return "Find-Me/Follow-Me Application";
1108 }
1109
1110 static int reload(void *mod)
1111 {
1112         reload_followme();
1113         return 0;       
1114 }
1115
1116 static const char *key(void)
1117 {
1118         return ASTERISK_GPL_KEY;
1119 }
1120
1121 STD_MOD(MOD_1, reload, NULL, NULL);