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