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