034efa0f17f70e71d3d746dc748b1b09839d0ebf
[asterisk/asterisk.git] / res / res_parking.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Routines implementing call parking
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <asterisk/file.h>
15 #include <asterisk/logger.h>
16 #include <asterisk/channel.h>
17 #include <asterisk/pbx.h>
18 #include <asterisk/options.h>
19 #include <asterisk/module.h>
20 #include <asterisk/translate.h>
21 #include <asterisk/say.h>
22 #include <asterisk/channel_pvt.h>
23 #include <asterisk/parking.h>
24 #include <stdlib.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <sys/time.h>
31 #include <sys/signal.h>
32 #include <netinet/in.h>
33
34 #include <pthread.h>
35
36 static char *parkedcall = "ParkedCall";
37
38 /* No more than 45 seconds parked before you do something with them */
39 static int parkingtime = 45000;
40
41 /* Context for which parking is made accessible */
42 static char parking_con[AST_MAX_EXTENSION] = "parkedcalls";
43
44 /* Extension you type to park the call */
45 static char parking_ext[AST_MAX_EXTENSION] = "700";
46
47 /* First available extension for parking */
48 static int parking_start = 701;
49
50 /* Last available extension for parking */
51 static int parking_stop = 750;
52
53 /* Registrar for operations */
54 static char *registrar = "res_parking";
55
56 static char *synopsis = "Answer a parked call";
57
58 static char *descrip = "ParkedCall(exten):"
59 "Used to connect to a parked call.  This Application is always\n"
60 "registered internally and does not need to be explicitly added\n"
61 "into the dialplan, although you should include the 'parkedcalls'\n"
62 "context.\n";
63
64 struct parkeduser {
65         struct ast_channel *chan;
66         struct timeval start;
67         int parkingnum;
68         /* Where to go if our parking time expires */
69         char context[AST_MAX_EXTENSION];
70         char exten[AST_MAX_EXTENSION];
71         int priority;
72         struct parkeduser *next;
73 };
74
75 static struct parkeduser *parkinglot;
76
77 static pthread_mutex_t parking_lock = PTHREAD_MUTEX_INITIALIZER;
78
79 static pthread_t parking_thread;
80
81 STANDARD_LOCAL_USER;
82
83 LOCAL_USER_DECL;
84
85 char *ast_parking_ext(void)
86 {
87         return parking_ext;
88 }
89
90 int ast_park_call(struct ast_channel *chan, struct ast_channel *peer)
91 {
92         /* We put the user in the parking list, then wake up the parking thread to be sure it looks
93            after these channels too */
94         struct parkeduser *pu, *cur;
95         int x;
96         pu = malloc(sizeof(struct parkeduser));
97         if (pu) {
98                 ast_pthread_mutex_lock(&parking_lock);
99                 for (x=parking_start;x<=parking_stop;x++) {
100                         cur = parkinglot;
101                         while(cur) {
102                                 if (cur->parkingnum == x) 
103                                         break;
104                                 cur = cur->next;
105                         }
106                         if (!cur)
107                                 break;
108                 }
109                 if (x <= parking_stop) {
110                         pu->chan = chan;
111                         gettimeofday(&pu->start, NULL);
112                         pu->parkingnum = x;
113                         /* Remember what had been dialed, so that if the parking
114                            expires, we try to come back to the same place */
115                         strncpy(pu->context, chan->context, sizeof(pu->context)-1);
116                         strncpy(pu->exten, chan->exten, sizeof(pu->exten)-1);
117                         pu->priority = chan->priority;
118                         pu->next = parkinglot;
119                         parkinglot = pu;
120                         ast_pthread_mutex_unlock(&parking_lock);
121                         /* Wake up the (presumably select()ing) thread */
122                         pthread_kill(parking_thread, SIGURG);
123                         if (option_verbose > 1) 
124                                 ast_verbose(VERBOSE_PREFIX_2 "Parked %s on %d\n", pu->chan->name, pu->parkingnum);
125                         ast_say_digits(peer, pu->parkingnum, "", peer->language);
126                         return 0;
127                 } else {
128                         ast_log(LOG_WARNING, "No more parking spaces\n");
129                         free(pu);
130                         ast_pthread_mutex_unlock(&parking_lock);
131                         return -1;
132                 }
133         } else {
134                 ast_log(LOG_WARNING, "Out of memory\n");
135                 return -1;
136         }
137         return 0;
138 }
139
140 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer)
141 {
142         struct ast_channel *chan;
143         struct ast_frame *f;
144         /* Make a new, fake channel that we'll use to masquerade in the real one */
145         chan = ast_channel_alloc();
146         if (chan) {
147                 /* Let us keep track of the channel name */
148                 snprintf(chan->name, sizeof (chan->name), "Parked/%s",rchan->name);
149                 /* Make formats okay */
150                 chan->readformat = rchan->readformat;
151                 chan->writeformat = rchan->writeformat;
152                 ast_channel_masquerade(chan, rchan);
153                 /* Setup the extensions and such */
154                 strncpy(chan->context, rchan->context, sizeof(chan->context) - 1);
155                 strncpy(chan->exten, rchan->exten, sizeof(chan->exten) - 1);
156                 chan->priority = rchan->priority;
157                 /* Make the masq execute */
158                 f = ast_read(chan);
159                 if (f)
160                         ast_frfree(f);
161                 ast_park_call(chan, peer);
162         } else {
163                 ast_log(LOG_WARNING, "Unable to create parked channel\n");
164                 return -1;
165         }
166         return 0;
167 }
168
169 int ast_bridge_call(struct ast_channel *chan, struct ast_channel *peer, int allowredirect)
170 {
171         /* Copy voice back and forth between the two channels.  Give the peer
172            the ability to transfer calls with '#<extension' syntax. */
173         int len;
174         struct ast_frame *f;
175         struct ast_channel *who;
176         char newext[256], *ptr;
177         int res;
178         struct ast_option_header *aoh;
179         /* Answer if need be */
180         if (chan->state != AST_STATE_UP) {
181                 if (ast_answer(chan))
182                         return -1;
183         }
184         peer->appl = "Bridged Call";
185         peer->data = chan->name;
186         for (;;) {
187                 res = ast_channel_bridge(chan, peer, allowredirect ? AST_BRIDGE_DTMF_CHANNEL_1 : 0, &f, &who);
188                 if (res < 0) {
189                         ast_log(LOG_WARNING, "Bridge failed on channels %s and %s\n", chan->name, peer->name);
190                         return -1;
191                 }
192                 
193                 if (!f || ((f->frametype == AST_FRAME_CONTROL) && ((f->subclass == AST_CONTROL_HANGUP) || (f->subclass == AST_CONTROL_BUSY) || 
194                         (f->subclass == AST_CONTROL_CONGESTION)))) {
195                                 res = -1;
196                                 break;
197                 }
198                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_RINGING)) {
199                         if (who == chan)
200                                 ast_indicate(peer, AST_CONTROL_RINGING);
201                         else
202                                 ast_indicate(chan, AST_CONTROL_RINGING);
203                 }
204                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_OPTION)) {
205                         aoh = f->data;
206                         /* Forward option Requests */
207                         if (aoh && (aoh->flag == AST_OPTION_FLAG_REQUEST)) {
208                                 if (who == chan)
209                                         ast_channel_setoption(peer, ntohs(aoh->option), aoh->data, f->datalen - sizeof(struct ast_option_header), 0);
210                                 else
211                                         ast_channel_setoption(chan, ntohs(aoh->option), aoh->data, f->datalen - sizeof(struct ast_option_header), 0);
212                         }
213                 }
214                 if ((f->frametype == AST_FRAME_DTMF) && (who == peer) && allowredirect &&
215                      (f->subclass == '#')) {
216                                 memset(newext, 0, sizeof(newext));
217                                 ptr = newext;
218                                         /* Transfer */
219                                 if ((res=ast_streamfile(peer, "pbx-transfer", chan->language)))
220                                         break;
221                                 if ((res=ast_waitstream(peer, AST_DIGIT_ANY)) < 0)
222                                         break;
223                                 ast_stopstream(peer);
224                                 if (res > 0) {
225                                         /* If they've typed a digit already, handle it */
226                                         newext[0] = res;
227                                         ptr++;
228                                         len --;
229                                 }
230                                 res = 0;
231                                 while(strlen(newext) < sizeof(newext - 1)) {
232                                         res = ast_waitfordigit(peer, 3000);
233                                         if (res < 1)
234                                                 break;
235                                         *(ptr++) = res;
236                                         if (!ast_canmatch_extension(peer, peer->context, newext, 1, peer->callerid) ||
237                                                 ast_exists_extension(peer, peer->context, newext, 1, peer->callerid)) {
238                                                 res = 0;
239                                                 break;
240                                         }
241                                 }
242                                 if (res)
243                                         break;
244                                 if (!strcmp(newext, ast_parking_ext())) {
245                                         if (!ast_park_call(chan, peer)) {
246                                                 /* We return non-zero, but tell the PBX not to hang the channel when
247                                                    the thread dies -- We have to be careful now though.  We are responsible for 
248                                                    hanging up the channel, else it will never be hung up! */
249                                                 res=AST_PBX_KEEPALIVE;
250                                                 break;
251                                         } else {
252                                                 ast_log(LOG_WARNING, "Unable to park call %s\n", chan->name);
253                                         }
254                                         /* XXX Maybe we should have another message here instead of invalid extension XXX */
255                                 } else if (ast_exists_extension(chan, peer->context, newext, 1, peer->callerid)) {
256                                         /* Set the channel's new extension, since it exists, using peer context */
257                                         strncpy(chan->exten, newext, sizeof(chan->exten)-1);
258                                         strncpy(chan->context, peer->context, sizeof(chan->context)-1);
259                                         chan->priority = 0;
260                                         ast_frfree(f);
261                                         if (option_verbose > 2) 
262                                                 ast_verbose(VERBOSE_PREFIX_3 "Transferring %s to '%s' (context %s) priority 1\n", chan->name, chan->exten, chan->context);
263                                         res=0;
264                                         break;
265                                 } else {
266                                         if (option_verbose > 2) 
267                                                 ast_verbose(VERBOSE_PREFIX_3 "Unable to find extension '%s' in context %s\n", newext, peer->context);
268                                 }
269                                 res = ast_streamfile(peer, "pbx-invalid", chan->language);
270                                 if (res)
271                                         break;
272                                 res = ast_waitstream(peer, AST_DIGIT_ANY);
273                                 ast_stopstream(peer);
274                                 res = 0;
275                         } else {
276             if (f && (f->frametype == AST_FRAME_DTMF)) {
277                   if (who == peer)
278                         ast_write(chan, f);
279                   else
280                         ast_write(peer, f);
281             }            
282 #if 1
283                                 ast_log(LOG_DEBUG, "Read from %s (%d,%d)\n", who->name, f->frametype, f->subclass);
284 #endif
285                         }
286          if (f)
287                ast_frfree(f);
288         }
289         return res;
290 }
291
292 static void *do_parking_thread(void *ignore)
293 {
294         int ms, tms, max;
295         struct parkeduser *pu, *pl, *pt = NULL;
296         struct timeval tv;
297         struct ast_frame *f;
298         int x;
299         fd_set rfds, efds;
300         fd_set nrfds, nefds;
301         FD_ZERO(&rfds);
302         FD_ZERO(&efds);
303         for (;;) {
304                 ms = -1;
305                 max = -1;
306                 ast_pthread_mutex_lock(&parking_lock);
307                 pl = NULL;
308                 pu = parkinglot;
309                 gettimeofday(&tv, NULL);
310                 FD_ZERO(&nrfds);
311                 FD_ZERO(&nefds);
312                 while(pu) {
313                         tms = (tv.tv_sec - pu->start.tv_sec) * 1000 + (tv.tv_usec - pu->start.tv_usec) / 1000;
314                         if (tms > parkingtime) {
315                                 /* They've been waiting too long, send them back to where they came.  Theoretically they
316                                    should have their original extensions and such, but we copy to be on the safe side */
317                                 strncpy(pu->chan->exten, pu->exten, sizeof(pu->chan->exten)-1);
318                                 strncpy(pu->chan->context, pu->context, sizeof(pu->chan->context)-1);
319                                 pu->chan->priority = pu->priority;
320                                 /* Start up the PBX, or hang them up */
321                                 if (ast_pbx_start(pu->chan))  {
322                                         ast_log(LOG_WARNING, "Unable to restart the PBX for user on '%s', hanging them up...\n", pu->chan->name);
323                                         ast_hangup(pu->chan);
324                                 }
325                                 /* And take them out of the parking lot */
326                                 if (pl) 
327                                         pl->next = pu->next;
328                                 else
329                                         parkinglot = pu->next;
330                                 pt = pu;
331                                 pu = pu->next;
332                                 free(pt);
333                         } else {
334                                 for (x=0;x<AST_MAX_FDS;x++) {
335                                         if ((pu->chan->fds[x] > -1) && (FD_ISSET(pu->chan->fds[x], &rfds) || FD_ISSET(pu->chan->fds[x], &efds))) {
336                                                         if (FD_ISSET(pu->chan->fds[x], &efds))
337                                                                 pu->chan->exception = 1;
338                                                         pu->chan->fdno = x;
339                                                         /* See if they need servicing */
340                                                         f = ast_read(pu->chan);
341                                                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass ==  AST_CONTROL_HANGUP))) {
342                                                         /* There's a problem, hang them up*/
343                                                         if (option_verbose > 1) 
344                                                                 ast_verbose(VERBOSE_PREFIX_2 "%s got tired of being parked\n", pu->chan->name);
345                                                         ast_hangup(pu->chan);
346                                                         /* And take them out of the parking lot */
347                                                         if (pl) 
348                                                                 pl->next = pu->next;
349                                                         else
350                                                                 parkinglot = pu->next;
351                                                         pt = pu;
352                                                         pu = pu->next;
353                                                         free(pt);
354                                                         break;
355                                                 } else {
356                                                         /* XXX Maybe we could do something with packets, like dial "0" for operator or something XXX */
357                                                         ast_frfree(f);
358                                                         goto std;       /* XXX Ick: jumping into an else statement??? XXX */
359                                                 }
360                                         }
361                                 }
362                                 if (x >= AST_MAX_FDS) {
363 std:                                    for (x=0;x<AST_MAX_FDS;x++) {
364                                                 /* Keep this one for next one */
365                                                 if (pu->chan->fds[x] > -1) {
366                                                         FD_SET(pu->chan->fds[x], &nrfds);
367                                                         FD_SET(pu->chan->fds[x], &nefds);
368                                                         if (pu->chan->fds[x] > max)
369                                                                 max = pu->chan->fds[x];
370                                                 }
371                                         }
372                                         /* Keep track of our longest wait */
373                                         if ((tms < ms) || (ms < 0))
374                                                 ms = tms;
375                                         pl = pu;
376                                         pu = pu->next;
377                                 }
378                         }
379                 }
380                 ast_pthread_mutex_unlock(&parking_lock);
381                 rfds = nrfds;
382                 efds = nefds;
383                 tv.tv_sec = ms / 1000;
384                 tv.tv_usec = (ms % 1000) * 1000;
385                 /* Wait for something to happen */
386                 select(max + 1, &rfds, NULL, &efds, (ms > -1) ? &tv : NULL);
387                 pthread_testcancel();
388         }
389         return NULL;    /* Never reached */
390 }
391
392 static int park_exec(struct ast_channel *chan, void *data)
393 {
394         int res=0;
395         struct localuser *u;
396         struct ast_channel *peer=NULL;
397         struct parkeduser *pu, *pl=NULL;
398         int park;
399         if (!data) {
400                 ast_log(LOG_WARNING, "Park requires an argument (extension number)\n");
401                 return -1;
402         }
403         LOCAL_USER_ADD(u);
404         park = atoi((char *)data);
405         ast_pthread_mutex_lock(&parking_lock);
406         pu = parkinglot;
407         while(pu) {
408                 if (pu->parkingnum == park) {
409                         if (pl)
410                                 pl->next = pu->next;
411                         else
412                                 parkinglot = pu->next;
413                         break;
414                 }
415                 pu = pu->next;
416         }
417         ast_pthread_mutex_unlock(&parking_lock);
418         if (pu) {
419                 peer = pu->chan;
420                 free(pu);
421         }
422         if (peer) {
423                 res = ast_channel_make_compatible(chan, peer);
424                 if (res < 0) {
425                         ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for bridge\n", chan->name, peer->name);
426                         ast_hangup(peer);
427                         return -1;
428                 }
429                 /* This runs sorta backwards, since we give the incoming channel control, as if it
430                    were the person called. */
431                 if (option_verbose > 2) 
432                         ast_verbose(VERBOSE_PREFIX_3 "Channel %s connected to parked call %d\n", chan->name, park);
433                 res = ast_bridge_call(peer, chan, 1);
434                 /* Simulate the PBX hanging up */
435                 if (res != AST_PBX_KEEPALIVE)
436                         ast_hangup(peer);
437                 return -1;
438         } else {
439                 /* XXX Play a message XXX */
440                 if (option_verbose > 2) 
441                         ast_verbose(VERBOSE_PREFIX_3 "Channel %s tried to talk to non-existant parked call %d\n", chan->name, park);
442                 res = -1;
443         }
444         LOCAL_USER_REMOVE(u);
445         return res;
446 }
447
448 int load_module(void)
449 {
450         int res;
451         int x;
452         struct ast_context *con;
453         char exten[AST_MAX_EXTENSION];
454         con = ast_context_find(parking_con);
455         if (!con) {
456                 con = ast_context_create(parking_con, registrar);
457                 if (!con) {
458                         ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", parking_con);
459                         return -1;
460                 }
461         }
462         for(x=parking_start; x<=parking_stop;x++) {
463                 snprintf(exten, sizeof(exten), "%d", x);
464                 ast_add_extension2(con, 1, exten, 1, NULL, parkedcall, strdup(exten), free, registrar);
465         }
466         pthread_create(&parking_thread, NULL, do_parking_thread, NULL);
467         res = ast_register_application(parkedcall, park_exec, synopsis, descrip);
468         return res;
469 }
470
471 int unload_module(void)
472 {
473         STANDARD_HANGUP_LOCALUSERS;
474         return ast_unregister_application(parkedcall);
475 }
476
477 char *description(void)
478 {
479         return "Call Parking Resource";
480 }
481
482 int usecount(void)
483 {
484         /* Never allow parking to be unloaded because it will
485            unresolve needed symbols in the dialer */
486 #if 0
487         int res;
488         STANDARD_USECOUNT(res);
489         return res;
490 #else
491         return 1;
492 #endif
493 }
494
495 char *key()
496 {
497         return ASTERISK_GPL_KEY;
498 }