merge Russell's 'hold_handling' branch, finally implementing music-on-hold handling...
[asterisk/asterisk.git] / channels / chan_mgcp.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Implementation of Media Gateway Control Protocol
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \par See also
26  * \arg \ref Config_mgcp
27  *
28  * \ingroup channel_drivers
29  */
30
31 #include "asterisk.h"
32
33 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34
35 #include <stdio.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <sys/socket.h>
39 #include <sys/ioctl.h>
40 #include <net/if.h>
41 #include <errno.h>
42 #include <stdlib.h>
43 #include <fcntl.h>
44 #include <netdb.h>
45 #include <sys/signal.h>
46 #include <signal.h>
47 #include <netinet/in.h>
48 #include <netinet/in_systm.h>
49 #include <netinet/ip.h>
50 #include <arpa/inet.h>
51 #include <ctype.h>
52
53 #include "asterisk/lock.h"
54 #include "asterisk/channel.h"
55 #include "asterisk/config.h"
56 #include "asterisk/logger.h"
57 #include "asterisk/module.h"
58 #include "asterisk/pbx.h"
59 #include "asterisk/options.h"
60 #include "asterisk/lock.h"
61 #include "asterisk/sched.h"
62 #include "asterisk/io.h"
63 #include "asterisk/rtp.h"
64 #include "asterisk/acl.h"
65 #include "asterisk/callerid.h"
66 #include "asterisk/cli.h"
67 #include "asterisk/say.h"
68 #include "asterisk/cdr.h"
69 #include "asterisk/astdb.h"
70 #include "asterisk/features.h"
71 #include "asterisk/app.h"
72 #include "asterisk/musiconhold.h"
73 #include "asterisk/utils.h"
74 #include "asterisk/causes.h"
75 #include "asterisk/dsp.h"
76 #include "asterisk/devicestate.h"
77 #include "asterisk/stringfields.h"
78 #include "asterisk/abstract_jb.h"
79
80 #ifndef IPTOS_MINCOST
81 #define IPTOS_MINCOST 0x02
82 #endif
83
84 /*
85  * Define to work around buggy dlink MGCP phone firmware which
86  * appears not to know that "rt" is part of the "G" package.
87  */
88 /* #define DLINK_BUGGY_FIRMWARE */
89
90 #define MGCPDUMPER
91 #define DEFAULT_EXPIRY  120
92 #define MAX_EXPIRY      3600
93 #define CANREINVITE     1
94
95 #ifndef INADDR_NONE
96 #define INADDR_NONE (in_addr_t)(-1)
97 #endif
98
99 /*! Global jitterbuffer configuration - by default, jb is disabled */
100 static struct ast_jb_conf default_jbconf =
101 {
102         .flags = 0,
103         .max_size = -1,
104         .resync_threshold = -1,
105         .impl = ""
106 };
107 static struct ast_jb_conf global_jbconf;
108
109 static const char tdesc[] = "Media Gateway Control Protocol (MGCP)";
110 static const char config[] = "mgcp.conf";
111
112 #define MGCP_DTMF_RFC2833       (1 << 0)
113 #define MGCP_DTMF_INBAND        (1 << 1)
114 #define MGCP_DTMF_HYBRID        (1 << 2)
115
116 #define DEFAULT_MGCP_GW_PORT    2427 /*!< From RFC 2705 */
117 #define DEFAULT_MGCP_CA_PORT    2727 /*!< From RFC 2705 */
118 #define MGCP_MAX_PACKET         1500 /*!< Also from RFC 2543, should sub headers tho */
119 #define DEFAULT_RETRANS         1000 /*!< How frequently to retransmit */
120 #define MAX_RETRANS             5    /*!< Try only 5 times for retransmissions */
121
122 /*! MGCP rtp stream modes { */
123 #define MGCP_CX_SENDONLY        0
124 #define MGCP_CX_RECVONLY        1
125 #define MGCP_CX_SENDRECV        2
126 #define MGCP_CX_CONF            3
127 #define MGCP_CX_CONFERENCE      3
128 #define MGCP_CX_MUTE            4
129 #define MGCP_CX_INACTIVE        4
130 /*! } */
131
132 static char *mgcp_cxmodes[] = {
133         "sendonly",
134         "recvonly",
135         "sendrecv",
136         "confrnce",
137         "inactive"
138 };
139
140 enum {
141         MGCP_CMD_EPCF,
142         MGCP_CMD_CRCX,
143         MGCP_CMD_MDCX,
144         MGCP_CMD_DLCX,
145         MGCP_CMD_RQNT,
146         MGCP_CMD_NTFY,
147         MGCP_CMD_AUEP,
148         MGCP_CMD_AUCX,
149         MGCP_CMD_RSIP
150 };
151
152 static char context[AST_MAX_EXTENSION] = "default";
153
154 static char language[MAX_LANGUAGE] = "";
155 static char musicclass[MAX_MUSICCLASS] = "";
156 static char cid_num[AST_MAX_EXTENSION] = "";
157 static char cid_name[AST_MAX_EXTENSION] = "";
158
159 static int dtmfmode = 0;
160 static int nat = 0;
161
162 static ast_group_t cur_callergroup = 0;
163 static ast_group_t cur_pickupgroup = 0;
164
165 static int tos = 0;
166
167 static int immediate = 0;
168
169 static int callwaiting = 0;
170
171 static int callreturn = 0;
172
173 static int slowsequence = 0;
174
175 static int threewaycalling = 0;
176
177 /*! This is for flashhook transfers */
178 static int transfer = 0;
179
180 static int cancallforward = 0;
181
182 static int singlepath = 0;
183
184 static int canreinvite = CANREINVITE;
185
186 static char accountcode[AST_MAX_ACCOUNT_CODE] = "";
187
188 static char mailbox[AST_MAX_EXTENSION];
189
190 static int amaflags = 0;
191
192 static int adsi = 0;
193
194 static unsigned int oseq;
195
196 /*! Wait up to 16 seconds for first digit (FXO logic) */
197 static int firstdigittimeout = 16000;
198
199 /*! How long to wait for following digits (FXO logic) */
200 static int gendigittimeout = 8000;
201
202 /*! How long to wait for an extra digit, if there is an ambiguous match */
203 static int matchdigittimeout = 3000;
204
205 /*! Protect the monitoring thread, so only one process can kill or start it, and not
206     when it's doing something critical. */
207 AST_MUTEX_DEFINE_STATIC(netlock);
208
209 AST_MUTEX_DEFINE_STATIC(monlock);
210
211 /*! This is the thread for the monitor which checks for input on the channels
212     which are not currently in use. */
213 static pthread_t monitor_thread = AST_PTHREADT_NULL;
214
215 static int restart_monitor(void);
216
217 static int capability = AST_FORMAT_ULAW;
218 static int nonCodecCapability = AST_RTP_DTMF;
219
220 static char ourhost[MAXHOSTNAMELEN];
221 static struct in_addr __ourip;
222 static int ourport;
223
224 static int mgcpdebug = 0;
225
226 static struct sched_context *sched;
227 static struct io_context *io;
228 /*! The private structures of the  mgcp channels are linked for
229   ! selecting outgoing channels */
230    
231 #define MGCP_MAX_HEADERS        64
232 #define MGCP_MAX_LINES          64
233
234 struct mgcp_request {
235         int len;
236         char *verb;
237         char *identifier;
238         char *endpoint;
239         char *version;
240         int headers;                    /*!< MGCP Headers */
241         char *header[MGCP_MAX_HEADERS];
242         int lines;                      /*!< SDP Content */
243         char *line[MGCP_MAX_LINES];
244         char data[MGCP_MAX_PACKET];
245         int cmd;                        /*!< int version of verb = command */
246         unsigned int trid;              /*!< int version of identifier = transaction id */
247         struct mgcp_request *next;      /*!< next in the queue */
248 };
249
250 /*! \brief mgcp_message: MGCP message for queuing up */
251 struct mgcp_message {
252         struct mgcp_endpoint *owner_ep;
253         struct mgcp_subchannel *owner_sub;
254         int retrans;
255         unsigned long expire;
256         unsigned int seqno;
257         int len;
258         struct mgcp_message *next;
259         char buf[0];
260 };
261
262 #define RESPONSE_TIMEOUT 30     /*!< in seconds */
263
264 struct mgcp_response {
265         time_t whensent;
266         int len;
267         int seqno;
268         struct mgcp_response *next;
269         char buf[0];
270 };
271
272 #define MAX_SUBS 2
273
274 #define SUB_REAL 0
275 #define SUB_ALT  1
276
277 struct mgcp_subchannel {
278         /*! subchannel magic string. 
279            Needed to prove that any subchannel pointer passed by asterisk 
280            really points to a valid subchannel memory area.
281            Ugly.. But serves the purpose for the time being.
282          */
283 #define MGCP_SUBCHANNEL_MAGIC "!978!"
284         char magic[6]; 
285         ast_mutex_t lock;
286         int id;
287         struct ast_channel *owner;
288         struct mgcp_endpoint *parent;
289         struct ast_rtp *rtp;
290         struct sockaddr_in tmpdest;
291         char txident[80]; /*! \todo FIXME txident is replaced by rqnt_ident in endpoint. 
292                         This should be obsoleted */
293         char cxident[80];
294         char callid[80];
295         int cxmode;
296         struct mgcp_request *cx_queue; /*!< pending CX commands */
297         ast_mutex_t cx_queue_lock;     /*!< CX queue lock */
298         int nat;
299         int iseq;                      /*!< Not used? RTP? */
300         int outgoing;
301         int alreadygone;
302         struct mgcp_subchannel *next;  /*!< for out circular linked list */
303 };
304
305 #define MGCP_ONHOOK  1
306 #define MGCP_OFFHOOK 2
307
308 #define TYPE_TRUNK 1
309 #define TYPE_LINE  2
310
311 struct mgcp_endpoint {
312         ast_mutex_t lock;
313         char name[80];
314         struct mgcp_subchannel *sub;            /*!< Pointer to our current connection, channel and stuff */
315         char accountcode[AST_MAX_ACCOUNT_CODE];
316         char exten[AST_MAX_EXTENSION];          /*!< Extention where to start */
317         char context[AST_MAX_EXTENSION];
318         char language[MAX_LANGUAGE];
319         char cid_num[AST_MAX_EXTENSION];        /*!< Caller*ID number */
320         char cid_name[AST_MAX_EXTENSION];       /*!< Caller*ID name */
321         char lastcallerid[AST_MAX_EXTENSION];   /*!< Last Caller*ID */
322         char call_forward[AST_MAX_EXTENSION];   /*!< Last Caller*ID */
323         char mailbox[AST_MAX_EXTENSION];
324         char musicclass[MAX_MUSICCLASS];
325         char curtone[80];                       /*!< Current tone */
326         ast_group_t callgroup;
327         ast_group_t pickupgroup;
328         int callwaiting;
329         int hascallwaiting;
330         int transfer;
331         int threewaycalling;
332         int singlepath;
333         int cancallforward;
334         int canreinvite;
335         int callreturn;
336         int dnd; /* How does this affect callwait? Do we just deny a mgcp_request if we're dnd? */
337         int hascallerid;
338         int hidecallerid;
339         int dtmfmode;
340         int amaflags;
341         int type;
342         int slowsequence;                       /*!< MS: Sequence the endpoint as a whole */
343         int group;
344         int iseq; /*!< Not used? */
345         int lastout; /*!< tracking this on the subchannels.  Is it needed here? */
346         int needdestroy; /*!< Not used? */
347         int capability;
348         int nonCodecCapability;
349         int onhooktime;
350         int msgstate; /*!< voicemail message state */
351         int immediate;
352         int hookstate;
353         int adsi;
354         char rqnt_ident[80];             /*!< request identifier */
355         struct mgcp_request *rqnt_queue; /*!< pending RQNT commands */
356         ast_mutex_t rqnt_queue_lock;
357         struct mgcp_request *cmd_queue;  /*!< pending commands other than RQNT */
358         ast_mutex_t cmd_queue_lock;
359         int delme;                       /*!< needed for reload */
360         int needaudit;                   /*!< needed for reload */
361         struct ast_dsp *dsp; /*!< XXX Should there be a dsp/subchannel? XXX */
362         /* owner is tracked on the subchannels, and the *sub indicates whos in charge */
363         /* struct ast_channel *owner; */
364         /* struct ast_rtp *rtp; */
365         /* struct sockaddr_in tmpdest; */
366         /* message go the the endpoint and not the channel so they stay here */
367         struct mgcp_endpoint *next;
368         struct mgcp_gateway *parent;
369 };
370
371 static struct mgcp_gateway {
372         /* A gateway containing one or more endpoints */
373         char name[80];
374         int isnamedottedip; /*!< is the name FQDN or dotted ip */
375         struct sockaddr_in addr;
376         struct sockaddr_in defaddr;
377         struct in_addr ourip;
378         int dynamic;
379         int expire;             /*!< XXX Should we ever expire dynamic registrations? XXX */
380         struct mgcp_endpoint *endpoints;
381         struct ast_ha *ha;
382 /* obsolete
383         time_t lastouttime;
384         int lastout;
385         int messagepending;
386 */
387 /* Wildcard endpoint name */
388         char wcardep[30];
389         struct mgcp_message *msgs; /*!< gw msg queue */
390         ast_mutex_t msgs_lock;     /*!< queue lock */  
391         int retransid;             /*!< retrans timer id */
392         int delme;                 /*!< needed for reload */
393         struct mgcp_response *responses;
394         struct mgcp_gateway *next;
395 } *gateways;
396
397 AST_MUTEX_DEFINE_STATIC(mgcp_reload_lock);
398 static int mgcp_reloading = 0;
399
400 /*! \brief gatelock: mutex for gateway/endpoint lists */
401 AST_MUTEX_DEFINE_STATIC(gatelock);
402
403 static int mgcpsock  = -1;
404
405 static struct sockaddr_in bindaddr;
406
407 static struct ast_frame  *mgcp_read(struct ast_channel *ast);
408 static int transmit_response(struct mgcp_subchannel *sub, char *msg, struct mgcp_request *req, char *msgrest);
409 static int transmit_notify_request(struct mgcp_subchannel *sub, char *tone);
410 static int transmit_modify_request(struct mgcp_subchannel *sub);
411 static int transmit_notify_request_with_callerid(struct mgcp_subchannel *sub, char *tone, char *callernum, char *callername);
412 static int transmit_modify_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp *rtp, int codecs);
413 static int transmit_connection_del(struct mgcp_subchannel *sub);
414 static int transmit_audit_endpoint(struct mgcp_endpoint *p);
415 static void start_rtp(struct mgcp_subchannel *sub);
416 static void handle_response(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,  
417                             int result, unsigned int ident, struct mgcp_request *resp);
418 static void dump_cmd_queues(struct mgcp_endpoint *p, struct mgcp_subchannel *sub);
419 static int mgcp_do_reload(void);
420 static int mgcp_reload(int fd, int argc, char *argv[]);
421
422 static struct ast_channel *mgcp_request(const char *type, int format, void *data, int *cause);
423 static int mgcp_call(struct ast_channel *ast, char *dest, int timeout);
424 static int mgcp_hangup(struct ast_channel *ast);
425 static int mgcp_answer(struct ast_channel *ast);
426 static struct ast_frame *mgcp_read(struct ast_channel *ast);
427 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame);
428 static int mgcp_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
429 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
430 static int mgcp_senddigit(struct ast_channel *ast, char digit);
431 static int mgcp_devicestate(void *data);
432
433 static const struct ast_channel_tech mgcp_tech = {
434         .type = "MGCP",
435         .description = tdesc,
436         .capabilities = AST_FORMAT_ULAW,
437         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
438         .requester = mgcp_request,
439         .devicestate = mgcp_devicestate,
440         .call = mgcp_call,
441         .hangup = mgcp_hangup,
442         .answer = mgcp_answer,
443         .read = mgcp_read,
444         .write = mgcp_write,
445         .indicate = mgcp_indicate,
446         .fixup = mgcp_fixup,
447         .send_digit = mgcp_senddigit,
448         .bridge = ast_rtp_bridge,
449 };
450
451 static int has_voicemail(struct mgcp_endpoint *p)
452 {
453         return ast_app_has_voicemail(p->mailbox, NULL);
454 }
455
456 static int unalloc_sub(struct mgcp_subchannel *sub)
457 {
458         struct mgcp_endpoint *p = sub->parent;
459         if (p->sub == sub) {
460                 ast_log(LOG_WARNING, "Trying to unalloc the real channel %s@%s?!?\n", p->name, p->parent->name);
461                 return -1;
462         }
463         ast_log(LOG_DEBUG, "Released sub %d of channel %s@%s\n", sub->id, p->name, p->parent->name);
464
465         sub->owner = NULL;
466         if (!ast_strlen_zero(sub->cxident)) {
467                 transmit_connection_del(sub);
468         }
469         sub->cxident[0] = '\0';
470         sub->callid[0] = '\0';
471         sub->cxmode = MGCP_CX_INACTIVE;
472         sub->outgoing = 0;
473         sub->alreadygone = 0;
474         memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
475         if (sub->rtp) {
476                 ast_rtp_destroy(sub->rtp);
477                 sub->rtp = NULL;
478         }
479         dump_cmd_queues(NULL, sub); /* SC */
480         return 0;
481 }
482
483 /* modified for new transport mechanism */
484 static int __mgcp_xmit(struct mgcp_gateway *gw, char *data, int len)
485 {
486         int res;
487         if (gw->addr.sin_addr.s_addr)
488                 res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&gw->addr, sizeof(struct sockaddr_in));
489         else 
490                 res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&gw->defaddr, sizeof(struct sockaddr_in));
491         if (res != len) {
492                 ast_log(LOG_WARNING, "mgcp_xmit returned %d: %s\n", res, strerror(errno));
493         }
494         return res;
495 }
496
497 static int resend_response(struct mgcp_subchannel *sub, struct mgcp_response *resp)
498 {
499         struct mgcp_endpoint *p = sub->parent;
500         int res;
501         char iabuf[INET_ADDRSTRLEN];
502         if (mgcpdebug) {
503                 ast_verbose("Retransmitting:\n%s\n to %s:%d\n", resp->buf, ast_inet_ntoa(iabuf, sizeof(iabuf), p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
504         }
505         res = __mgcp_xmit(p->parent, resp->buf, resp->len);
506         if (res > 0)
507                 res = 0;
508         return res;
509 }
510
511 static int send_response(struct mgcp_subchannel *sub, struct mgcp_request *req)
512 {
513         struct mgcp_endpoint *p = sub->parent;
514         int res;
515         char iabuf[INET_ADDRSTRLEN];
516         if (mgcpdebug) {
517                 ast_verbose("Transmitting:\n%s\n to %s:%d\n", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
518         }
519         res = __mgcp_xmit(p->parent, req->data, req->len);
520         if (res > 0)
521                 res = 0;
522         return res;
523 }
524
525 /* modified for new transport framework */
526 static void dump_queue(struct mgcp_gateway *gw, struct mgcp_endpoint *p)
527 {
528         struct mgcp_message *cur, *q = NULL, *w, *prev;
529
530         ast_mutex_lock(&gw->msgs_lock);
531         prev = NULL, cur = gw->msgs;
532         while (cur) {
533                 if (!p || cur->owner_ep == p) {
534                         if (prev)
535                                 prev->next = cur->next;
536                         else
537                                 gw->msgs = cur->next;
538
539                         ast_log(LOG_NOTICE, "Removing message from %s transaction %u\n", 
540                                 gw->name, cur->seqno);
541
542                         w = cur;
543                         cur = cur->next;
544                         if (q) {
545                                 w->next = q;
546                         } else {
547                                 w->next = NULL;
548                         }
549                         q = w;
550                 } else {
551                         prev = cur, cur=cur->next;
552                 }
553         }
554         ast_mutex_unlock(&gw->msgs_lock);
555
556         while (q) {
557                 cur = q;
558                 q = q->next;
559                 free(cur);
560         }
561 }
562
563 static void mgcp_queue_frame(struct mgcp_subchannel *sub, struct ast_frame *f)
564 {
565         for(;;) {
566                 if (sub->owner) {
567                         if (!ast_mutex_trylock(&sub->owner->lock)) {
568                                 ast_queue_frame(sub->owner, f);
569                                 ast_mutex_unlock(&sub->owner->lock);
570                                 break;
571                         } else {
572                                 ast_mutex_unlock(&sub->lock);
573                                 usleep(1);
574                                 ast_mutex_lock(&sub->lock);
575                         }
576                 } else
577                         break;
578         }
579 }
580
581 static void mgcp_queue_hangup(struct mgcp_subchannel *sub)
582 {
583         for(;;) {
584                 if (sub->owner) {
585                         if (!ast_mutex_trylock(&sub->owner->lock)) {
586                                 ast_queue_hangup(sub->owner);
587                                 ast_mutex_unlock(&sub->owner->lock);
588                                 break;
589                         } else {
590                                 ast_mutex_unlock(&sub->lock);
591                                 usleep(1);
592                                 ast_mutex_lock(&sub->lock);
593                         }
594                 } else
595                         break;
596         }
597 }
598
599 static void mgcp_queue_control(struct mgcp_subchannel *sub, int control)
600 {
601         struct ast_frame f = { AST_FRAME_CONTROL, };
602         f.subclass = control;
603         return mgcp_queue_frame(sub, &f);
604 }
605
606 static int retrans_pkt(void *data)
607 {
608         struct mgcp_gateway *gw = (struct mgcp_gateway *)data;
609         struct mgcp_message *cur, *exq = NULL, *w, *prev;
610         int res = 0;
611
612         /* find out expired msgs */
613         ast_mutex_lock(&gw->msgs_lock);
614
615         prev = NULL, cur = gw->msgs;
616         while (cur) {
617                 if (cur->retrans < MAX_RETRANS) {
618                         cur->retrans++;
619                         if (mgcpdebug) {
620                                 ast_verbose("Retransmitting #%d transaction %u on [%s]\n",
621                                         cur->retrans, cur->seqno, gw->name);
622                         }
623                         __mgcp_xmit(gw, cur->buf, cur->len);
624
625                         prev = cur;
626                         cur = cur->next;
627                 } else {
628                         if (prev)
629                                 prev->next = cur->next;
630                         else
631                                 gw->msgs = cur->next;
632
633                         ast_log(LOG_WARNING, "Maximum retries exceeded for transaction %u on [%s]\n",
634                                 cur->seqno, gw->name);
635
636                         w = cur;
637                         cur = cur->next;
638
639                         if (exq) {
640                                 w->next = exq;
641                         } else {
642                                 w->next = NULL;
643                         }
644                         exq = w;
645                 }
646         }
647
648         if (!gw->msgs) {
649                 gw->retransid = -1;
650                 res = 0;
651         } else {
652                 res = 1;
653         }
654         ast_mutex_unlock(&gw->msgs_lock);
655
656         while (exq) {
657                 cur = exq;
658                 /* time-out transaction */
659                 handle_response(cur->owner_ep, cur->owner_sub, 406, cur->seqno, NULL); 
660                 exq = exq->next;
661                 free(cur);
662         }
663
664         return res;
665 }
666
667 /* modified for the new transaction mechanism */
668 static int mgcp_postrequest(struct mgcp_endpoint *p, struct mgcp_subchannel *sub, 
669                             char *data, int len, unsigned int seqno)
670 {
671         struct mgcp_message *msg = malloc(sizeof(struct mgcp_message) + len);
672         struct mgcp_message *cur;
673         struct mgcp_gateway *gw = ((p && p->parent) ? p->parent : NULL);
674         struct timeval tv;
675
676         if (!msg) {
677                 return -1;
678         }
679         if (!gw) {
680                 return -1;
681         }
682 /* SC
683         time(&t);
684         if (gw->messagepending && (gw->lastouttime + 20 < t)) {
685                 ast_log(LOG_NOTICE, "Timeout waiting for response to message:%d,  lastouttime: %ld, now: %ld.  Dumping pending queue\n",
686                         gw->msgs ? gw->msgs->seqno : -1, (long) gw->lastouttime, (long) t);
687                 dump_queue(sub->parent);
688         }
689 */
690         msg->owner_sub = sub;
691         msg->owner_ep = p;
692         msg->seqno = seqno;
693         msg->next = NULL;
694         msg->len = len;
695         msg->retrans = 0;
696         memcpy(msg->buf, data, msg->len);
697
698         ast_mutex_lock(&gw->msgs_lock);
699         cur = gw->msgs;
700         if (cur) {
701                 while(cur->next)
702                         cur = cur->next;
703                 cur->next = msg;
704         } else {
705                 gw->msgs = msg;
706         }
707
708         if (gettimeofday(&tv, NULL) < 0) {
709                 /* This shouldn't ever happen, but let's be sure */
710                 ast_log(LOG_NOTICE, "gettimeofday() failed!\n");
711         } else {
712                 msg->expire = tv.tv_sec * 1000 + tv.tv_usec / 1000 + DEFAULT_RETRANS;
713
714                 if (gw->retransid == -1)
715                         gw->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, (void *)gw);
716         }
717         ast_mutex_unlock(&gw->msgs_lock);
718 /* SC
719         if (!gw->messagepending) {
720                 gw->messagepending = 1;
721                 gw->lastout = seqno;
722                 gw->lastouttime = t;
723 */
724         __mgcp_xmit(gw, msg->buf, msg->len);
725                 /* XXX Should schedule retransmission XXX */
726 /* SC
727         } else
728                 ast_log(LOG_DEBUG, "Deferring transmission of transaction %d\n", seqno);
729 */
730         return 0;
731 }
732
733 /* modified for new transport */
734 static int send_request(struct mgcp_endpoint *p, struct mgcp_subchannel *sub, 
735                         struct mgcp_request *req, unsigned int seqno)
736 {
737         int res = 0;
738         struct mgcp_request **queue, *q, *r, *t;
739         char iabuf[INET_ADDRSTRLEN];
740         ast_mutex_t *l;
741
742         ast_log(LOG_DEBUG, "Slow sequence is %d\n", p->slowsequence);
743         if (p->slowsequence) {
744                 queue = &p->cmd_queue;
745                 l = &p->cmd_queue_lock;
746                 ast_mutex_lock(l);
747         } else {
748                 switch (req->cmd) {
749                 case MGCP_CMD_DLCX:
750                         queue = &sub->cx_queue;
751                         l = &sub->cx_queue_lock;
752                         ast_mutex_lock(l);
753                         q = sub->cx_queue;
754                         /* delete pending cx cmds */
755                         while (q) {
756                                 r = q->next;
757                                 free(q);
758                                 q = r;
759                         }
760                         *queue = NULL;
761                         break;
762
763                 case MGCP_CMD_CRCX:
764                 case MGCP_CMD_MDCX:
765                         queue = &sub->cx_queue;
766                         l = &sub->cx_queue_lock;
767                         ast_mutex_lock(l);
768                         break;
769
770                 case MGCP_CMD_RQNT:
771                         queue = &p->rqnt_queue;
772                         l = &p->rqnt_queue_lock;
773                         ast_mutex_lock(l);
774                         break;
775
776                 default:
777                         queue = &p->cmd_queue;
778                         l = &p->cmd_queue_lock;
779                         ast_mutex_lock(l);
780                         break;
781                 }
782         }
783
784         r = (struct mgcp_request *) malloc (sizeof(struct mgcp_request));
785         if (!r) {
786                 ast_log(LOG_WARNING, "Cannot post MGCP request: insufficient memory\n");
787                 ast_mutex_unlock(l);
788                 return -1;
789         }
790         memcpy(r, req, sizeof(struct mgcp_request));
791
792         if (!(*queue)) {
793                 if (mgcpdebug) {
794                         ast_verbose("Posting Request:\n%s to %s:%d\n", req->data, 
795                                 ast_inet_ntoa(iabuf, sizeof(iabuf), p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
796                 }
797
798                 res = mgcp_postrequest(p, sub, req->data, req->len, seqno);
799         } else {
800                 if (mgcpdebug) {
801                         ast_verbose("Queueing Request:\n%s to %s:%d\n", req->data, 
802                                 ast_inet_ntoa(iabuf, sizeof(iabuf), p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
803                 }
804         }
805
806         /* XXX find tail. We could also keep tail in the data struct for faster access */
807         for (t = *queue; t && t->next; t = t->next);
808
809         r->next = NULL;
810         if (t)
811                 t->next = r;
812         else
813                 *queue = r;
814
815         ast_mutex_unlock(l);
816
817         return res;
818 }
819
820 static int mgcp_call(struct ast_channel *ast, char *dest, int timeout)
821 {
822         int res;
823         struct mgcp_endpoint *p;
824         struct mgcp_subchannel *sub;
825         char tone[50] = "";
826         const char *distinctive_ring = NULL;
827         struct varshead *headp;
828         struct ast_var_t *current;
829
830         if (mgcpdebug) {
831                 ast_verbose(VERBOSE_PREFIX_3 "MGCP mgcp_call(%s)\n", ast->name);
832         }
833         sub = ast->tech_pvt;
834         p = sub->parent;
835         headp = &ast->varshead;
836         AST_LIST_TRAVERSE(headp,current,entries) {
837                 /* Check whether there is an ALERT_INFO variable */
838                 if (strcasecmp(ast_var_name(current),"ALERT_INFO") == 0) {
839                         distinctive_ring = ast_var_value(current);
840                 }
841         }
842
843         ast_mutex_lock(&sub->lock);
844         switch (p->hookstate) {
845         case MGCP_OFFHOOK:
846                 if (!ast_strlen_zero(distinctive_ring)) {
847                         snprintf(tone, sizeof(tone), "L/wt%s", distinctive_ring);
848                         if (mgcpdebug) {
849                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP distinctive callwait %s\n", tone);
850                         }
851                 } else {
852                         snprintf(tone, sizeof(tone), "L/wt");
853                         if (mgcpdebug) {
854                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP normal callwait %s\n", tone);
855                         }
856                 }
857                 break;
858         case MGCP_ONHOOK:
859         default:
860                 if (!ast_strlen_zero(distinctive_ring)) {
861                         snprintf(tone, sizeof(tone), "L/r%s", distinctive_ring);
862                         if (mgcpdebug) {
863                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP distinctive ring %s\n", tone);
864                         }
865                 } else {
866                         snprintf(tone, sizeof(tone), "L/rg");
867                         if (mgcpdebug) {
868                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP default ring\n");
869                         }
870                 }
871                 break;
872         }
873
874         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
875                 ast_log(LOG_WARNING, "mgcp_call called on %s, neither down nor reserved\n", ast->name);
876                 ast_mutex_unlock(&sub->lock);
877                 return -1;
878         }
879
880         res = 0;
881         sub->outgoing = 1;
882         sub->cxmode = MGCP_CX_RECVONLY;
883         if (p->type == TYPE_LINE) {
884                 if (!sub->rtp) {
885                         start_rtp(sub);
886                 } else {
887                         transmit_modify_request(sub);
888                 }
889
890                 if (sub->next->owner && !ast_strlen_zero(sub->next->cxident) && !ast_strlen_zero(sub->next->callid)) {
891                         /* try to prevent a callwait from disturbing the other connection */
892                         sub->next->cxmode = MGCP_CX_RECVONLY;
893                         transmit_modify_request(sub->next);
894                 }
895
896                 transmit_notify_request_with_callerid(sub, tone, ast->cid.cid_num, ast->cid.cid_name);
897                 ast_setstate(ast, AST_STATE_RINGING);
898
899                 if (sub->next->owner && !ast_strlen_zero(sub->next->cxident) && !ast_strlen_zero(sub->next->callid)) {
900                         /* Put the connection back in sendrecv */
901                         sub->next->cxmode = MGCP_CX_SENDRECV;
902                         transmit_modify_request(sub->next);
903                 }
904         } else {
905                 ast_log(LOG_NOTICE, "Don't know how to dial on trunks yet\n");
906                 res = -1;
907         }
908         ast_mutex_unlock(&sub->lock);
909         ast_queue_control(ast, AST_CONTROL_RINGING);
910         return res;
911 }
912
913 static int mgcp_hangup(struct ast_channel *ast)
914 {
915         struct mgcp_subchannel *sub = ast->tech_pvt;
916         struct mgcp_endpoint *p = sub->parent;
917
918         if (option_debug) {
919                 ast_log(LOG_DEBUG, "mgcp_hangup(%s)\n", ast->name);
920         }
921         if (!ast->tech_pvt) {
922                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
923                 return 0;
924         }
925         if (strcmp(sub->magic, MGCP_SUBCHANNEL_MAGIC)) {
926                 ast_log(LOG_DEBUG, "Invalid magic. MGCP subchannel freed up already.\n");
927                 return 0;
928         }
929         ast_mutex_lock(&sub->lock);
930         if (mgcpdebug) {
931                 ast_verbose(VERBOSE_PREFIX_3 "MGCP mgcp_hangup(%s) on %s@%s\n", ast->name, p->name, p->parent->name);
932         }
933
934         if ((p->dtmfmode & MGCP_DTMF_INBAND) && p->dsp) {
935                 /* check whether other channel is active. */
936                 if (!sub->next->owner) {
937                         if (p->dtmfmode & MGCP_DTMF_HYBRID)
938                                 p->dtmfmode &= ~MGCP_DTMF_INBAND;
939                         if (mgcpdebug) {
940                                 ast_verbose(VERBOSE_PREFIX_2 "MGCP free dsp on %s@%s\n", p->name, p->parent->name);
941                         }
942                         ast_dsp_free(p->dsp);
943                         p->dsp = NULL;
944                 }
945         }
946
947         sub->owner = NULL;
948         if (!ast_strlen_zero(sub->cxident)) {
949                 transmit_connection_del(sub);
950         }
951         sub->cxident[0] = '\0';
952         if ((sub == p->sub) && sub->next->owner) {
953                 if (p->hookstate == MGCP_OFFHOOK) {
954                         if (sub->next->owner && ast_bridged_channel(sub->next->owner)) {
955                                 transmit_notify_request_with_callerid(p->sub, "L/wt", ast_bridged_channel(sub->next->owner)->cid.cid_num, ast_bridged_channel(sub->next->owner)->cid.cid_name);
956                         }
957                 } else {
958                         /* set our other connection as the primary and swith over to it */
959                         p->sub = sub->next;
960                         p->sub->cxmode = MGCP_CX_RECVONLY;
961                         transmit_modify_request(p->sub);
962                         if (sub->next->owner && ast_bridged_channel(sub->next->owner)) {
963                                 transmit_notify_request_with_callerid(p->sub, "L/rg", ast_bridged_channel(sub->next->owner)->cid.cid_num, ast_bridged_channel(sub->next->owner)->cid.cid_name);
964                         }
965                 }
966
967         } else if ((sub == p->sub->next) && p->hookstate == MGCP_OFFHOOK) {
968                 transmit_notify_request(sub, "L/v");
969         } else if (p->hookstate == MGCP_OFFHOOK) {
970                 transmit_notify_request(sub, "L/ro");
971         } else {
972                 transmit_notify_request(sub, "");
973         }
974
975         ast->tech_pvt = NULL;
976         sub->alreadygone = 0;
977         sub->outgoing = 0;
978         sub->cxmode = MGCP_CX_INACTIVE;
979         sub->callid[0] = '\0';
980         /* Reset temporary destination */
981         memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
982         if (sub->rtp) {
983                 ast_rtp_destroy(sub->rtp);
984                 sub->rtp = NULL;
985         }
986
987         /* Decrement use count */
988         ast_atomic_fetchadd_int(&__mod_desc->usecnt, -1);
989         ast_update_use_count();
990         /* Decrement use count */
991
992         if ((p->hookstate == MGCP_ONHOOK) && (!sub->next->rtp)) {
993                 p->hidecallerid = 0;
994                 if (p->hascallwaiting && !p->callwaiting) {
995                         if (option_verbose > 2)
996                                 ast_verbose(VERBOSE_PREFIX_3 "Enabling call waiting on %s\n", ast->name);
997                         p->callwaiting = -1;
998                 }
999                 if (has_voicemail(p)) {
1000                         if (mgcpdebug) {
1001                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP mgcp_hangup(%s) on %s@%s set vmwi(+)\n", 
1002                                         ast->name, p->name, p->parent->name);
1003                         }
1004                         transmit_notify_request(sub, "L/vmwi(+)");
1005                 } else {
1006                         if (mgcpdebug) {
1007                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP mgcp_hangup(%s) on %s@%s set vmwi(-)\n", 
1008                                         ast->name, p->name, p->parent->name);
1009                         }
1010                         transmit_notify_request(sub, "L/vmwi(-)");
1011                 }
1012         }
1013         ast_mutex_unlock(&sub->lock);
1014         return 0;
1015 }
1016
1017 static int mgcp_show_endpoints(int fd, int argc, char *argv[])
1018 {
1019         struct mgcp_gateway  *g;
1020         struct mgcp_endpoint *e;
1021         int hasendpoints = 0;
1022         char iabuf[INET_ADDRSTRLEN];
1023
1024         if (argc != 3) 
1025                 return RESULT_SHOWUSAGE;
1026         ast_mutex_lock(&gatelock);
1027         g = gateways;
1028         while(g) {
1029                 e = g->endpoints;
1030                 ast_cli(fd, "Gateway '%s' at %s (%s)\n", g->name, g->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), g->addr.sin_addr) : ast_inet_ntoa(iabuf, sizeof(iabuf), g->defaddr.sin_addr), g->dynamic ? "Dynamic" : "Static");
1031                 while(e) {
1032                         /* Don't show wilcard endpoint */
1033                         if (strcmp(e->name, g->wcardep) !=0)
1034                                 ast_cli(fd, "   -- '%s@%s in '%s' is %s\n", e->name, g->name, e->context, e->sub->owner ? "active" : "idle");
1035                         hasendpoints = 1;
1036                         e = e->next;
1037                 }
1038                 if (!hasendpoints) {
1039                         ast_cli(fd, "   << No Endpoints Defined >>     ");
1040                 }
1041                 g = g->next;
1042         }
1043         ast_mutex_unlock(&gatelock);
1044         return RESULT_SUCCESS;
1045 }
1046
1047 static char show_endpoints_usage[] = 
1048 "Usage: mgcp show endpoints\n"
1049 "       Lists all endpoints known to the MGCP (Media Gateway Control Protocol) subsystem.\n";
1050
1051 static struct ast_cli_entry  cli_show_endpoints = 
1052         { { "mgcp", "show", "endpoints", NULL }, mgcp_show_endpoints, "Show defined MGCP endpoints", show_endpoints_usage };
1053
1054 static int mgcp_audit_endpoint(int fd, int argc, char *argv[])
1055 {
1056         struct mgcp_gateway  *g;
1057         struct mgcp_endpoint *e;
1058         int found = 0;
1059         char *ename,*gname, *c;
1060
1061         if (!mgcpdebug) {
1062                 return RESULT_SHOWUSAGE;
1063         }
1064         if (argc != 4) 
1065                 return RESULT_SHOWUSAGE;
1066         /* split the name into parts by null */
1067         ename = argv[3];
1068         gname = ename;
1069         while (*gname) {
1070                 if (*gname == '@') {
1071                         *gname = 0;
1072                         gname++;
1073                         break;
1074                 }
1075                 gname++;
1076         }
1077         if (gname[0] == '[')
1078                 gname++;
1079         if ((c = strrchr(gname, ']')))
1080                 *c = '\0';
1081         ast_mutex_lock(&gatelock);
1082         g = gateways;
1083         while(g) {
1084                 if (!strcasecmp(g->name, gname)) {
1085                         e = g->endpoints;
1086                         while(e) {
1087                                 if (!strcasecmp(e->name, ename)) {
1088                                         found = 1;
1089                                         transmit_audit_endpoint(e);
1090                                         break;
1091                                 }
1092                                 e = e->next;
1093                         }
1094                         if (found) {
1095                                 break;
1096                         }
1097                 }
1098                 g = g->next;
1099         }
1100         if (!found) {
1101                 ast_cli(fd, "   << Could not find endpoint >>     ");
1102         }
1103         ast_mutex_unlock(&gatelock);
1104         return RESULT_SUCCESS;
1105 }
1106
1107 static char audit_endpoint_usage[] = 
1108 "Usage: mgcp audit endpoint <endpointid>\n"
1109 "       Lists the capabilities of an endpoint in the MGCP (Media Gateway Control Protocol) subsystem.\n"
1110 "       mgcp debug MUST be on to see the results of this command.\n";
1111
1112 static struct ast_cli_entry  cli_audit_endpoint = 
1113         { { "mgcp", "audit", "endpoint", NULL }, mgcp_audit_endpoint, "Audit specified MGCP endpoint", audit_endpoint_usage };
1114
1115 static int mgcp_answer(struct ast_channel *ast)
1116 {
1117         int res = 0;
1118         struct mgcp_subchannel *sub = ast->tech_pvt;
1119         struct mgcp_endpoint *p = sub->parent;
1120
1121         ast_mutex_lock(&sub->lock);
1122         sub->cxmode = MGCP_CX_SENDRECV;
1123         if (!sub->rtp) {
1124                 start_rtp(sub);
1125         } else {
1126                 transmit_modify_request(sub);
1127         }
1128         /* verbose level check */
1129         if (option_verbose > 2) {
1130                 ast_verbose(VERBOSE_PREFIX_3 "MGCP mgcp_answer(%s) on %s@%s-%d\n", 
1131                         ast->name, p->name, p->parent->name, sub->id);
1132         }
1133         if (ast->_state != AST_STATE_UP) {
1134                 ast_setstate(ast, AST_STATE_UP);
1135                 if (option_debug)
1136                         ast_log(LOG_DEBUG, "mgcp_answer(%s)\n", ast->name);
1137                 transmit_notify_request(sub, "");
1138                 transmit_modify_request(sub);
1139         }
1140         ast_mutex_unlock(&sub->lock);
1141         return res;
1142 }
1143
1144 static struct ast_frame *mgcp_rtp_read(struct mgcp_subchannel *sub)
1145 {
1146         /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
1147         struct ast_frame *f;
1148
1149         f = ast_rtp_read(sub->rtp);
1150         /* Don't send RFC2833 if we're not supposed to */
1151         if (f && (f->frametype == AST_FRAME_DTMF) && !(sub->parent->dtmfmode & MGCP_DTMF_RFC2833))
1152                 return &ast_null_frame;
1153         if (sub->owner) {
1154                 /* We already hold the channel lock */
1155                 if (f->frametype == AST_FRAME_VOICE) {
1156                         if (f->subclass != sub->owner->nativeformats) {
1157                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1158                                 sub->owner->nativeformats = f->subclass;
1159                                 ast_set_read_format(sub->owner, sub->owner->readformat);
1160                                 ast_set_write_format(sub->owner, sub->owner->writeformat);
1161                         }
1162                         /* Courtesy fearnor aka alex@pilosoft.com */
1163                         if ((sub->parent->dtmfmode & MGCP_DTMF_INBAND) && (sub->parent->dsp)) {
1164 #if 0
1165                                 ast_log(LOG_NOTICE, "MGCP ast_dsp_process\n");
1166 #endif
1167                                 f = ast_dsp_process(sub->owner, sub->parent->dsp, f);
1168                         }
1169                 }
1170         }
1171         return f;
1172 }
1173
1174
1175 static struct ast_frame *mgcp_read(struct ast_channel *ast)
1176 {
1177         struct ast_frame *f;
1178         struct mgcp_subchannel *sub = ast->tech_pvt;
1179         ast_mutex_lock(&sub->lock);
1180         f = mgcp_rtp_read(sub);
1181         ast_mutex_unlock(&sub->lock);
1182         return f;
1183 }
1184
1185 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame)
1186 {
1187         struct mgcp_subchannel *sub = ast->tech_pvt;
1188         int res = 0;
1189         if (frame->frametype != AST_FRAME_VOICE) {
1190                 if (frame->frametype == AST_FRAME_IMAGE)
1191                         return 0;
1192                 else {
1193                         ast_log(LOG_WARNING, "Can't send %d type frames with MGCP write\n", frame->frametype);
1194                         return 0;
1195                 }
1196         } else {
1197                 if (!(frame->subclass & ast->nativeformats)) {
1198                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1199                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1200                         return -1;
1201                 }
1202         }
1203         if (sub) {
1204                 ast_mutex_lock(&sub->lock);
1205                 if ((sub->parent->sub == sub) || !sub->parent->singlepath) {
1206                         if (sub->rtp) {
1207                                 res =  ast_rtp_write(sub->rtp, frame);
1208                         }
1209                 }
1210                 ast_mutex_unlock(&sub->lock);
1211         }
1212         return res;
1213 }
1214
1215 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1216 {
1217         struct mgcp_subchannel *sub = newchan->tech_pvt;
1218
1219         ast_mutex_lock(&sub->lock);
1220         ast_log(LOG_NOTICE, "mgcp_fixup(%s, %s)\n", oldchan->name, newchan->name);
1221         if (sub->owner != oldchan) {
1222                 ast_mutex_unlock(&sub->lock);
1223                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
1224                 return -1;
1225         }
1226         sub->owner = newchan;
1227         ast_mutex_unlock(&sub->lock);
1228         return 0;
1229 }
1230
1231 static int mgcp_senddigit(struct ast_channel *ast, char digit)
1232 {
1233         struct mgcp_subchannel *sub = ast->tech_pvt;
1234         char tmp[4];
1235
1236         tmp[0] = 'D';
1237         tmp[1] = '/';
1238         tmp[2] = digit;
1239         tmp[3] = '\0';
1240         ast_mutex_lock(&sub->lock);
1241         transmit_notify_request(sub, tmp);
1242         ast_mutex_unlock(&sub->lock);
1243         return -1;
1244 }
1245
1246 /*!
1247  *  \brief  mgcp_devicestate: channel callback for device status monitoring
1248  *  \param  data tech/resource name of MGCP device to query
1249  *
1250  * Callback for device state management in channel subsystem
1251  * to obtain device status (up/down) of a specific MGCP endpoint
1252  *
1253  *  \return device status result (from devicestate.h) AST_DEVICE_INVALID (not available) or AST_DEVICE_UNKNOWN (available but unknown state)
1254  */
1255 static int mgcp_devicestate(void *data)
1256 {
1257         struct mgcp_gateway  *g;
1258         struct mgcp_endpoint *e = NULL;
1259         char *tmp, *endpt, *gw;
1260         int ret = AST_DEVICE_INVALID;
1261
1262         endpt = ast_strdupa(data);
1263         if ((tmp = strchr(endpt, '@'))) {
1264                 *tmp++ = '\0';
1265                 gw = tmp;
1266         } else
1267                 goto error;
1268
1269         ast_mutex_lock(&gatelock);
1270         g = gateways;
1271         while (g) {
1272                 if (strcasecmp(g->name, gw) == 0) {
1273                         e = g->endpoints;
1274                         break;
1275                 }
1276                 g = g->next;
1277         }
1278
1279         if (!e)
1280                 goto error;
1281
1282         while (e) {
1283                 if (strcasecmp(e->name, endpt) == 0)
1284                         break;
1285                 e = e->next;
1286         }
1287
1288         if (!e)
1289                 goto error;
1290
1291         /*
1292          * As long as the gateway/endpoint is valid, we'll
1293          * assume that the device is available and its state
1294          * can be tracked.
1295          */
1296         ret = AST_DEVICE_UNKNOWN;
1297
1298 error:
1299         ast_mutex_unlock(&gatelock);
1300         return ret;
1301 }
1302
1303 static char *control2str(int ind) {
1304         switch (ind) {
1305         case AST_CONTROL_HANGUP:
1306                 return "Other end has hungup";
1307         case AST_CONTROL_RING:
1308                 return "Local ring";
1309         case AST_CONTROL_RINGING:
1310                 return "Remote end is ringing";
1311         case AST_CONTROL_ANSWER:
1312                 return "Remote end has answered";
1313         case AST_CONTROL_BUSY:
1314                 return "Remote end is busy";
1315         case AST_CONTROL_TAKEOFFHOOK:
1316                 return "Make it go off hook";
1317         case AST_CONTROL_OFFHOOK:
1318                 return "Line is off hook";
1319         case AST_CONTROL_CONGESTION:
1320                 return "Congestion (circuits busy)";
1321         case AST_CONTROL_FLASH:
1322                 return "Flash hook";
1323         case AST_CONTROL_WINK:
1324                 return "Wink";
1325         case AST_CONTROL_OPTION:
1326                 return "Set a low-level option";
1327         case AST_CONTROL_RADIO_KEY:
1328                 return "Key Radio";
1329         case AST_CONTROL_RADIO_UNKEY:
1330                 return "Un-Key Radio";
1331         }
1332         return "UNKNOWN";
1333 }
1334
1335 static int mgcp_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen)
1336 {
1337         struct mgcp_subchannel *sub = ast->tech_pvt;
1338         int res = 0;
1339
1340         if (mgcpdebug) {
1341                 ast_verbose(VERBOSE_PREFIX_3 "MGCP asked to indicate %d '%s' condition on channel %s\n",
1342                         ind, control2str(ind), ast->name);
1343         }
1344         ast_mutex_lock(&sub->lock);
1345         switch(ind) {
1346         case AST_CONTROL_RINGING:
1347 #ifdef DLINK_BUGGY_FIRMWARE     
1348                 transmit_notify_request(sub, "rt");
1349 #else
1350                 transmit_notify_request(sub, "G/rt");
1351 #endif          
1352                 break;
1353         case AST_CONTROL_BUSY:
1354                 transmit_notify_request(sub, "L/bz");
1355                 break;
1356         case AST_CONTROL_CONGESTION:
1357                 transmit_notify_request(sub, "G/cg");
1358                 break;
1359         case AST_CONTROL_HOLD:
1360                 ast_moh_start(ast, data, NULL);
1361                 break;
1362         case AST_CONTROL_UNHOLD:
1363                 ast_moh_stop(ast);
1364                 break;
1365         case -1:
1366                 transmit_notify_request(sub, "");
1367                 break;
1368         default:
1369                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
1370                 res = -1;
1371         }
1372         ast_mutex_unlock(&sub->lock);
1373         return res;
1374 }
1375
1376 static struct ast_channel *mgcp_new(struct mgcp_subchannel *sub, int state)
1377 {
1378         struct ast_channel *tmp;
1379         struct mgcp_endpoint *i = sub->parent;
1380         int fmt;
1381
1382         tmp = ast_channel_alloc(1);
1383         if (tmp) {
1384                 tmp->tech = &mgcp_tech;
1385                 tmp->nativeformats = i->capability;
1386                 if (!tmp->nativeformats)
1387                         tmp->nativeformats = capability;
1388                 fmt = ast_best_codec(tmp->nativeformats);
1389                 ast_string_field_build(tmp, name, "MGCP/%s@%s-%d", i->name, i->parent->name, sub->id);
1390                 if (sub->rtp)
1391                         tmp->fds[0] = ast_rtp_fd(sub->rtp);
1392                 if (i->dtmfmode & (MGCP_DTMF_INBAND | MGCP_DTMF_HYBRID)) {
1393                         i->dsp = ast_dsp_new();
1394                         ast_dsp_set_features(i->dsp,DSP_FEATURE_DTMF_DETECT);
1395                         /* this is to prevent clipping of dtmf tones during dsp processing */
1396                         ast_dsp_digitmode(i->dsp, DSP_DIGITMODE_NOQUELCH);
1397                 } else {
1398                         i->dsp = NULL;
1399                 }
1400                 ast_setstate(tmp, state);
1401                 if (state == AST_STATE_RING)
1402                         tmp->rings = 1;
1403                 tmp->writeformat = fmt;
1404                 tmp->rawwriteformat = fmt;
1405                 tmp->readformat = fmt;
1406                 tmp->rawreadformat = fmt;
1407                 tmp->tech_pvt = sub;
1408                 if (!ast_strlen_zero(i->language))
1409                         ast_string_field_set(tmp, language, i->language);
1410                 if (!ast_strlen_zero(i->accountcode))
1411                         ast_string_field_set(tmp, accountcode, i->accountcode);
1412                 if (i->amaflags)
1413                         tmp->amaflags = i->amaflags;
1414                 sub->owner = tmp;
1415                 ast_atomic_fetchadd_int(&__mod_desc->usecnt, +1);
1416                 ast_update_use_count();
1417                 tmp->callgroup = i->callgroup;
1418                 tmp->pickupgroup = i->pickupgroup;
1419                 ast_string_field_set(tmp, call_forward, i->call_forward);
1420                 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
1421                 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
1422                 ast_set_callerid(tmp, i->cid_num, i->cid_name, i->cid_num);
1423                 if (!i->adsi)
1424                         tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1425                 tmp->priority = 1;
1426                 if (state != AST_STATE_DOWN) {
1427                         if (ast_pbx_start(tmp)) {
1428                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1429                                 ast_hangup(tmp);
1430                                 tmp = NULL;
1431                         }
1432                 }
1433                 /* verbose level check */
1434                 if (option_verbose > 2) {
1435                         ast_verbose(VERBOSE_PREFIX_3 "MGCP mgcp_new(%s) created in state: %s\n",
1436                                 tmp->name, ast_state2str(state));
1437                 }
1438
1439                 /* Configure the new channel jb */
1440                 if (tmp && sub && sub->rtp)
1441                         ast_jb_configure(tmp, &global_jbconf);
1442         } else {
1443                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1444         }
1445         return tmp;
1446 }
1447
1448 static char* get_sdp_by_line(char* line, char *name, int nameLen)
1449 {
1450         if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1451                 char* r = line + nameLen + 1;
1452                 while (*r && (*r < 33)) ++r;
1453                 return r;
1454         }
1455         return "";
1456 }
1457
1458 static char *get_sdp(struct mgcp_request *req, char *name)
1459 {
1460         int x;
1461         int len = strlen(name);
1462         char *r;
1463
1464         for (x=0; x<req->lines; x++) {
1465                 r = get_sdp_by_line(req->line[x], name, len);
1466                 if (r[0] != '\0') return r;
1467         }
1468         return "";
1469 }
1470
1471 static void sdpLineNum_iterator_init(int* iterator)
1472 {
1473         *iterator = 0;
1474 }
1475
1476 static char* get_sdp_iterate(int* iterator, struct mgcp_request *req, char *name)
1477 {
1478         int len = strlen(name);
1479         char *r;
1480         while (*iterator < req->lines) {
1481                 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1482                 if (r[0] != '\0') return r;
1483         }
1484         return "";
1485 }
1486
1487 static char *__get_header(struct mgcp_request *req, char *name, int *start)
1488 {
1489         int x;
1490         int len = strlen(name);
1491         char *r;
1492         for (x=*start;x<req->headers;x++) {
1493                 if (!strncasecmp(req->header[x], name, len) && 
1494                     (req->header[x][len] == ':')) {
1495                         r = req->header[x] + len + 1;
1496                         while(*r && (*r < 33))
1497                                 r++;
1498                         *start = x+1;
1499                         return r;
1500                 }
1501         }
1502         /* Don't return NULL, so get_header is always a valid pointer */
1503         return "";
1504 }
1505
1506 static char *get_header(struct mgcp_request *req, char *name)
1507 {
1508         int start = 0;
1509         return __get_header(req, name, &start);
1510 }
1511
1512 /*! \brief get_csv: (SC:) get comma separated value */
1513 static char *get_csv(char *c, int *len, char **next) 
1514 {
1515         char *s;
1516
1517         *next = NULL, *len = 0;
1518         if (!c) return NULL;
1519
1520         while (*c && (*c < 33 || *c == ','))
1521                 c++;
1522
1523         s = c;
1524         while (*c && (*c >= 33 && *c != ','))
1525                 c++, (*len)++;
1526         *next = c;
1527
1528         if (*len == 0)
1529                 s = NULL, *next = NULL;
1530
1531         return s;
1532 }
1533
1534 static struct mgcp_subchannel *find_subchannel_and_lock(char *name, int msgid, struct sockaddr_in *sin)
1535 {
1536         struct mgcp_endpoint *p = NULL;
1537         struct mgcp_subchannel *sub = NULL;
1538         struct mgcp_gateway *g;
1539         char iabuf[INET_ADDRSTRLEN];
1540         char tmp[256] = "";
1541         char *at = NULL, *c;
1542         int found = 0;
1543         if (name) {
1544                 ast_copy_string(tmp, name, sizeof(tmp));
1545                 at = strchr(tmp, '@');
1546                 if (!at) {
1547                         ast_log(LOG_NOTICE, "Endpoint '%s' has no at sign!\n", name);
1548                         return NULL;
1549                 }
1550                 *at++ = '\0';
1551         }
1552         ast_mutex_lock(&gatelock);
1553         if (at && (at[0] == '[')) {
1554                 at++;
1555                 c = strrchr(at, ']');
1556                 if (c)
1557                         *c = '\0';
1558         }
1559         g = gateways;
1560         while(g) {
1561                 if ((!name || !strcasecmp(g->name, at)) && 
1562                     (sin || g->addr.sin_addr.s_addr || g->defaddr.sin_addr.s_addr)) {
1563                         /* Found the gateway.  If it's dynamic, save it's address -- now for the endpoint */
1564                         if (sin && g->dynamic && name) {
1565                                 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1566                                         (g->addr.sin_port != sin->sin_port)) {
1567                                         memcpy(&g->addr, sin, sizeof(g->addr));
1568                                         if (ast_ouraddrfor(&g->addr.sin_addr, &g->ourip))
1569                                                 memcpy(&g->ourip, &__ourip, sizeof(g->ourip));
1570                                         if (option_verbose > 2)
1571                                                 ast_verbose(VERBOSE_PREFIX_3 "Registered MGCP gateway '%s' at %s port %d\n", g->name, ast_inet_ntoa(iabuf, sizeof(iabuf), g->addr.sin_addr), ntohs(g->addr.sin_port));
1572                                 }
1573                         }
1574                         /* not dynamic, check if the name matches */
1575                         else if (name) {
1576                                 if (strcasecmp(g->name, at)) {
1577                                         g = g->next;
1578                                         continue;
1579                                 }
1580                         }
1581                         /* not dynamic, no name, check if the addr matches */
1582                         else if (!name && sin) {
1583                                 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1584                                     (g->addr.sin_port != sin->sin_port)) {
1585                                         g = g->next;
1586                                         continue;
1587                                 }
1588                         } else {
1589                                 g = g->next;
1590                                 continue;
1591                         }
1592                         /* SC */
1593                         p = g->endpoints;
1594                         while(p) {
1595                                 if (option_debug)
1596                                         ast_log(LOG_DEBUG, "Searching on %s@%s for subchannel\n",
1597                                                 p->name, g->name);
1598                                 if (msgid) {
1599 #if 0 /* new transport mech */
1600                                         sub = p->sub;
1601                                         do {
1602                                                 if (option_debug)
1603                                                         ast_log(LOG_DEBUG, "Searching on %s@%s-%d for subchannel with lastout: %d\n",
1604                                                                 p->name, g->name, sub->id, msgid);
1605                                                 if (sub->lastout == msgid) {
1606                                                         if (option_debug)
1607                                                                 ast_log(LOG_DEBUG, "Found subchannel sub%d to handle request %d sub->lastout: %d\n",
1608                                                                         sub->id, msgid, sub->lastout);
1609                                                         found = 1;
1610                                                         break;
1611                                                 }
1612                                                 sub = sub->next;
1613                                         } while (sub != p->sub);
1614                                         if (found) {
1615                                                 break;
1616                                         }
1617 #endif
1618                                         /* SC */
1619                                         sub = p->sub;
1620                                         found = 1;
1621                                         /* SC */
1622                                         break;
1623                                 } else if (name && !strcasecmp(p->name, tmp)) {
1624                                         ast_log(LOG_DEBUG, "Coundn't determine subchannel, assuming current master %s@%s-%d\n", 
1625                                                 p->name, g->name, p->sub->id);
1626                                         sub = p->sub;
1627                                         found = 1;
1628                                         break;
1629                                 }
1630                                 p = p->next;
1631                         }
1632                         if (sub && found) {
1633                                 ast_mutex_lock(&sub->lock);
1634                                 break;
1635                         }
1636                 }
1637                 g = g->next;
1638         }
1639         ast_mutex_unlock(&gatelock);
1640         if (!sub) {
1641                 if (name) {
1642                         if (g)
1643                                 ast_log(LOG_NOTICE, "Endpoint '%s' not found on gateway '%s'\n", tmp, at);
1644                         else
1645                                 ast_log(LOG_NOTICE, "Gateway '%s' (and thus its endpoint '%s') does not exist\n", at, tmp);
1646                 } 
1647         }
1648         return sub;
1649 }
1650
1651 static void parse(struct mgcp_request *req)
1652 {
1653         /* Divide fields by NULL's */
1654         char *c;
1655         int f = 0;
1656         c = req->data;
1657
1658         /* First header starts immediately */
1659         req->header[f] = c;
1660         while(*c) {
1661                 if (*c == '\n') {
1662                         /* We've got a new header */
1663                         *c = 0;
1664 #if 0
1665                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1666 #endif                  
1667                         if (ast_strlen_zero(req->header[f])) {
1668                                 /* Line by itself means we're now in content */
1669                                 c++;
1670                                 break;
1671                         }
1672                         if (f >= MGCP_MAX_HEADERS - 1) {
1673                                 ast_log(LOG_WARNING, "Too many MGCP headers...\n");
1674                         } else
1675                                 f++;
1676                         req->header[f] = c + 1;
1677                 } else if (*c == '\r') {
1678                         /* Ignore but eliminate \r's */
1679                         *c = 0;
1680                 }
1681                 c++;
1682         }
1683         /* Check for last header */
1684         if (!ast_strlen_zero(req->header[f])) 
1685                 f++;
1686         req->headers = f;
1687         /* Now we process any mime content */
1688         f = 0;
1689         req->line[f] = c;
1690         while(*c) {
1691                 if (*c == '\n') {
1692                         /* We've got a new line */
1693                         *c = 0;
1694 #if 0
1695                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1696 #endif                  
1697                         if (f >= MGCP_MAX_LINES - 1) {
1698                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1699                         } else
1700                                 f++;
1701                         req->line[f] = c + 1;
1702                 } else if (*c == '\r') {
1703                         /* Ignore and eliminate \r's */
1704                         *c = 0;
1705                 }
1706                 c++;
1707         }
1708         /* Check for last line */
1709         if (!ast_strlen_zero(req->line[f])) 
1710                 f++;
1711         req->lines = f;
1712         /* Parse up the initial header */
1713         c = req->header[0];
1714         while(*c && *c < 33) c++;
1715         /* First the verb */
1716         req->verb = c;
1717         while(*c && (*c > 32)) c++;
1718         if (*c) {
1719                 *c = '\0';
1720                 c++;
1721                 while(*c && (*c < 33)) c++;
1722                 req->identifier = c;
1723                 while(*c && (*c > 32)) c++;
1724                 if (*c) {
1725                         *c = '\0';
1726                         c++;
1727                         while(*c && (*c < 33)) c++;
1728                         req->endpoint = c;
1729                         while(*c && (*c > 32)) c++;
1730                         if (*c) {
1731                                 *c = '\0';
1732                                 c++;
1733                                 while(*c && (*c < 33)) c++;
1734                                 req->version = c;
1735                                 while(*c && (*c > 32)) c++;
1736                                 while(*c && (*c < 33)) c++;
1737                                 while(*c && (*c > 32)) c++;
1738                                 *c = '\0';
1739                         }
1740                 }
1741         }
1742                 
1743         if (mgcpdebug) {
1744                 ast_verbose("Verb: '%s', Identifier: '%s', Endpoint: '%s', Version: '%s'\n",
1745                         req->verb, req->identifier, req->endpoint, req->version);
1746                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1747         }
1748         if (*c) 
1749                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1750 }
1751
1752 static int process_sdp(struct mgcp_subchannel *sub, struct mgcp_request *req)
1753 {
1754         char *m;
1755         char *c;
1756         char *a;
1757         char host[258];
1758         int len;
1759         int portno;
1760         int peercapability, peerNonCodecCapability;
1761         struct sockaddr_in sin;
1762         char *codecs;
1763         struct ast_hostent ahp; struct hostent *hp;
1764         int codec, codec_count=0;
1765         int iterator;
1766         struct mgcp_endpoint *p = sub->parent;
1767
1768         /* Get codec and RTP info from SDP */
1769         m = get_sdp(req, "m");
1770         c = get_sdp(req, "c");
1771         if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
1772                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1773                 return -1;
1774         }
1775         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1776                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1777                 return -1;
1778         }
1779         /* XXX This could block for a long time, and block the main thread! XXX */
1780         hp = ast_gethostbyname(host, &ahp);
1781         if (!hp) {
1782                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1783                 return -1;
1784         }
1785         if (sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) {
1786                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
1787                 return -1;
1788         }
1789         sin.sin_family = AF_INET;
1790         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1791         sin.sin_port = htons(portno);
1792         ast_rtp_set_peer(sub->rtp, &sin);
1793 #if 0
1794         printf("Peer RTP is at port %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
1795 #endif  
1796         /* Scan through the RTP payload types specified in a "m=" line: */
1797         ast_rtp_pt_clear(sub->rtp);
1798         codecs = ast_strdupa(m + len);
1799         while (!ast_strlen_zero(codecs)) {
1800                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1801                         if (codec_count)
1802                                 break;
1803                         ast_log(LOG_WARNING, "Error in codec string '%s' at '%s'\n", m, codecs);
1804                         return -1;
1805                 }
1806                 ast_rtp_set_m_type(sub->rtp, codec);
1807                 codec_count++;
1808                 codecs += len;
1809         }
1810
1811         /* Next, scan through each "a=rtpmap:" line, noting each */
1812         /* specified RTP payload type (with corresponding MIME subtype): */
1813         sdpLineNum_iterator_init(&iterator);
1814         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1815                 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
1816                 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2)
1817                         continue;
1818                 /* Note: should really look at the 'freq' and '#chans' params too */
1819                 ast_rtp_set_rtpmap_type(sub->rtp, codec, "audio", mimeSubtype, 0);
1820         }
1821
1822         /* Now gather all of the codecs that were asked for: */
1823         ast_rtp_get_current_formats(sub->rtp, &peercapability, &peerNonCodecCapability);
1824         p->capability = capability & peercapability;
1825         if (mgcpdebug) {
1826                 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1827                         capability, peercapability, p->capability);
1828                 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1829                         nonCodecCapability, peerNonCodecCapability, p->nonCodecCapability);
1830         }
1831         if (!p->capability) {
1832                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1833                 return -1;
1834         }
1835         return 0;
1836 }
1837
1838 static int add_header(struct mgcp_request *req, char *var, char *value)
1839 {
1840         if (req->len >= sizeof(req->data) - 4) {
1841                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1842                 return -1;
1843         }
1844         if (req->lines) {
1845                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1846                 return -1;
1847         }
1848         req->header[req->headers] = req->data + req->len;
1849         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s: %s\r\n", var, value);
1850         req->len += strlen(req->header[req->headers]);
1851         if (req->headers < MGCP_MAX_HEADERS)
1852                 req->headers++;
1853         else {
1854                 ast_log(LOG_WARNING, "Out of header space\n");
1855                 return -1;
1856         }
1857         return 0;       
1858 }
1859
1860 static int add_line(struct mgcp_request *req, char *line)
1861 {
1862         if (req->len >= sizeof(req->data) - 4) {
1863                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1864                 return -1;
1865         }
1866         if (!req->lines) {
1867                 /* Add extra empty return */
1868                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1869                 req->len += strlen(req->data + req->len);
1870         }
1871         req->line[req->lines] = req->data + req->len;
1872         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1873         req->len += strlen(req->line[req->lines]);
1874         if (req->lines < MGCP_MAX_LINES)
1875                 req->lines++;
1876         else {
1877                 ast_log(LOG_WARNING, "Out of line space\n");
1878                 return -1;
1879         }
1880         return 0;       
1881 }
1882
1883 static int init_resp(struct mgcp_request *req, char *resp, struct mgcp_request *orig, char *resprest)
1884 {
1885         /* Initialize a response */
1886         if (req->headers || req->len) {
1887                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1888                 return -1;
1889         }
1890         req->header[req->headers] = req->data + req->len;
1891         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s %s\r\n", resp, orig->identifier, resprest);
1892         req->len += strlen(req->header[req->headers]);
1893         if (req->headers < MGCP_MAX_HEADERS)
1894                 req->headers++;
1895         else
1896                 ast_log(LOG_WARNING, "Out of header space\n");
1897         return 0;
1898 }
1899
1900 static int init_req(struct mgcp_endpoint *p, struct mgcp_request *req, char *verb)
1901 {
1902         /* Initialize a response */
1903         if (req->headers || req->len) {
1904                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1905                 return -1;
1906         }
1907         req->header[req->headers] = req->data + req->len;
1908         /* check if we need brackets around the gw name */
1909         if (p->parent->isnamedottedip)
1910                 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %d %s@[%s] MGCP 1.0\r\n", verb, oseq, p->name, p->parent->name);
1911         else
1912                 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %d %s@%s MGCP 1.0\r\n", verb, oseq, p->name, p->parent->name);
1913         req->len += strlen(req->header[req->headers]);
1914         if (req->headers < MGCP_MAX_HEADERS)
1915                 req->headers++;
1916         else
1917                 ast_log(LOG_WARNING, "Out of header space\n");
1918         return 0;
1919 }
1920
1921
1922 static int respprep(struct mgcp_request *resp, struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest)
1923 {
1924         memset(resp, 0, sizeof(*resp));
1925         init_resp(resp, msg, req, msgrest);
1926         return 0;
1927 }
1928
1929 static int reqprep(struct mgcp_request *req, struct mgcp_endpoint *p, char *verb)
1930 {
1931         memset(req, 0, sizeof(struct mgcp_request));
1932         oseq++;
1933         if (oseq > 999999999)
1934                 oseq = 1;
1935         init_req(p, req, verb);
1936         return 0;
1937 }
1938
1939 static int transmit_response(struct mgcp_subchannel *sub, char *msg, struct mgcp_request *req, char *msgrest)
1940 {
1941         struct mgcp_request resp;
1942         struct mgcp_endpoint *p = sub->parent;
1943         struct mgcp_response *mgr;
1944
1945         respprep(&resp, p, msg, req, msgrest);
1946         mgr = malloc(sizeof(struct mgcp_response) + resp.len + 1);
1947         if (mgr) {
1948                 /* Store MGCP response in case we have to retransmit */
1949                 memset(mgr, 0, sizeof(struct mgcp_response));
1950                 sscanf(req->identifier, "%d", &mgr->seqno);
1951                 time(&mgr->whensent);
1952                 mgr->len = resp.len;
1953                 memcpy(mgr->buf, resp.data, resp.len);
1954                 mgr->buf[resp.len] = '\0';
1955                 mgr->next = p->parent->responses;
1956                 p->parent->responses = mgr;
1957         }
1958         return send_response(sub, &resp);
1959 }
1960
1961
1962 static int add_sdp(struct mgcp_request *resp, struct mgcp_subchannel *sub, struct ast_rtp *rtp)
1963 {
1964         int len;
1965         int codec;
1966         char costr[80];
1967         struct sockaddr_in sin;
1968         char v[256];
1969         char s[256];
1970         char o[256];
1971         char c[256];
1972         char t[256];
1973         char m[256] = "";
1974         char a[1024] = "";
1975         char iabuf[INET_ADDRSTRLEN];
1976         int x;
1977         struct sockaddr_in dest;
1978         struct mgcp_endpoint *p = sub->parent;
1979         /* XXX We break with the "recommendation" and send our IP, in order that our
1980                peer doesn't have to ast_gethostbyname() us XXX */
1981         len = 0;
1982         if (!sub->rtp) {
1983                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1984                 return -1;
1985         }
1986         ast_rtp_get_us(sub->rtp, &sin);
1987         if (rtp) {
1988                 ast_rtp_get_peer(rtp, &dest);
1989         } else {
1990                 if (sub->tmpdest.sin_addr.s_addr) {
1991                         dest.sin_addr = sub->tmpdest.sin_addr;
1992                         dest.sin_port = sub->tmpdest.sin_port;
1993                         /* Reset temporary destination */
1994                         memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
1995                 } else {
1996                         dest.sin_addr = p->parent->ourip;
1997                         dest.sin_port = sin.sin_port;
1998                 }
1999         }
2000         if (mgcpdebug) {
2001                 ast_verbose("We're at %s port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->parent->ourip), ntohs(sin.sin_port));
2002         }
2003         snprintf(v, sizeof(v), "v=0\r\n");
2004         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), ast_inet_ntoa(iabuf, sizeof(iabuf), dest.sin_addr));
2005         snprintf(s, sizeof(s), "s=session\r\n");
2006         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(iabuf, sizeof(iabuf), dest.sin_addr));
2007         snprintf(t, sizeof(t), "t=0 0\r\n");
2008         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2009         for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2010                 if (p->capability & x) {
2011                         if (mgcpdebug) {
2012                                 ast_verbose("Answering with capability %d\n", x);
2013                         }
2014                         codec = ast_rtp_lookup_code(sub->rtp, 1, x);
2015                         if (codec > -1) {
2016                                 snprintf(costr, sizeof(costr), " %d", codec);
2017                                 strncat(m, costr, sizeof(m) - strlen(m) - 1);
2018                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x, 0));
2019                                 strncat(a, costr, sizeof(a) - strlen(a) - 1);
2020                         }
2021                 }
2022         }
2023         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2024                 if (p->nonCodecCapability & x) {
2025                         if (mgcpdebug) {
2026                                 ast_verbose("Answering with non-codec capability %d\n", x);
2027                         }
2028                         codec = ast_rtp_lookup_code(sub->rtp, 0, x);
2029                         if (codec > -1) {
2030                                 snprintf(costr, sizeof(costr), " %d", codec);
2031                                 strncat(m, costr, sizeof(m) - strlen(m) - 1);
2032                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x, 0));
2033                                 strncat(a, costr, sizeof(a) - strlen(a) - 1);
2034                                 if (x == AST_RTP_DTMF) {
2035                                         /* Indicate we support DTMF...  Not sure about 16,
2036                                            but MSN supports it so dang it, we will too... */
2037                                         snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n", codec);
2038                                         strncat(a, costr, sizeof(a) - strlen(a) - 1);
2039                                 }
2040                         }
2041                 }
2042         }
2043         strncat(m, "\r\n", sizeof(m) - strlen(m) - 1);
2044         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2045         snprintf(costr, sizeof(costr), "%d", len);
2046         add_line(resp, v);
2047         add_line(resp, o);
2048         add_line(resp, s);
2049         add_line(resp, c);
2050         add_line(resp, t);
2051         add_line(resp, m);
2052         add_line(resp, a);
2053         return 0;
2054 }
2055
2056 static int transmit_modify_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp *rtp, int codecs)
2057 {
2058         struct mgcp_request resp;
2059         char local[256];
2060         char tmp[80];
2061         int x;
2062         int capability;
2063         struct mgcp_endpoint *p = sub->parent;
2064
2065         capability = p->capability;
2066         if (codecs)
2067                 capability = codecs;
2068         if (ast_strlen_zero(sub->cxident) && rtp) {
2069                 /* We don't have a CXident yet, store the destination and
2070                    wait a bit */
2071                 ast_rtp_get_peer(rtp, &sub->tmpdest);
2072                 return 0;
2073         }
2074         snprintf(local, sizeof(local), "p:20");
2075         for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2076                 if (p->capability & x) {
2077                         snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype(1, x, 0));
2078                         strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2079                 }
2080         }
2081         reqprep(&resp, p, "MDCX");
2082         add_header(&resp, "C", sub->callid);
2083         add_header(&resp, "L", local);
2084         add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2085         /* X header should not be sent. kept for compatibility */
2086         add_header(&resp, "X", sub->txident);
2087         add_header(&resp, "I", sub->cxident);
2088         /*add_header(&resp, "S", "");*/
2089         add_sdp(&resp, sub, rtp);
2090         /* fill in new fields */
2091         resp.cmd = MGCP_CMD_MDCX;
2092         resp.trid = oseq;
2093         return send_request(p, sub, &resp, oseq); /* SC */
2094 }
2095
2096 static int transmit_connect_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp *rtp)
2097 {
2098         struct mgcp_request resp;
2099         char local[256];
2100         char tmp[80];
2101         int x;
2102         struct mgcp_endpoint *p = sub->parent;
2103
2104         snprintf(local, sizeof(local), "p:20");
2105         for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2106                 if (p->capability & x) {
2107                         snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype(1, x, 0));
2108                         strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2109                 }
2110         }
2111         if (mgcpdebug) {
2112                 ast_verbose(VERBOSE_PREFIX_3 "Creating connection for %s@%s-%d in cxmode: %s callid: %s\n", 
2113                         p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2114         }
2115         reqprep(&resp, p, "CRCX");
2116         add_header(&resp, "C", sub->callid);
2117         add_header(&resp, "L", local);
2118         add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2119         /* X header should not be sent. kept for compatibility */
2120         add_header(&resp, "X", sub->txident);
2121         /*add_header(&resp, "S", "");*/
2122         add_sdp(&resp, sub, rtp);
2123         /* fill in new fields */
2124         resp.cmd = MGCP_CMD_CRCX;
2125         resp.trid = oseq;
2126         return send_request(p, sub, &resp, oseq);  /* SC */
2127 }
2128
2129 static int transmit_notify_request(struct mgcp_subchannel *sub, char *tone)
2130 {
2131         struct mgcp_request resp;
2132         struct mgcp_endpoint *p = sub->parent;
2133
2134         if (mgcpdebug) {
2135                 ast_verbose(VERBOSE_PREFIX_3 "MGCP Asked to indicate tone: %s on  %s@%s-%d in cxmode: %s\n", 
2136                         tone, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
2137         }
2138         ast_copy_string(p->curtone, tone, sizeof(p->curtone));
2139         reqprep(&resp, p, "RQNT");
2140         add_header(&resp, "X", p->rqnt_ident); /* SC */
2141         switch (p->hookstate) {
2142         case MGCP_ONHOOK:
2143                 add_header(&resp, "R", "L/hd(N)");
2144                 break;
2145         case MGCP_OFFHOOK:
2146                 add_header(&resp, "R", (sub->rtp && (p->dtmfmode & MGCP_DTMF_INBAND)) ? "L/hu(N),L/hf(N)" : "L/hu(N),L/hf(N),D/[0-9#*](N)");
2147                 break;
2148         }
2149         if (!ast_strlen_zero(tone)) {
2150                 add_header(&resp, "S", tone);
2151         }
2152         /* fill in new fields */
2153         resp.cmd = MGCP_CMD_RQNT;
2154         resp.trid = oseq;
2155         return send_request(p, NULL, &resp, oseq); /* SC */
2156 }
2157
2158 static int transmit_notify_request_with_callerid(struct mgcp_subchannel *sub, char *tone, char *callernum, char *callername)
2159 {
2160         struct mgcp_request resp;
2161         char tone2[256];
2162         char *l, *n;
2163         time_t t;
2164         struct tm tm;
2165         struct mgcp_endpoint *p = sub->parent;
2166         
2167         time(&t);
2168         localtime_r(&t,&tm);
2169         n = callername;
2170         l = callernum;
2171         if (!n)
2172                 n = "";
2173         if (!l)
2174                 l = "";
2175
2176         /* Keep track of last callerid for blacklist and callreturn */
2177         ast_copy_string(p->lastcallerid, l, sizeof(p->lastcallerid));
2178
2179         snprintf(tone2, sizeof(tone2), "%s,L/ci(%02d/%02d/%02d/%02d,%s,%s)", tone, 
2180                 tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, l, n);
2181         ast_copy_string(p->curtone, tone, sizeof(p->curtone));
2182         reqprep(&resp, p, "RQNT");
2183         add_header(&resp, "X", p->rqnt_ident); /* SC */
2184         switch (p->hookstate) {
2185         case MGCP_ONHOOK:
2186                 add_header(&resp, "R", "L/hd(N)");
2187                 break;
2188         case MGCP_OFFHOOK:
2189                 add_header(&resp, "R",  (sub->rtp && (p->dtmfmode & MGCP_DTMF_INBAND)) ? "L/hu(N),L/hf(N)" : "L/hu(N),L/hf(N),D/[0-9#*](N)");
2190                 break;
2191         }
2192         if (!ast_strlen_zero(tone2)) {
2193                 add_header(&resp, "S", tone2);
2194         }
2195         if (mgcpdebug) {
2196                 ast_verbose(VERBOSE_PREFIX_3 "MGCP Asked to indicate tone: %s on  %s@%s-%d in cxmode: %s\n", 
2197                         tone2, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
2198         }
2199         /* fill in new fields */
2200         resp.cmd = MGCP_CMD_RQNT;
2201         resp.trid = oseq;
2202         return send_request(p, NULL, &resp, oseq);  /* SC */
2203 }
2204
2205 static int transmit_modify_request(struct mgcp_subchannel *sub)
2206 {
2207         struct mgcp_request resp;
2208         struct mgcp_endpoint *p = sub->parent;
2209
2210         if (ast_strlen_zero(sub->cxident)) {
2211                 /* We don't have a CXident yet, store the destination and
2212                    wait a bit */
2213                 return 0;
2214         }
2215         if (mgcpdebug) {
2216                 ast_verbose(VERBOSE_PREFIX_3 "Modified %s@%s-%d with new mode: %s on callid: %s\n", 
2217                         p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2218         }
2219         reqprep(&resp, p, "MDCX");
2220         add_header(&resp, "C", sub->callid);
2221         add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2222         /* X header should not be sent. kept for compatibility */
2223         add_header(&resp, "X", sub->txident);
2224         add_header(&resp, "I", sub->cxident);
2225         switch (sub->parent->hookstate) {
2226         case MGCP_ONHOOK:
2227                 add_header(&resp, "R", "L/hd(N)");
2228                 break;
2229         case MGCP_OFFHOOK:
2230                 add_header(&resp, "R",  (sub->rtp && (p->dtmfmode & MGCP_DTMF_INBAND)) ? "L/hu(N), L/hf(N)" : "L/hu(N),L/hf(N),D/[0-9#*](N)");
2231                 break;
2232         }
2233         /* fill in new fields */
2234         resp.cmd = MGCP_CMD_MDCX;
2235         resp.trid = oseq;
2236         return send_request(p, sub, &resp, oseq); /* SC */
2237 }
2238
2239
2240 static int transmit_audit_endpoint(struct mgcp_endpoint *p)
2241 {
2242         struct mgcp_request resp;
2243         reqprep(&resp, p, "AUEP");
2244         /* removed unknown param VS */
2245         /*add_header(&resp, "F", "A,R,D,S,X,N,I,T,O,ES,E,MD,M");*/
2246         add_header(&resp, "F", "A");
2247         /* fill in new fields */
2248         resp.cmd = MGCP_CMD_AUEP;
2249         resp.trid = oseq;
2250         return send_request(p, NULL, &resp, oseq);  /* SC */
2251 }
2252
2253 static int transmit_connection_del(struct mgcp_subchannel *sub)
2254 {
2255         struct mgcp_endpoint *p = sub->parent;
2256         struct mgcp_request resp;
2257
2258         if (mgcpdebug) {
2259                 ast_verbose(VERBOSE_PREFIX_3 "Delete connection %s %s@%s-%d with new mode: %s on callid: %s\n", 
2260                         sub->cxident, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2261         }
2262         reqprep(&resp, p, "DLCX");
2263         /* check if call id is avail */
2264         if (sub->callid[0])
2265                 add_header(&resp, "C", sub->callid);
2266         /* X header should not be sent. kept for compatibility */
2267         add_header(&resp, "X", sub->txident);
2268         /* check if cxident is avail */
2269         if (sub->cxident[0])
2270                 add_header(&resp, "I", sub->cxident);
2271         /* fill in new fields */
2272         resp.cmd = MGCP_CMD_DLCX;
2273         resp.trid = oseq;
2274         return send_request(p, sub, &resp, oseq);  /* SC */
2275 }
2276
2277 static int transmit_connection_del_w_params(struct mgcp_endpoint *p, char *callid, char *cxident)
2278 {
2279         struct mgcp_request resp;
2280
2281         if (mgcpdebug) {
2282                 ast_verbose(VERBOSE_PREFIX_3 "Delete connection %s %s@%s on callid: %s\n", 
2283                         cxident ? cxident : "", p->name, p->parent->name, callid ? callid : "");
2284         }
2285         reqprep(&resp, p, "DLCX");
2286         /* check if call id is avail */
2287         if (callid && *callid)
2288                 add_header(&resp, "C", callid);
2289         /* check if cxident is avail */
2290         if (cxident && *cxident)
2291                 add_header(&resp, "I", cxident);
2292         /* fill in new fields */
2293         resp.cmd = MGCP_CMD_DLCX;
2294         resp.trid = oseq;
2295         return send_request(p, p->sub, &resp, oseq);
2296 }
2297
2298 /*! \brief  dump_cmd_queues: (SC:) cleanup pending commands */
2299 static void dump_cmd_queues(struct mgcp_endpoint *p, struct mgcp_subchannel *sub) 
2300 {
2301         struct mgcp_request *t, *q;
2302
2303         if (p) {
2304                 ast_mutex_lock(&p->rqnt_queue_lock);
2305                 for (q = p->rqnt_queue; q; t = q->next, free(q), q=t);
2306                 p->rqnt_queue = NULL;
2307                 ast_mutex_unlock(&p->rqnt_queue_lock);
2308
2309                 ast_mutex_lock(&p->cmd_queue_lock);
2310                 for (q = p->cmd_queue; q; t = q->next, free(q), q=t);
2311                 p->cmd_queue = NULL;
2312                 ast_mutex_unlock(&p->cmd_queue_lock);
2313
2314                 ast_mutex_lock(&p->sub->cx_queue_lock);
2315                 for (q = p->sub->cx_queue; q; t = q->next, free(q), q=t);
2316                 p->sub->cx_queue = NULL;
2317                 ast_mutex_unlock(&p->sub->cx_queue_lock);
2318
2319                 ast_mutex_lock(&p->sub->next->cx_queue_lock);
2320                 for (q = p->sub->next->cx_queue; q; t = q->next, free(q), q=t);
2321                 p->sub->next->cx_queue = NULL;
2322                 ast_mutex_unlock(&p->sub->next->cx_queue_lock);
2323         } else if (sub) {
2324                 ast_mutex_lock(&sub->cx_queue_lock);
2325                 for (q = sub->cx_queue; q; t = q->next, free(q), q=t);
2326                 sub->cx_queue = NULL;
2327                 ast_mutex_unlock(&sub->cx_queue_lock);
2328         }
2329 }
2330
2331
2332 /*! \brief  find_command: (SC:) remove command transaction from queue */
2333 static struct mgcp_request *find_command(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
2334                                          struct mgcp_request **queue, ast_mutex_t *l, int ident)
2335 {
2336         struct mgcp_request *prev, *req;
2337         char iabuf[INET_ADDRSTRLEN];
2338
2339         ast_mutex_lock(l);
2340         for (prev = NULL, req = *queue; req; prev = req, req = req->next) {
2341                 if (req->trid == ident) {
2342                         /* remove from queue */
2343                         if (!prev)
2344                                 *queue = req->next;
2345                         else
2346                                 prev->next = req->next;
2347
2348                         /* send next pending command */
2349                         if (*queue) {
2350                                 if (mgcpdebug) {
2351                                         ast_verbose("Posting Queued Request:\n%s to %s:%d\n", (*queue)->data, 
2352                                                 ast_inet_ntoa(iabuf, sizeof(iabuf), p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
2353                                 }
2354
2355                                 mgcp_postrequest(p, sub, (*queue)->data, (*queue)->len, (*queue)->trid);
2356                         }
2357                         break;
2358                 }
2359         }
2360         ast_mutex_unlock(l);
2361         return req;
2362 }
2363
2364 /* modified for new transport mechanism */
2365 static void handle_response(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,  
2366                             int result, unsigned int ident, struct mgcp_request *resp)
2367 {
2368         char *c;
2369         struct mgcp_request *req;
2370         struct mgcp_gateway *gw = p->parent;
2371
2372         if (result < 200) {
2373                 /* provisional response */
2374                 return;
2375         }
2376
2377         if (p->slowsequence) 
2378                 req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
2379         else if (sub)
2380                 req = find_command(p, sub, &sub->cx_queue, &sub->cx_queue_lock, ident);
2381         else if (!(req = find_command(p, sub, &p->rqnt_queue, &p->rqnt_queue_lock, ident)))
2382                 req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
2383
2384         if (!req) {
2385                 if (option_verbose > 2) {
2386                         ast_verbose(VERBOSE_PREFIX_3 "No command found on [%s] for transaction %d. Ignoring...\n", 
2387                                 gw->name, ident);
2388                 }
2389                 return;
2390         }
2391
2392         if (p && (result >= 400) && (result <= 599)) {
2393                 switch (result) {
2394                 case 401:
2395                         p->hookstate = MGCP_OFFHOOK;
2396                         break;
2397                 case 402:
2398                         p->hookstate = MGCP_ONHOOK;
2399                         break;
2400                 case 406:
2401                         ast_log(LOG_NOTICE, "Transaction %d timed out\n", ident);
2402                         break;
2403                 case 407:
2404                         ast_log(LOG_NOTICE, "Transaction %d aborted\n", ident);
2405                         break;
2406                 }
2407                 if (sub) {
2408                         if (sub->owner) {
2409                                 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n", 
2410                                         result, p->name, p->parent->name, sub ? sub->id:-1);
2411                                 mgcp_queue_hangup(sub);
2412                         }
2413                 } else {
2414                         if (p->sub->next->owner) {
2415                                 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n", 
2416                                         result, p->name, p->parent->name, sub ? sub->id:-1);
2417                                 mgcp_queue_hangup(p->sub);
2418                         }
2419
2420                         if (p->sub->owner) {
2421                                 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n", 
2422                                         result, p->name, p->parent->name, sub ? sub->id:-1);
2423                                 mgcp_queue_hangup(p->sub);
2424                         }
2425
2426                         dump_cmd_queues(p, NULL);
2427                 }
2428         }
2429
2430         if (resp) {
2431                 if (req->cmd == MGCP_CMD_CRCX) {
2432                         if ((c = get_header(resp, "I"))) {
2433                                 if (!ast_strlen_zero(c) && sub) {
2434                                         /* if we are hanging up do not process this conn. */
2435                                         if (sub->owner) {
2436                                                 if (!ast_strlen_zero(sub->cxident)) {
2437                                                         if (strcasecmp(c, sub->cxident)) {
2438                                                                 ast_log(LOG_WARNING, "Subchannel already has a cxident. sub->cxident: %s requested %s\n", sub->cxident, c);
2439                                                         }
2440                                                 }
2441                                                 ast_copy_string(sub->cxident, c, sizeof(sub->cxident));
2442                                                 if (sub->tmpdest.sin_addr.s_addr) {
2443                                                         transmit_modify_with_sdp(sub, NULL, 0);
2444                                                 }
2445                                         } else {
2446                                                 /* XXX delete this one
2447                                                    callid and conn id may already be lost. 
2448                                                    so the following del conn may have a side effect of 
2449                                                    cleaning up the next subchannel */
2450                                                 transmit_connection_del(sub);
2451                                         }
2452                                 }
2453                         }
2454                 }
2455
2456                 if (req->cmd == MGCP_CMD_AUEP) {
2457                         /* check stale connection ids */
2458                         if ((c = get_header(resp, "I"))) {
2459                                 char *v, *n;
2460                                 int len;
2461                                 while ((v = get_csv(c, &len, &n))) {
2462                                         if (len) {
2463                                                 if (strncasecmp(v, p->sub->cxident, len) &&
2464                                                     strncasecmp(v, p->sub->next->cxident, len)) {
2465                                                         /* connection id not found. delete it */
2466                                                         char cxident[80];
2467                                                         memcpy(cxident, v, len);
2468                                                         cxident[len] = '\0';
2469                                                         if (option_verbose > 2) {
2470                                                                 ast_verbose(VERBOSE_PREFIX_3 "Non existing connection id %s on %s@%s \n", 
2471                                                                         cxident, p->name, gw->name);
2472                                                         }
2473                                                         transmit_connection_del_w_params(p, NULL, cxident);
2474                                                 }
2475                                         }
2476                                         c = n;
2477                                 }
2478                         }
2479
2480                         /* Try to determine the hookstate returned from an audit endpoint command */
2481                         if ((c = get_header(resp, "ES"))) {
2482                                 if (!ast_strlen_zero(c)) {
2483                                         if (strstr(c, "hu")) {
2484                                                 if (p->hookstate != MGCP_ONHOOK) {
2485                                                         /* XXX cleanup if we think we are offhook XXX */
2486                                                         if ((p->sub->owner || p->sub->next->owner ) && 
2487                                                             p->hookstate == MGCP_OFFHOOK)
2488                                                                 mgcp_queue_hangup(sub);
2489                                                         p->hookstate = MGCP_ONHOOK;
2490
2491                                                         /* update the requested events according to the new hookstate */
2492                                                         transmit_notify_request(p->sub, "");
2493
2494                                                         /* verbose level check */
2495                                                         if (option_verbose > 2) {
2496                                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting hookstate of %s@%s to ONHOOK\n", p->name, gw->name);
2497                                                         }
2498                                                 }
2499                                         } else if (strstr(c, "hd")) {
2500                                                 if (p->hookstate != MGCP_OFFHOOK) {
2501                                                         p->hookstate = MGCP_OFFHOOK;
2502
2503                                                         /* update the requested events according to the new hookstate */
2504                                                         transmit_notify_request(p->sub, "");
2505
2506                                                         /* verbose level check */
2507                                                         if (option_verbose > 2) {
2508                                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting hookstate of %s@%s to OFFHOOK\n", p->name, gw->name);
2509                                                         }
2510                                                 }
2511                                         }
2512                                 }
2513                         }
2514                 }
2515
2516                 if (resp && resp->lines) {
2517                         /* do not process sdp if we are hanging up. this may be a late response */
2518                         if (sub && sub->owner) {
2519                                 if (!sub->rtp)
2520                                         start_rtp(sub);
2521                                 if (sub->rtp)
2522                                         process_sdp(sub, resp);
2523                         }
2524                 }
2525         }
2526
2527         free(req);
2528 }
2529
2530 static void start_rtp(struct mgcp_subchannel *sub)
2531 {
2532         ast_mutex_lock(&sub->lock);
2533         /* check again to be on the safe side */
2534         if (sub->rtp) {
2535                 ast_rtp_destroy(sub->rtp);
2536                 sub->rtp = NULL;
2537         }
2538         /* Allocate the RTP now */
2539         sub->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2540         if (sub->rtp && sub->owner)
2541                 sub->owner->fds[0] = ast_rtp_fd(sub->rtp);
2542         if (sub->rtp)
2543                 ast_rtp_setnat(sub->rtp, sub->nat);
2544 #if 0
2545         ast_rtp_set_callback(p->rtp, rtpready);
2546         ast_rtp_set_data(p->rtp, p);
2547 #endif          
2548         /* Make a call*ID */
2549         snprintf(sub->callid, sizeof(sub->callid), "%08lx%s", ast_random(), sub->txident);
2550         /* Transmit the connection create */
2551         transmit_connect_with_sdp(sub, NULL);
2552         ast_mutex_unlock(&sub->lock);
2553 }
2554
2555 static void *mgcp_ss(void *data)
2556 {
2557         struct ast_channel *chan = data;
2558         struct mgcp_subchannel *sub = chan->tech_pvt;
2559         struct mgcp_endpoint *p = sub->parent;
2560         char exten[AST_MAX_EXTENSION] = "";
2561         int len = 0;
2562         int timeout = firstdigittimeout;
2563         int res;
2564         int getforward = 0;
2565
2566         while(len < AST_MAX_EXTENSION-1) {
2567                 res = ast_waitfordigit(chan, timeout);
2568                 timeout = 0;
2569                 if (res < 0) {
2570                         ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
2571                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2572                         ast_indicate(chan, -1);
2573                         ast_hangup(chan);
2574                         return NULL;
2575                 } else if (res) {
2576                         exten[len++]=res;
2577                         exten[len] = '\0';
2578                 }
2579                 if (!ast_ignore_pattern(chan->context, exten)) {
2580                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2581                         ast_indicate(chan, -1);
2582                 } else {
2583                         /* XXX Redundant?  We should already be playing dialtone */
2584                         /*tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);*/
2585                         transmit_notify_request(sub, "L/dl");
2586                 }
2587                 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
2588                         if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
2589                                 if (getforward) {
2590                                         /* Record this as the forwarding extension */
2591                                         ast_copy_string(p->call_forward, exten, sizeof(p->call_forward)); 
2592                                         if (option_verbose > 2) {
2593                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %s\n", 
2594                                                         p->call_forward, chan->name);
2595                                         }
2596                                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2597                                         transmit_notify_request(sub, "L/sl");
2598                                         if (res)
2599                                                 break;
2600                                         usleep(500000);
2601                                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2602                                         ast_indicate(chan, -1);
2603                                         sleep(1);
2604                                         memset(exten, 0, sizeof(exten));
2605                                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);*/
2606                                         transmit_notify_request(sub, "L/dl");
2607                                         len = 0;
2608                                         getforward = 0;
2609                                 } else {
2610                                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2611                                         ast_indicate(chan, -1);
2612                                         ast_copy_string(chan->exten, exten, sizeof(chan->exten));
2613                                         ast_set_callerid(chan,
2614                                                 p->hidecallerid ? "" : p->cid_num,
2615                                                 p->hidecallerid ? "" : p->cid_name,
2616                                                 chan->cid.cid_ani ? NULL : p->cid_num);
2617                                         ast_setstate(chan, AST_STATE_RING);
2618                                         /*zt_enable_ec(p);*/
2619                                         if (p->dtmfmode & MGCP_DTMF_HYBRID) {
2620                                                 p->dtmfmode |= MGCP_DTMF_INBAND;
2621                                                 ast_indicate(chan, -1);
2622                                         }
2623                                         res = ast_pbx_run(chan);
2624                                         if (res) {
2625                                                 ast_log(LOG_WARNING, "PBX exited non-zero\n");
2626                                                 /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);*/
2627                                                 /*transmit_notify_request(p, "nbz", 1);*/
2628                                                 transmit_notify_request(sub, "G/cg");
2629                                         }
2630                                         return NULL;
2631                                 }
2632                         } else {
2633                                 /* It's a match, but they just typed a digit, and there is an ambiguous match,
2634                                    so just set the timeout to matchdigittimeout and wait some more */
2635                                 timeout = matchdigittimeout;
2636                         }
2637                 } else if (res == 0) {
2638                         ast_log(LOG_DEBUG, "not enough digits (and no ambiguous match)...\n");
2639                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);*/
2640                         transmit_notify_request(sub, "G/cg");
2641                         /*zt_wait_event(p->subs[index].zfd);*/
2642                         ast_hangup(chan);
2643                         return NULL;
2644                 } else if (p->hascallwaiting && p->callwaiting && !strcmp(exten, "*70")) {
2645                         if (option_verbose > 2) {
2646                                 ast_verbose(VERBOSE_PREFIX_3 "Disabling call waiting on %s\n", chan->name);
2647                         }
2648                         /* Disable call waiting if enabled */
2649                         p->callwaiting = 0;
2650                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2651                         transmit_notify_request(sub, "L/sl");
2652                         len = 0;
2653                         memset(exten, 0, sizeof(exten));
2654                         timeout = firstdigittimeout;
2655                 } else if (!strcmp(exten,ast_pickup_ext())) {
2656                         /* Scan all channels and see if any there
2657                          * ringing channqels with that have call groups
2658                          * that equal this channels pickup group  
2659                          */
2660                         if (ast_pickup_call(chan)) {
2661                                 ast_log(LOG_WARNING, "No call pickup possible...\n");
2662                                 /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);*/
2663                                 transmit_notify_request(sub, "G/cg");
2664                         }
2665                         ast_hangup(chan);
2666                         return NULL;
2667                 } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
2668                         if (option_verbose > 2) {
2669                                 ast_verbose(VERBOSE_PREFIX_3 "Disabling Caller*ID on %s\n", chan->name);
2670                         }
2671                         /* Disable Caller*ID if enabled */
2672                         p->hidecallerid = 1;
2673                         ast_set_callerid(chan, "", "", NULL);
2674                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2675                         transmit_notify_request(sub, "L/sl");
2676                         len = 0;
2677                         memset(exten, 0, sizeof(exten));
2678                         timeout = firstdigittimeout;
2679                 } else if (p->callreturn && !strcmp(exten, "*69")) {
2680                         res = 0;
2681                         if (!ast_strlen_zero(p->lastcallerid)) {
2682                                 res = ast_say_digit_str(chan, p->lastcallerid, "", chan->language);
2683                         }
2684                         if (!res)
2685                                 /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2686                                 transmit_notify_request(sub, "L/sl");
2687                         break;
2688                 } else if (!strcmp(exten, "*78")) {
2689                         /* Do not disturb */
2690                         if (option_verbose > 2) {
2691                                 ast_verbose(VERBOSE_PREFIX_3 "Enabled DND on channel %s\n", chan->name);
2692                         }
2693                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2694                         transmit_notify_request(sub, "L/sl");
2695                         p->dnd = 1;
2696                         getforward = 0;
2697                         memset(exten, 0, sizeof(exten));
2698                         len = 0;
2699                 } else if (!strcmp(exten, "*79")) {
2700                         /* Do not disturb */
2701                         if (option_verbose > 2) {
2702                                 ast_verbose(VERBOSE_PREFIX_3 "Disabled DND on channel %s\n", chan->name);
2703                         }
2704                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2705                         transmit_notify_request(sub, "L/sl");
2706                         p->dnd = 0;
2707                         getforward = 0;
2708                         memset(exten, 0, sizeof(exten));
2709                         len = 0;
2710                 } else if (p->cancallforward && !strcmp(exten, "*72")) {
2711                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2712                         transmit_notify_request(sub, "L/sl");
2713                         getforward = 1;
2714                         memset(exten, 0, sizeof(exten));
2715                         len = 0;
2716                 } else if (p->cancallforward && !strcmp(exten, "*73")) {
2717                         if (option_verbose > 2) {
2718                                 ast_verbose(VERBOSE_PREFIX_3 "Cancelling call forwarding on channel %s\n", chan->name);
2719                         }
2720                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2721                         transmit_notify_request(sub, "L/sl");
2722                         memset(p->call_forward, 0, sizeof(p->call_forward));
2723                         getforward = 0;
2724                         memset(exten, 0, sizeof(exten));
2725                         len = 0;
2726                 } else if (!strcmp(exten, ast_parking_ext()) && 
2727                         sub->next->owner && ast_bridged_channel(sub->next->owner)) {
2728                         /* This is a three way call, the main call being a real channel, 
2729                            and we're parking the first call. */
2730                         ast_masq_park_call(ast_bridged_channel(sub->next->owner), chan, 0, NULL);
2731                         if (option_verbose > 2) {
2732                                 ast_verbose(VERBOSE_PREFIX_3 "Parking call to '%s'\n", chan->name);
2733                         }
2734                         break;
2735                 } else if (!ast_strlen_zero(p->lastcallerid) && !strcmp(exten, "*60")) {
2736                         if (option_verbose > 2) {
2737                                 ast_verbose(VERBOSE_PREFIX_3 "Blacklisting number %s\n", p->lastcallerid);
2738                         }
2739                         res = ast_db_put("blacklist", p->lastcallerid, "1");
2740                         if (!res) {
2741                                 /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2742                                 transmit_notify_request(sub, "L/sl");
2743                                 memset(exten, 0, sizeof(exten));
2744                                 len = 0;
2745                         }
2746                 } else if (p->hidecallerid && !strcmp(exten, "*82")) {
2747                         if (option_verbose > 2) {
2748                                 ast_verbose(VERBOSE_PREFIX_3 "Enabling Caller*ID on %s\n", chan->name);
2749                         }
2750                         /* Enable Caller*ID if enabled */
2751                         p->hidecallerid = 0;
2752                         ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
2753                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2754                         transmit_notify_request(sub, "L/sl");
2755                         len = 0;
2756                         memset(exten, 0, sizeof(exten));
2757                         timeout = firstdigittimeout;
2758                 } else if (!ast_canmatch_extension(chan, chan->context, exten, 1, chan->cid.cid_num) &&
2759                                 ((exten[0] != '*') || (strlen(exten) > 2))) {
2760                         if (option_debug)
2761                                 ast_log(LOG_DEBUG, "Can't match %s from '%s' in context %s\n", exten, chan->cid.cid_num ? chan->cid.cid_num : "<Unknown Caller>", chan->context);
2762                         break;
2763                 }
2764                 if (!timeout)
2765                         timeout = gendigittimeout;
2766                 if (len && !ast_ignore_pattern(chan->context, exten))
2767                         /*tone_zone_play_tone(p->subs[index].zfd, -1);*/
2768                         ast_indicate(chan, -1);
2769         }
2770 #if 0
2771         for (;;) {
2772                 res = ast_waitfordigit(chan, to);
2773                 if (!res) {
2774                         ast_log(LOG_DEBUG, "Timeout...\n");
2775                         break;
2776                 }
2777                 if (res < 0) {
2778                         ast_log(LOG_DEBUG, "Got hangup...\n");
2779                         ast_hangup(chan);
2780                         break;
2781                 }
2782                 exten[pos++] = res;
2783                 if (!ast_ignore_pattern(chan->context, exten))
2784                         ast_indicate(chan, -1);
2785                 if (ast_matchmore_extension(chan, chan->context, exten, 1, chan->callerid)) {
2786                         if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid)) 
2787                                 to = 3000;
2788                         else
2789                                 to = 8000;
2790                 } else
2791                         break;
2792         }
2793         if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid)) {
2794                 ast_copy_string(chan->exten, exten, sizeof(chan->exten)1);
2795                 if (!p->rtp) {
2796                         start_rtp(p);
2797                 }
2798                 ast_setstate(chan, AST_STATE_RING);
2799                 chan->rings = 1;
2800                 if (ast_pbx_run(chan)) {
2801                         ast_log(LOG_WARNING, "Unable to launch PBX on %s\n", chan->name);
2802                 } else
2803                         return NULL;
2804         }
2805 #endif
2806         ast_hangup(chan);
2807         return NULL;
2808 }
2809
2810 static int attempt_transfer(struct mgcp_endpoint *p)
2811 {
2812         /* *************************
2813          * I hope this works.
2814          * Copied out of chan_zap
2815          * Cross your fingers
2816          * *************************/
2817
2818         /* In order to transfer, we need at least one of the channels to
2819            actually be in a call bridge.  We can't conference two applications
2820            together (but then, why would we want to?) */
2821         if (ast_bridged_channel(p->sub->owner)) {
2822                 /* The three-way person we're about to transfer to could still be in MOH, so
2823                    stop if now if appropriate */
2824                 if (ast_bridged_channel(p->sub->next->owner))
2825                         ast_queue_control(p->sub->next->owner, AST_CONTROL_UNHOLD);
2826                 if (p->sub->owner->_state == AST_STATE_RINGING) {
2827                         ast_indicate(ast_bridged_channel(p->sub->next->owner), AST_CONTROL_RINGING);
2828                 }
2829                 if (ast_channel_masquerade(p->sub->next->owner, ast_bridged_channel(p->sub->owner))) {
2830                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2831                                 ast_bridged_channel(p->sub->owner)->name, p->sub->next->owner->name);
2832                         return -1;
2833                 }
2834                 /* Orphan the channel */
2835                 unalloc_sub(p->sub->next);
2836         } else if (ast_bridged_channel(p->sub->next->owner)) {
2837                 if (p->sub->owner->_state == AST_STATE_RINGING) {
2838                         ast_indicate(ast_bridged_channel(p->sub->next->owner), AST_CONTROL_RINGING);
2839                 }
2840                 ast_queue_control(p->sub->next->owner, AST_CONTROL_UNHOLD);
2841                 if (ast_channel_masquerade(p->sub->owner, ast_bridged_channel(p->sub->next->owner))) {
2842                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2843                                 ast_bridged_channel(p->sub->next->owner)->name, p->sub->owner->name);
2844                         return -1;
2845                 }
2846                 /*swap_subs(p, SUB_THREEWAY, SUB_REAL);*/
2847                 if (option_verbose > 2) {
2848                         ast_verbose(VERBOSE_PREFIX_3 "Swapping %d for %d on %s@%s\n", p->sub->id, p->sub->next->id, p->name, p->parent->name);
2849                 }
2850                 p->sub = p->sub->next;
2851                 unalloc_sub(p->sub->next);
2852                 /* Tell the caller not to hangup */
2853                 return 1;
2854         } else {
2855                 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
2856                         p->sub->owner->name, p->sub->next->owner->name);
2857                 p->sub->next->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2858                 if (p->sub->next->owner) {
2859                         p->sub->next->alreadygone = 1;
2860                         mgcp_queue_hangup(p->sub->next);
2861                 }
2862         }
2863         return 0;
2864 }
2865
2866 static void handle_hd_hf(struct mgcp_subchannel *sub, char *ev) 
2867 {
2868         struct mgcp_endpoint *p = sub->parent;
2869         struct ast_channel *c;
2870         pthread_t t;
2871         pthread_attr_t attr;
2872         pthread_attr_init(&attr);
2873         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);    
2874
2875         /* Off hook / answer */
2876         if (sub->outgoing) {
2877                 /* Answered */
2878                 if (sub->owner) {
2879                         if (ast_bridged_channel(sub->owner))
2880                                 ast_queue_control(sub->owner, AST_CONTROL_UNHOLD);
2881                         sub->cxmode = MGCP_CX_SENDRECV;
2882                         if (!sub->rtp) {
2883                                 start_rtp(sub);
2884                         } else {
2885                                 transmit_modify_request(sub);
2886                         }
2887                         /*transmit_notify_request(sub, "aw");*/
2888                         transmit_notify_request(sub, "");
2889                         mgcp_queue_control(sub, AST_CONTROL_ANSWER);
2890                 }
2891         } else {
2892                 /* Start switch */
2893                 /*sub->cxmode = MGCP_CX_SENDRECV;*/
2894                 if (!sub->owner) {
2895                         if (!sub->rtp) {
2896                                 start_rtp(sub);
2897                         } else {
2898                                 transmit_modify_request(sub);
2899                         }
2900                         if (p->immediate) {
2901                                 /* The channel is immediately up. Start right away */
2902 #ifdef DLINK_BUGGY_FIRMWARE     
2903                                 transmit_notify_request(sub, "rt");
2904 #else
2905                                 transmit_notify_request(sub, "G/rt");
2906 #endif          
2907                                 c = mgcp_new(sub, AST_STATE_RING);
2908                                 if (!c) {
2909                                         ast_log(LOG_WARNING, "Unable to start PBX on channel %s@%s\n", p->name, p->parent->name);
2910                                         transmit_notify_request(sub, "G/cg");
2911                                         ast_hangup(c);
2912                                 }
2913                         } else {
2914                                 if (has_voicemail(p)) {
2915                                         transmit_notify_request(sub, "L/sl");
2916                                 } else {
2917                                         transmit_notify_request(sub, "L/dl");
2918                                 }
2919                                 c = mgcp_new(sub, AST_STATE_DOWN);
2920                                 if (c) {
2921                                         if (ast_pthread_create(&t, &attr, mgcp_ss, c)) {
2922                                                 ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
2923                                                 ast_hangup(c);
2924                                         }
2925                                 } else {
2926                                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", p->name, p->parent->name);
2927                                 }
2928                         }
2929                 } else {
2930                         if (p->hookstate == MGCP_OFFHOOK) {
2931                                 ast_log(LOG_WARNING, "Off hook, but already have owner on %s@%s\n", p->name, p->parent->name);
2932                         } else {
2933                                 ast_log(LOG_WARNING, "On hook, but already have owner on %s@%s\n", p->name, p->parent->name);
2934                                 ast_log(LOG_WARNING, "If we're onhook why are we here trying to handle a hd or hf?");
2935                         }
2936                         if (ast_bridged_channel(sub->owner))
2937                                 ast_queue_control(sub->owner, AST_CONTROL_UNHOLD);
2938                         sub->cxmode = MGCP_CX_SENDRECV;
2939                         if (!sub->rtp) {
2940                                 start_rtp(sub);
2941                         } else {
2942                                 transmit_modify_request(sub);
2943                         }
2944                         /*transmit_notify_request(sub, "aw");*/
2945                         transmit_notify_request(sub, "");
2946                         /*ast_queue_control(sub->owner, AST_CONTROL_ANSWER);*/
2947                 }
2948         }
2949 }
2950
2951 static int handle_request(struct mgcp_subchannel *sub, struct mgcp_request *req, struct sockaddr_in *sin)
2952 {
2953         char *ev, *s;
2954         struct ast_frame f = { 0, };
2955         struct mgcp_endpoint *p = sub->parent;
2956         struct mgcp_gateway *g = NULL;
2957         char iabuf[INET_ADDRSTRLEN];
2958         int res;
2959
2960         if (mgcpdebug) {
2961                 ast_verbose("Handling request '%s' on %s@%s\n", req->verb, p->name, p->parent->name);
2962         }
2963         /* Clear out potential response */
2964         if (!strcasecmp(req->verb, "RSIP")) {
2965                 /* Test if this RSIP request is just a keepalive */
2966                 if(!strcasecmp( get_header(req, "RM"), "X-keepalive")) {
2967                         if (option_verbose > 2)
2968                                 ast_verbose(VERBOSE_PREFIX_3 "Received keepalive request from %s@%s\n", p->name, p->parent->name);
2969                         transmit_response(sub, "200", req, "OK");
2970                 } else {
2971                         dump_queue(p->parent, p);
2972                         dump_cmd_queues(p, NULL);
2973                         
2974                         if (option_verbose > 2 && (strcmp(p->name, p->parent->wcardep) != 0)) {
2975                                 ast_verbose(VERBOSE_PREFIX_3 "Resetting interface %s@%s\n", p->name, p->parent->name);
2976                         }
2977                         /* For RSIP on wildcard we reset all endpoints */
2978                         if (!strcmp(p->name, p->parent->wcardep)) {
2979                                 /* Reset all endpoints */
2980                                 struct mgcp_endpoint *tmp_ep;
2981                                 
2982                                 g = p->parent;
2983                                 tmp_ep = g->endpoints;
2984                                 while (tmp_ep) {
2985                                         /*if ((strcmp(tmp_ep->name, "*") != 0) && (strcmp(tmp_ep->name, "aaln/" "*") != 0)) {*/
2986                                         if (strcmp(tmp_ep->name, g->wcardep) != 0) {
2987                                                 struct mgcp_subchannel *tmp_sub, *first_sub;
2988                                                 if (option_verbose > 2) {
2989                                                         ast_verbose(VERBOSE_PREFIX_3 "Resetting interface %s@%s\n", tmp_ep->name, p->parent->name);
2990                                                 }
2991                                                 
2992                                                 first_sub = tmp_ep->sub;
2993                                                 tmp_sub = tmp_ep->sub;