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