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