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