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