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