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