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