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