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