Merge Stephen Davie's record route patches
[asterisk/asterisk.git] / channels / chan_sip.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Implementation of Session Initiation 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 <ctype.h>
16 #include <pthread.h>
17 #include <string.h>
18 #include <asterisk/lock.h>
19 #include <asterisk/channel.h>
20 #include <asterisk/channel_pvt.h>
21 #include <asterisk/config.h>
22 #include <asterisk/logger.h>
23 #include <asterisk/module.h>
24 #include <asterisk/pbx.h>
25 #include <asterisk/options.h>
26 #include <asterisk/lock.h>
27 #include <asterisk/sched.h>
28 #include <asterisk/io.h>
29 #include <asterisk/rtp.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/callerid.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/md5.h>
34 #include <asterisk/app.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/dsp.h>
37 #include <sys/socket.h>
38 #include <sys/ioctl.h>
39 #include <net/if.h>
40 #include <errno.h>
41 #include <unistd.h>
42 #include <stdlib.h>
43 #include <fcntl.h>
44 #include <netdb.h>
45 #include <arpa/inet.h>
46 #include <sys/signal.h>
47 #include <netinet/ip.h>
48
49 /* #define VOCAL_DATA_HACK */
50
51 #define SIPDUMPER
52 #define DEFAULT_DEFAULT_EXPIREY 120
53 #define DEFAULT_MAX_EXPIREY     3600
54
55 #define SIP_DTMF_RFC2833        (1 << 0)
56 #define SIP_DTMF_INBAND         (1 << 1)
57 #define SIP_DTMF_INFO           (1 << 2)
58
59 static int max_expirey = DEFAULT_MAX_EXPIREY;
60 static int default_expirey = DEFAULT_DEFAULT_EXPIREY;
61
62 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
63
64 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
65 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
66 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
67
68 #define DEFAULT_RETRANS         1000                    /* How frequently to retransmit */
69 #define MAX_RETRANS                     5                               /* Try only 5 times for retransmissions */
70
71 static char *desc = "Session Initiation Protocol (SIP)";
72 static char *type = "sip";
73 static char *tdesc = "Session Initiation Protocol (SIP)";
74 static char *config = "sip.conf";
75
76 #define DEFAULT_SIP_PORT        5060    /* From RFC 2543 */
77 #define SIP_MAX_PACKET  1500            /* Also from RFC 2543, should sub headers tho */
78
79 static char context[AST_MAX_EXTENSION] = "default";
80
81 static char language[MAX_LANGUAGE] = "";
82
83 static char callerid[AST_MAX_EXTENSION] = "asterisk";
84
85 static int usecnt =0;
86 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
87
88 /* Protect the interface list (of sip_pvt's) */
89 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
90
91 /* Protect the monitoring thread, so only one process can kill or start it, and not
92    when it's doing something critical. */
93 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
94
95 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
96
97 /* This is the thread for the monitor which checks for input on the channels
98    which are not currently in use.  */
99 static pthread_t monitor_thread = 0;
100
101 static int restart_monitor(void);
102
103 /* Codecs that we support by default: */
104 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM;
105 static int noncodeccapability = AST_RTP_DTMF;
106
107 static char ourhost[256];
108 static struct in_addr __ourip;
109 static int ourport;
110
111 static int sipdebug = 0;
112
113 static int tos = 0;
114
115 static int globaldtmfmode = SIP_DTMF_RFC2833;
116
117 /* Expire slowly */
118 static int expirey = 900;
119
120 static struct sched_context *sched;
121 static struct io_context *io;
122 /* The private structures of the  sip channels are linked for
123    selecting outgoing channels */
124    
125 #define SIP_MAX_HEADERS         64
126 #define SIP_MAX_LINES           64
127
128 static struct sip_codec_pref {
129         int codec;
130         struct sip_codec_pref *next;
131 } *prefs;
132
133 struct sip_request {
134   char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
135   char *rlPart2; /* The Request URI or Response Status */
136         int len;
137         int headers;                                    /* SIP Headers */
138         char *header[SIP_MAX_HEADERS];
139         int lines;                                              /* SDP Content */
140         char *line[SIP_MAX_LINES];
141         char data[SIP_MAX_PACKET];
142 };
143
144 struct sip_pkt;
145
146 struct sip_route {
147         struct sip_route *next;
148         char hop[0];
149 };
150
151 static struct sip_pvt {
152         pthread_mutex_t lock;                           /* Channel private lock */
153         char callid[80];                                        /* Global CallID */
154         char randdata[80];      /* Random data */
155         unsigned int ocseq;                                     /* Current outgoing seqno */
156         unsigned int icseq;                                     /* Current incoming seqno */
157         int lastinvite;                                         /* Last Cseq of invite */
158         int alreadygone;                                        /* Whether or not we've already been destroyed by or peer */
159         int needdestroy;                                        /* if we need to be destroyed */
160         int capability;                                         /* Special capability */
161         int noncodeccapability;
162         int outgoing;                                           /* Outgoing or incoming call? */
163         int insecure;                                           /* Don't check source port/ip */
164         int expirey;                                            /* How long we take to expire */
165         int branch;                                                     /* One random number */
166         int canreinvite;                                        /* Do we support reinvite */
167         int progress;                                           /* Have sent 183 message progress */
168         int tag;                                                        /* Another random number */
169         int nat;                                                        /* Whether to try to support NAT */
170         struct sockaddr_in sa;                          /* Our peer */
171         struct sockaddr_in recv;                        /* Received as */
172         struct in_addr ourip;                           /* Our IP */
173         struct ast_channel *owner;                      /* Who owns us */
174         char exten[AST_MAX_EXTENSION];          /* Extention where to start */
175         char refer_to[AST_MAX_EXTENSION];       /* Place to store REFER-TO extension */
176         char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
177         char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
178         struct sip_pvt *refer_call;                     /* Call we are referring */
179         struct sip_route *route;                        /* Head of linked list of routing steps (fm Record-Route) */
180         char remote_party_id[256];
181         char context[AST_MAX_EXTENSION];
182         char language[MAX_LANGUAGE];
183         char theirtag[256];                             /* Their tag */
184         char username[81];
185         char peername[81];
186         char peersecret[81];
187         char callerid[256];                                     /* Caller*ID */
188         char via[256];
189         char accountcode[256];                          /* Account code */
190         int amaflags;                                           /* AMA Flags */
191         struct sip_request initreq;                     /* Initial request */
192         
193         int maxtime;                                            /* Max time for first response */
194         int initid;                                                     /* Auto-congest ID if appropriate */
195         int autokillid;                                         /* Auto-kill ID */
196
197         int dtmfmode;
198         struct ast_dsp *vad;
199         
200         struct sip_peer *peerpoke;                      /* If this calls is to poke a peer, which one */
201         struct sip_registry *registry;                  /* If this is a REGISTER call, to which registry */
202         struct ast_rtp *rtp;                            /* RTP Session */
203         struct sip_pkt *packets;                        /* Packets scheduled for re-transmission */
204         struct sip_pvt *next;
205 } *iflist = NULL;
206
207 struct sip_pkt {
208         struct sip_pkt *next;                           /* Next packet */
209         int retrans;                                            /* Retransmission number */
210         int seqno;                                                      /* Sequence number */
211         int resp;                                                       /* non-zero if this is a response packet (e.g. 200 OK) */
212         struct sip_pvt *owner;                          /* Owner call */
213         int retransid;                                          /* Retransmission ID */
214         int packetlen;                                          /* Length of packet */
215         char data[0];
216 };      
217
218 struct sip_user {
219         /* Users who can access various contexts */
220         char name[80];
221         char secret[80];
222         char context[80];
223         char callerid[80];
224         char methods[80];
225         char accountcode[80];
226         int nat;
227         int hascallerid;
228         int amaflags;
229         int insecure;
230         int canreinvite;
231         int dtmfmode;
232         struct ast_ha *ha;
233         struct sip_user *next;
234 };
235
236 struct sip_peer {
237         char name[80];
238         char secret[80];
239         char context[80];               /* JK02: peers need context too to allow parking etc */
240         char methods[80];
241         char username[80];
242         char mailbox[AST_MAX_EXTENSION];
243         int lastmsgssent;
244         time_t  lastmsgcheck;
245         int dynamic;
246         int expire;
247         int expirey;
248         int capability;
249         int insecure;
250         int nat;
251         int canreinvite;
252         int dtmfmode;
253         struct sockaddr_in addr;
254         struct in_addr mask;
255
256         /* Qualification */
257         struct sip_pvt *call;           /* Call pointer */
258         int pokeexpire;                         /* When to expire poke */
259         int lastms;                                     /* How long last response took (in ms), or -1 for no response */
260         int maxms;                                      /* Max ms we will accept for the host to be up, 0 to not monitor */
261         struct timeval ps;                      /* Ping send time */
262         
263         struct sockaddr_in defaddr;
264         struct ast_ha *ha;
265         int delme;
266         int lastmsg;
267         struct sip_peer *next;
268 };
269
270 static struct ast_user_list {
271         struct sip_user *users;
272         pthread_mutex_t lock;
273 } userl = { NULL, AST_MUTEX_INITIALIZER };
274
275 static struct ast_peer_list {
276         struct sip_peer *peers;
277         pthread_mutex_t lock;
278 } peerl = { NULL, AST_MUTEX_INITIALIZER };
279
280
281 #define REG_STATE_UNREGISTERED 0
282 #define REG_STATE_REGSENT          1
283 #define REG_STATE_AUTHSENT         2
284 #define REG_STATE_REGISTERED   3
285 #define REG_STATE_REJECTED         4
286 #define REG_STATE_TIMEOUT          5
287 #define REG_STATE_NOAUTH           6
288
289 struct sip_registry {
290         pthread_mutex_t lock;                           /* Channel private lock */
291         struct sockaddr_in addr;                /* Who we connect to for registration purposes */
292         char username[80];
293         char secret[80];                        /* Password or key name in []'s */
294         char contact[80];                       /* Contact extension */
295         char random[80];
296         int expire;                                     /* Sched ID of expiration */
297         int timeout;                                    /* sched id of sip_reg_timeout */
298         int refresh;                                    /* How often to refresh */
299         struct sip_pvt *call;                           /* create a sip_pvt structure for each outbound "registration call" in progress */
300         int regstate;
301         int callid_valid;               /* 0 means we haven't chosen callid for this registry yet. */
302         char callid[80];                /* Global CallID for this registry */
303         struct sockaddr_in us;                  /* Who the server thinks we are */
304         struct sip_registry *next;
305 };
306
307 #define REINVITE_INVITE         1
308 #define REINVITE_UPDATE         2
309
310 static int sip_do_register(struct sip_registry *r);
311 struct sip_registry *registrations;
312
313 static int sipsock  = -1;
314 static int globalnat = 0;
315
316 static struct sockaddr_in bindaddr;
317
318 static struct ast_frame  *sip_read(struct ast_channel *ast);
319 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
320 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
321 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
322 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
323 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
324 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
325 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
326 static int transmit_message_with_text(struct sip_pvt *p, char *text);
327 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
328 char *getsipuri(char *header);
329 static void free_old_route(struct sip_route *route);
330
331 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
332 {
333         int res;
334         if (p->nat)
335             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
336         else
337             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
338         if (res != len) {
339                 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, inet_ntoa(p->sa.sin_addr), res, strerror(errno));
340         }
341         return res;
342 }
343
344 static void sip_destroy(struct sip_pvt *p);
345
346 static int retrans_pkt(void *data)
347 {
348         struct sip_pkt *pkt=data;
349         int res = 0;
350         ast_pthread_mutex_lock(&pkt->owner->lock);
351         if (!pkt->owner->needdestroy) {
352                 if (pkt->retrans < MAX_RETRANS) {
353                         pkt->retrans++;
354                         if (sipdebug) {
355                                 if (pkt->owner->nat)
356                                         ast_verbose("Retransmitting #%d (NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port));
357                                 else
358                                         ast_verbose("Retransmitting #%d (no NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port));
359                         }
360                         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
361                         res = 1;
362                 } else {
363                         ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
364                         pkt->retransid = -1;
365                         if (pkt->owner->owner) {
366                                 /* XXX Potential deadlocK?? XXX */
367                                 ast_queue_hangup(pkt->owner->owner, 1);
368                         } else {
369                                 /* If no owner, destroy now */
370                                 ast_pthread_mutex_unlock(&pkt->owner->lock);
371                                 sip_destroy(pkt->owner);
372                                 pkt = NULL;
373                         }
374                 }
375         } else {
376                 /* Don't bother retransmitting.  It's about to be killed anyway */
377                 pkt->retransid = -1;
378                 if (pkt->owner->owner) {
379                         /* XXX Potential deadlocK?? XXX */
380                         ast_queue_hangup(pkt->owner->owner, 1);
381                 } else {
382                         /* If no owner, destroy now */
383                         ast_pthread_mutex_unlock(&pkt->owner->lock);
384                         sip_destroy(pkt->owner);
385                         pkt=NULL;
386                 }
387         }
388         if (pkt)
389                 ast_pthread_mutex_unlock(&pkt->owner->lock);
390         return res;
391 }
392
393 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
394 {
395         struct sip_pkt *pkt;
396         pkt = malloc(sizeof(struct sip_pkt) + len);
397         if (!pkt)
398                 return -1;
399         memset(pkt, 0, sizeof(struct sip_pkt));
400         memcpy(pkt->data, data, len);
401         pkt->packetlen = len;
402         pkt->next = p->packets;
403         pkt->owner = p;
404         pkt->seqno = seqno;
405         pkt->resp = resp;
406         /* Schedule retransmission */
407         pkt->retransid = ast_sched_add(sched, 1000, retrans_pkt, pkt);
408         pkt->next = p->packets;
409         p->packets = pkt;
410         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
411         return 0;
412 }
413
414 static int __sip_autodestruct(void *data)
415 {
416         struct sip_pvt *p = data;
417         p->autokillid = -1;
418         ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
419         if (p->owner) {
420                 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
421                 ast_queue_hangup(p->owner, 0);
422         } else {
423                 sip_destroy(p);
424         }
425         return 0;
426 }
427
428 static int sip_scheddestroy(struct sip_pvt *p, int ms)
429 {
430         if (p->autokillid > -1)
431                 ast_sched_del(sched, p->autokillid);
432         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
433         return 0;
434 }
435
436 static int sip_cancel_destroy(struct sip_pvt *p)
437 {
438         if (p->autokillid > -1)
439                 ast_sched_del(sched, p->autokillid);
440         p->autokillid = -1;
441         return 0;
442 }
443
444 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
445 {
446         struct sip_pkt *cur, *prev = NULL;
447         int res = -1;
448         cur = p->packets;
449         while(cur) {
450                 if ((cur->seqno == seqno) && (cur->resp == resp)) {
451                         /* this is our baby */
452                         if (prev)
453                                 prev->next = cur->next;
454                         else
455                                 p->packets = cur->next;
456                         if (cur->retransid > -1)
457                                 ast_sched_del(sched, cur->retransid);
458                         free(cur);
459                         res = 0;
460                         break;
461                 }
462                 prev = cur;
463                 cur = cur->next;
464         }
465         ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
466         return res;
467 }
468
469 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
470 {
471         int res;
472         if (sipdebug) {
473                 if (p->nat)
474                         ast_verbose("%sTransmitting (NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
475                 else
476                         ast_verbose("%sTransmitting (no NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
477         }
478         if (reliable)
479                 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
480         else
481                 res = __sip_xmit(p, req->data, req->len);
482         if (res > 0)
483                 res = 0;
484         return res;
485 }
486
487 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
488 {
489         int res;
490         if (sipdebug) {
491                 if (p->nat)
492                         ast_verbose("%sTransmitting:\n%s (NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
493                 else
494                         ast_verbose("%sTransmitting:\n%s (no NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
495         }
496         if (reliable)
497                 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
498         else
499                 res = __sip_xmit(p, req->data, req->len);
500         return res;
501 }
502
503 static char *ditch_braces(char *tmp)
504 {
505         char *c = tmp;
506         char *n;
507         c = tmp;
508         if ((n = strchr(tmp, '<')) ) {
509                 c = n + 1;
510                 while(*c && *c != '>') c++;
511                 if (*c != '>') {
512                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
513                 } else {
514                         *c = '\0';
515                 }
516                 return n+1;
517         }
518         return c;
519 }
520
521 static int sip_sendtext(struct ast_channel *ast, char *text)
522 {
523         struct sip_pvt *p = ast->pvt->pvt;
524         if (sipdebug) 
525                 ast_verbose("Sending text %s on %s\n", text, ast->name);
526         if (!p)
527                 return -1;
528         if (!text || !strlen(text))
529                 return 0;
530         if (sipdebug)
531                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
532         transmit_message_with_text(p, text);
533         return 0;       
534 }
535
536 static int create_addr(struct sip_pvt *r, char *peer)
537 {
538         struct hostent *hp;
539         struct sip_peer *p;
540         int found=0;
541         r->sa.sin_family = AF_INET;
542         ast_pthread_mutex_lock(&peerl.lock);
543         p = peerl.peers;
544         while(p) {
545                 if (!strcasecmp(p->name, peer)) {
546                         found++;
547                         r->capability = p->capability;
548                         r->nat = p->nat;
549                         if (r->rtp) {
550                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
551                                 ast_rtp_setnat(r->rtp, r->nat);
552                         }
553                         strncpy(r->peername, p->username, sizeof(r->peername)-1);
554                         strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
555                         strncpy(r->username, p->username, sizeof(r->username)-1);
556                         r->insecure = p->insecure;
557                         r->canreinvite = p->canreinvite;
558                         r->maxtime = p->maxms;
559                         if (p->dtmfmode) {
560                                 r->dtmfmode = p->dtmfmode;
561                                 if (r->dtmfmode & SIP_DTMF_RFC2833)
562                                         r->noncodeccapability |= AST_RTP_DTMF;
563                                 else
564                                         r->noncodeccapability &= ~AST_RTP_DTMF;
565                         }
566                         strncpy(r->context, p->context,sizeof(r->context)-1);
567                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
568                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
569                                 if (p->addr.sin_addr.s_addr) {
570                                         r->sa.sin_addr = p->addr.sin_addr;
571                                         r->sa.sin_port = p->addr.sin_port;
572                                 } else {
573                                         r->sa.sin_addr = p->defaddr.sin_addr;
574                                         r->sa.sin_port = p->defaddr.sin_port;
575                                 }
576                                 memcpy(&r->recv, &r->sa, sizeof(r->recv));
577                                 break;
578                         }
579                 }
580                 p = p->next;
581         }
582         ast_pthread_mutex_unlock(&peerl.lock);
583         if (!p && !found) {
584                 hp = gethostbyname(peer);
585                 if (hp) {
586                         memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
587                         r->sa.sin_port = htons(DEFAULT_SIP_PORT);
588                         memcpy(&r->recv, &r->sa, sizeof(r->recv));
589                         return 0;
590                 } else {
591                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
592                         return -1;
593                 }
594         } else if (!p)
595                 return -1;
596         else
597                 return 0;
598 }
599
600 static int auto_congest(void *nothing)
601 {
602         struct sip_pvt *p = nothing;
603         ast_pthread_mutex_lock(&p->lock);
604         p->initid = -1;
605         if (p->owner) {
606                 if (!pthread_mutex_trylock(&p->owner->lock)) {
607                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
608                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
609                         ast_pthread_mutex_unlock(&p->owner->lock);
610                 }
611         }
612         ast_pthread_mutex_unlock(&p->lock);
613         return 0;
614 }
615
616 static void sip_prefs_free(void)
617 {
618         struct sip_codec_pref *cur, *next;
619         cur = prefs;
620         while(cur) {
621                 next = cur->next;
622                 free(cur);
623                 cur = next;
624         }
625         prefs = NULL;
626 }
627
628 static void sip_pref_remove(int format)
629 {
630         struct sip_codec_pref *cur, *prev=NULL;
631         cur = prefs;
632         while(cur) {
633                 if (cur->codec == format) {
634                         if (prev)
635                                 prev->next = cur->next;
636                         else
637                                 prefs = cur->next;
638                         free(cur);
639                         return;
640                 }
641                 prev = cur;
642                 cur = cur->next;
643         }
644 }
645
646 static int sip_pref_append(int format)
647 {
648         struct sip_codec_pref *cur, *tmp;
649         sip_pref_remove(format);
650         tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
651         if (!tmp)
652                 return -1;
653         memset(tmp, 0, sizeof(struct sip_codec_pref));
654         tmp->codec = format;
655         if (prefs) {
656                 cur = prefs;
657                 while(cur->next)
658                         cur = cur->next;
659                 cur->next = tmp;
660         } else
661                 prefs = tmp;
662         return 0;
663 }
664
665 static int sip_codec_choose(int formats)
666 {
667         struct sip_codec_pref *cur;
668         cur = prefs;
669         while(cur) {
670                 if (formats & cur->codec)
671                         return cur->codec;
672                 cur = cur->next;
673         }
674         return ast_best_codec(formats);
675 }
676
677 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
678 {
679         int res;
680         struct sip_pvt *p;
681         char *vxml_url = NULL;
682         struct varshead *headp;
683         struct ast_var_t *current;
684         
685         p = ast->pvt->pvt;
686         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
687                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
688                 return -1;
689         }
690
691         /* Check whether there is a VXML_URL variable */
692         headp=&ast->varshead;
693         AST_LIST_TRAVERSE(headp,current,entries) {
694                 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
695                 {
696                         vxml_url = ast_var_value(current);
697                         break;
698                 }
699         }
700         
701         res = 0;
702         p->outgoing = 1;
703         transmit_invite(p, "INVITE", 1, NULL, vxml_url);
704         if (p->maxtime) {
705                 /* Initialize auto-congest time */
706                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
707         }
708         return res;
709 }
710
711 static void __sip_destroy(struct sip_pvt *p, int lockowner)
712 {
713         struct sip_pvt *cur, *prev = NULL;
714         struct sip_pkt *cp;
715         if (p->initid > -1)
716                 ast_sched_del(sched, p->initid);
717         if (p->autokillid > -1)
718                 ast_sched_del(sched, p->autokillid);
719         if (p->rtp) {
720                 ast_rtp_destroy(p->rtp);
721         }
722         if (p->route) {
723                 free_old_route(p->route);
724                 p->route = NULL;
725         }
726         /* Unlink us from the owner if we have one */
727         if (p->owner) {
728                 if (lockowner)
729                         ast_pthread_mutex_lock(&p->owner->lock);
730                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
731                 p->owner->pvt->pvt = NULL;
732                 if (lockowner)
733                         ast_pthread_mutex_unlock(&p->owner->lock);
734         }
735         cur = iflist;
736         while(cur) {
737                 if (cur == p) {
738                         if (prev)
739                                 prev->next = cur->next;
740                         else
741                                 iflist = cur->next;
742                         break;
743                 }
744                 prev = cur;
745                 cur = cur->next;
746         }
747         if (!cur) {
748                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
749         } else {
750                 if (p->initid > -1)
751                         ast_sched_del(sched, p->initid);
752                 while((cp = p->packets)) {
753                         p->packets = p->packets->next;
754                         if (cp->retransid > -1)
755                                 ast_sched_del(sched, cp->retransid);
756                         free(cp);
757                 }
758                 free(p);
759         }
760 }
761 static void sip_destroy(struct sip_pvt *p)
762 {
763         ast_pthread_mutex_lock(&iflock);
764         __sip_destroy(p, 1);
765         ast_pthread_mutex_unlock(&iflock);
766 }
767
768 /* Interface lookup code courtesy Tilghman of DrunkCoder.com.  Thanks! */
769
770 struct my_ifreq {
771         char ifrn_name[IFNAMSIZ];       /* Interface name, e.g. "en0".  */
772         struct sockaddr_in ifru_addr;
773 };
774
775 struct in_addr *lookup_iface(char *iface) {
776         int mysock;
777         int res;
778         static struct  my_ifreq ifreq;
779         memset(&ifreq, 0, sizeof(ifreq));
780         strncpy(ifreq.ifrn_name,iface,sizeof(ifreq.ifrn_name) - 1);
781
782         mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
783         res = ioctl(mysock,SIOCGIFADDR,&ifreq);
784         
785         close(mysock);
786         if (res < 0) {
787                 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
788                 return &__ourip;
789         }
790         return( (struct in_addr *) &ifreq.ifru_addr.sin_addr );
791 }
792
793 static struct in_addr *myaddrfor(struct in_addr *them)
794 {
795         FILE *PROC;
796         struct in_addr *temp = NULL;
797         unsigned int remote_ip;
798         char line[256];
799         remote_ip = them->s_addr;
800         
801         PROC = fopen("/proc/net/route","r");
802         if (!PROC) {
803                 /* If /proc/net/route doesn't exist, fall back to the old method */
804                 return &__ourip;
805         }
806         /* First line contains headers */
807         fgets(line,sizeof(line),PROC);
808
809         while (!feof(PROC)) {
810                 char iface[8];
811                 unsigned int dest, gateway, mask;
812                 int i,aoffset;
813                 char *fields[40];
814
815                 fgets(line,sizeof(line),PROC);
816
817                 aoffset = 0;
818                 for (i=0;i<sizeof(line);i++) {
819                         char *boffset;
820
821                         fields[aoffset++] = line + i;
822                         boffset = strchr(line + i,'\t');
823                         if (boffset == NULL) {
824                                 /* Exit loop */
825                                 break;
826                         } else {
827                                 *boffset = '\0';
828                                 i = boffset - line;
829                         }
830                 }
831
832                 sscanf(fields[0],"%s",iface);
833                 sscanf(fields[1],"%x",&dest);
834                 sscanf(fields[2],"%x",&gateway);
835                 sscanf(fields[7],"%x",&mask);
836 #if 0
837                 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
838 #endif          
839                 if (((remote_ip & mask) ^ dest) == 0) {
840                         if (sipdebug)
841                                 ast_verbose("Interface is %s\n",iface);
842                         temp = lookup_iface(iface);
843                         if (sipdebug)
844                                 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
845                         break;
846                 }
847         }
848         fclose(PROC);
849         if (!temp) {
850                 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s.  Using default\n", inet_ntoa(*them));
851                 temp = &__ourip;
852         }
853         return temp;
854 }
855
856
857 static int sip_hangup(struct ast_channel *ast)
858 {
859         struct sip_pvt *p = ast->pvt->pvt;
860         int needcancel = 0;
861         if (option_debug)
862                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
863         if (!ast->pvt->pvt) {
864                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
865                 return 0;
866         }
867         ast_pthread_mutex_lock(&p->lock);
868         /* Determine how to disconnect */
869         if (p->owner != ast) {
870                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
871                 ast_pthread_mutex_unlock(&p->lock);
872                 return 0;
873         }
874         if (!ast || (ast->_state != AST_STATE_UP))
875                 needcancel = 1;
876         /* Disconnect */
877         p = ast->pvt->pvt;
878         if (p->vad) {
879             ast_dsp_free(p->vad);
880         }
881         p->owner = NULL;
882         ast->pvt->pvt = NULL;
883
884         p->needdestroy = 1;
885         /* Start the process if it's not already started */
886         if (!p->alreadygone && strlen(p->initreq.data)) {
887                 if (needcancel) {
888                         transmit_request(p, "CANCEL", 0, 1);
889                 } else {
890                         /* Send a hangup */
891                         transmit_request(p, "BYE", 1, 1);
892                 }
893         }
894         ast_pthread_mutex_unlock(&p->lock);
895         return 0;
896 }
897
898 static int sip_answer(struct ast_channel *ast)
899 {
900         int res = 0,fmt;
901         char *codec;
902         struct sip_pvt *p = ast->pvt->pvt;
903
904         
905         if (ast->_state != AST_STATE_UP) {
906         
907         
908         
909                 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
910                 if (codec) {
911                         ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
912                         fmt=ast_getformatbyname(codec);
913                         if (fmt) {
914                                 p->capability=fmt;
915                         } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
916                 }
917
918                 ast_setstate(ast, AST_STATE_UP);
919                 if (option_debug)
920                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
921                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
922         }
923         return res;
924 }
925
926 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
927 {
928         struct sip_pvt *p = ast->pvt->pvt;
929         int res = 0;
930         if (frame->frametype != AST_FRAME_VOICE) {
931                 if (frame->frametype == AST_FRAME_IMAGE)
932                         return 0;
933                 else {
934                         ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
935                         return 0;
936                 }
937         } else {
938                 if (!(frame->subclass & ast->nativeformats)) {
939                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
940                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
941                         return -1;
942                 }
943         }
944         if (p) {
945                 ast_pthread_mutex_lock(&p->lock);
946                 if (p->rtp) {
947                         if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
948                                 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
949                                 p->progress = 1;
950                         }
951                         res =  ast_rtp_write(p->rtp, frame);
952                 }
953                 ast_pthread_mutex_unlock(&p->lock);
954         }
955         return res;
956 }
957
958 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
959 {
960         struct sip_pvt *p = newchan->pvt->pvt;
961         ast_pthread_mutex_lock(&p->lock);
962         if (p->owner != oldchan) {
963                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
964                 ast_pthread_mutex_unlock(&p->lock);
965                 return -1;
966         }
967         p->owner = newchan;
968         ast_pthread_mutex_unlock(&p->lock);
969         return 0;
970 }
971
972 static int sip_senddigit(struct ast_channel *ast, char digit)
973 {
974         struct sip_pvt *p = ast->pvt->pvt;
975         if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
976                 transmit_info_with_digit(p, digit);
977         }
978         if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
979                 ast_rtp_senddigit(p->rtp, digit);
980         }
981         /* If in-band DTMF is desired, send that */
982         if (p->dtmfmode & SIP_DTMF_INBAND)
983                 return -1;
984         return 0;
985 }
986
987 static int sip_indicate(struct ast_channel *ast, int condition)
988 {
989         struct sip_pvt *p = ast->pvt->pvt;
990         switch(condition) {
991         case AST_CONTROL_RINGING:
992                 if (ast->_state == AST_STATE_RING) {
993                         transmit_response(p, "180 Ringing", &p->initreq);
994                         break;
995                 }
996                 return -1;
997         case AST_CONTROL_BUSY:
998                 if (ast->_state != AST_STATE_UP) {
999                         transmit_response(p, "600 Busy everywhere", &p->initreq);
1000                         p->alreadygone = 1;
1001                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1002                         break;
1003                 }
1004                 return -1;
1005         case AST_CONTROL_CONGESTION:
1006                 if (ast->_state != AST_STATE_UP) {
1007                         transmit_response(p, "486 Busy here", &p->initreq);
1008                         p->alreadygone = 1;
1009                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1010                         break;
1011                 }
1012                 return -1;
1013         case -1:
1014                 return -1;
1015         default:
1016                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1017                 return -1;
1018         }
1019         return 0;
1020 }
1021
1022
1023
1024 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1025 {
1026         struct ast_channel *tmp;
1027         int fmt;
1028         tmp = ast_channel_alloc(1);
1029         if (tmp) {
1030                 /* Select our native format based on codec preference until we receive
1031                    something from another device to the contrary. */
1032                 if (i->capability)
1033                         tmp->nativeformats = sip_codec_choose(i->capability);
1034                 else 
1035                         tmp->nativeformats = sip_codec_choose(capability);
1036                 fmt = ast_best_codec(tmp->nativeformats);
1037                 if (title)
1038                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1039                 else
1040                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
1041                 tmp->type = type;
1042                 if (i->dtmfmode & SIP_DTMF_INBAND) {
1043                     i->vad = ast_dsp_new();
1044                     ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1045                 }
1046                 tmp->fds[0] = ast_rtp_fd(i->rtp);
1047                 ast_setstate(tmp, state);
1048                 if (state == AST_STATE_RING)
1049                         tmp->rings = 1;
1050                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1051                 tmp->writeformat = fmt;
1052                 tmp->pvt->rawwriteformat = fmt;
1053                 tmp->readformat = fmt;
1054                 tmp->pvt->rawreadformat = fmt;
1055                 tmp->pvt->pvt = i;
1056                 tmp->pvt->send_text = sip_sendtext;
1057                 tmp->pvt->call = sip_call;
1058                 tmp->pvt->hangup = sip_hangup;
1059                 tmp->pvt->answer = sip_answer;
1060                 tmp->pvt->read = sip_read;
1061                 tmp->pvt->write = sip_write;
1062                 tmp->pvt->indicate = sip_indicate;
1063                 tmp->pvt->fixup = sip_fixup;
1064                 tmp->pvt->send_digit = sip_senddigit;
1065                 tmp->pvt->bridge = ast_rtp_bridge;
1066                 if (strlen(i->language))
1067                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1068                 i->owner = tmp;
1069                 ast_pthread_mutex_lock(&usecnt_lock);
1070                 usecnt++;
1071                 ast_pthread_mutex_unlock(&usecnt_lock);
1072                 ast_update_use_count();
1073                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1074                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1075                 if (strlen(i->callerid))
1076                         tmp->callerid = strdup(i->callerid);
1077                 tmp->priority = 1;
1078                 if (state != AST_STATE_DOWN) {
1079                         if (ast_pbx_start(tmp)) {
1080                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1081                                 ast_hangup(tmp);
1082                                 tmp = NULL;
1083                         }
1084                 }
1085         } else
1086                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1087         return tmp;
1088 }
1089
1090 static struct cfalias {
1091         char *fullname;
1092         char *shortname;
1093 } aliases[] = {
1094         { "Content-Type", "c" },
1095         { "Content-Encoding", "e" },
1096         { "From", "f" },
1097         { "Call-ID", "i" },
1098         { "Contact", "m" },
1099         { "Content-Length", "l" },
1100         { "Subject", "s" },
1101         { "To", "t" },
1102         { "Via", "v" },
1103 };
1104
1105 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1106   if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1107     char* r = line + nameLen + 1;
1108     while (*r && (*r < 33)) ++r;
1109     return r;
1110   }
1111
1112   return "";
1113 }
1114
1115 static char *get_sdp(struct sip_request *req, char *name) {
1116   int x;
1117   int len = strlen(name);
1118   char *r;
1119
1120   for (x=0; x<req->lines; x++) {
1121     r = get_sdp_by_line(req->line[x], name, len);
1122     if (r[0] != '\0') return r;
1123   }
1124   return "";
1125 }
1126
1127 static void sdpLineNum_iterator_init(int* iterator) {
1128   *iterator = 0;
1129 }
1130
1131 static char* get_sdp_iterate(int* iterator,
1132                              struct sip_request *req, char *name) {
1133   int len = strlen(name);
1134   char *r;
1135   while (*iterator < req->lines) {
1136     r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1137     if (r[0] != '\0') return r;
1138   }
1139   return "";
1140 }
1141
1142 static char *__get_header(struct sip_request *req, char *name, int *start)
1143 {
1144         int x;
1145         int len = strlen(name);
1146         char *r;
1147         for (x=*start;x<req->headers;x++) {
1148                 if (!strncasecmp(req->header[x], name, len) && 
1149                                 (req->header[x][len] == ':')) {
1150                                         r = req->header[x] + len + 1;
1151                                         while(*r && (*r < 33))
1152                                                         r++;
1153                                         *start = x+1;
1154                                         return r;
1155                 }
1156         }
1157         /* Try aliases */
1158         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
1159                 if (!strcasecmp(aliases[x].fullname, name))
1160                         return __get_header(req, aliases[x].shortname, start);
1161
1162         /* Don't return NULL, so get_header is always a valid pointer */
1163         return "";
1164 }
1165
1166 static char *get_header(struct sip_request *req, char *name)
1167 {
1168         int start = 0;
1169         return __get_header(req, name, &start);
1170 }
1171
1172 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1173 {
1174         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
1175         struct ast_frame *f;
1176         static struct ast_frame null_frame = { AST_FRAME_NULL, };
1177         f = ast_rtp_read(p->rtp);
1178         /* Don't send RFC2833 if we're not supposed to */
1179         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1180                 return &null_frame;
1181         if (p->owner) {
1182                 /* We already hold the channel lock */
1183                 if (f->frametype == AST_FRAME_VOICE) {
1184                         if (f->subclass != p->owner->nativeformats) {
1185                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1186                                 p->owner->nativeformats = f->subclass;
1187                                 ast_set_read_format(p->owner, p->owner->readformat);
1188                                 ast_set_write_format(p->owner, p->owner->writeformat);
1189                         }
1190             if (p->dtmfmode & SIP_DTMF_INBAND) {
1191                    f = ast_dsp_process(p->owner,p->vad,f,0);
1192             }
1193                 }
1194         }
1195         return f;
1196 }
1197
1198 static struct ast_frame *sip_read(struct ast_channel *ast)
1199 {
1200         struct ast_frame *fr;
1201         struct sip_pvt *p = ast->pvt->pvt;
1202         ast_pthread_mutex_lock(&p->lock);
1203         fr = sip_rtp_read(p);
1204         ast_pthread_mutex_unlock(&p->lock);
1205         return fr;
1206 }
1207
1208 static void build_callid(char *callid, int len, struct in_addr ourip)
1209 {
1210         int res;
1211         int val;
1212         int x;
1213         for (x=0;x<4;x++) {
1214                 val = rand();
1215                 res = snprintf(callid, len, "%08x", val);
1216                 len -= res;
1217                 callid += res;
1218         }
1219         /* It's not important that we really use our right IP here... */
1220         snprintf(callid, len, "@%s", inet_ntoa(ourip));
1221 }
1222
1223 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1224 {
1225         struct sip_pvt *p;
1226
1227         p = malloc(sizeof(struct sip_pvt));
1228         if (!p)
1229                 return NULL;
1230         /* Keep track of stuff */
1231         memset(p, 0, sizeof(struct sip_pvt));
1232         p->initid = -1;
1233         p->autokillid = -1;
1234         p->rtp = ast_rtp_new(NULL, NULL);
1235         p->branch = rand();     
1236         p->tag = rand();
1237         /* Start with 101 instead of 1 */
1238         p->ocseq = 101;
1239         if (!p->rtp) {
1240                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1241                 free(p);
1242                 return NULL;
1243         }
1244         ast_rtp_settos(p->rtp, tos);
1245         if (useglobalnat && sin) {
1246                 /* Setup NAT structure according to global settings if we have an address */
1247                 p->nat = globalnat;
1248                 memcpy(&p->recv, sin, sizeof(p->recv));
1249                 ast_rtp_setnat(p->rtp, p->nat);
1250         }
1251         ast_pthread_mutex_init(&p->lock);
1252 #if 0
1253         ast_rtp_set_data(p->rtp, p);
1254         ast_rtp_set_callback(p->rtp, rtpready);
1255 #endif  
1256         if (sin) {
1257                 memcpy(&p->sa, sin, sizeof(p->sa));
1258                 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
1259         } else {
1260                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1261         }
1262         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1263         if (!callid)
1264                 build_callid(p->callid, sizeof(p->callid), p->ourip);
1265         else
1266                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1267         /* Assume reinvite OK and via INVITE */
1268         p->canreinvite = REINVITE_INVITE;
1269         p->dtmfmode = globaldtmfmode;
1270         if (p->dtmfmode & SIP_DTMF_RFC2833)
1271                 p->noncodeccapability |= AST_RTP_DTMF;
1272         strncpy(p->context, context, sizeof(p->context));
1273         /* Add to list */
1274         ast_pthread_mutex_lock(&iflock);
1275         p->next = iflist;
1276         iflist = p;
1277         ast_pthread_mutex_unlock(&iflock);
1278         if (option_debug)
1279                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1280         return p;
1281 }
1282
1283 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1284 {
1285         struct sip_pvt *p;
1286         char *callid;
1287         callid = get_header(req, "Call-ID");
1288         if (!strlen(callid)) {
1289                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1290                 return NULL;
1291         }
1292         ast_pthread_mutex_lock(&iflock);
1293         p = iflist;
1294         while(p) {
1295                 if (!strcmp(p->callid, callid)) {
1296                         /* Found the call */
1297 #if 0
1298                         if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1299                             (p->sa.sin_port != sin->sin_port))) {
1300                                         char orig[80];
1301                                         char new[80];
1302                                         snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1303                                         snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1304                                         ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1305                                         ast_pthread_mutex_unlock(&iflock);
1306                                         return NULL;
1307                         }
1308 #endif
1309                         ast_pthread_mutex_lock(&p->lock);
1310                         ast_pthread_mutex_unlock(&iflock);
1311                         return p;
1312                 }
1313                 p = p->next;
1314         }
1315         ast_pthread_mutex_unlock(&iflock);
1316         return sip_alloc(callid, sin, 1);
1317 }
1318
1319 static int sip_register(char *value, int lineno)
1320 {
1321         struct sip_registry *reg;
1322         char copy[256] = "";
1323         char *username, *hostname, *secret;
1324         char *porta;
1325         char *contact;
1326         char *stringp=NULL;
1327         
1328         struct hostent *hp;
1329         if (!value)
1330                 return -1;
1331         strncpy(copy, value, sizeof(copy)-1);
1332         stringp=copy;
1333         username = stringp;
1334         hostname = strrchr(stringp, '@');
1335         if (hostname) {
1336                 *hostname = '\0';
1337                 hostname++;
1338         }
1339         if (!hostname) {
1340                 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1341                 return -1;
1342         }
1343         stringp=username;
1344         username = strsep(&stringp, ":");
1345         secret = strsep(&stringp, ":");
1346         stringp = hostname;
1347         hostname = strsep(&stringp, "/");
1348         contact = strsep(&stringp, "/");
1349         if (!contact || !strlen(contact))
1350                 contact = "s";
1351         stringp=hostname;
1352         hostname = strsep(&stringp, ":");
1353         porta = strsep(&stringp, ":");
1354         
1355         if (porta && !atoi(porta)) {
1356                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1357                 return -1;
1358         }
1359         hp = gethostbyname(hostname);
1360         if (!hp) {
1361                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1362                 return -1;
1363         }
1364         reg = malloc(sizeof(struct sip_registry));
1365         if (reg) {
1366                 memset(reg, 0, sizeof(struct sip_registry));
1367                 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1368                 strncpy(reg->username, username, sizeof(reg->username)-1);
1369                 if (secret)
1370                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1371                 reg->expire = -1;
1372                 reg->refresh = default_expirey;
1373                 reg->addr.sin_family = AF_INET;
1374                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
1375                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1376                 reg->next = registrations;
1377                 reg->callid_valid = 0;
1378                 registrations = reg;
1379         } else {
1380                 ast_log(LOG_ERROR, "Out of memory\n");
1381                 return -1;
1382         }
1383         return 0;
1384 }
1385
1386 static void parse(struct sip_request *req)
1387 {
1388         /* Divide fields by NULL's */
1389         char *c;
1390         int f = 0;
1391         c = req->data;
1392
1393         /* First header starts immediately */
1394         req->header[f] = c;
1395         while(*c) {
1396                 if (*c == '\n') {
1397                         /* We've got a new header */
1398                         *c = 0;
1399
1400 #if 0
1401                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1402 #endif                  
1403                         if (!strlen(req->header[f])) {
1404                                 /* Line by itself means we're now in content */
1405                                 c++;
1406                                 break;
1407                         }
1408                         if (f >= SIP_MAX_HEADERS - 1) {
1409                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1410                         } else
1411                                 f++;
1412                         req->header[f] = c + 1;
1413                 } else if (*c == '\r') {
1414                         /* Ignore but eliminate \r's */
1415                         *c = 0;
1416                 }
1417                 c++;
1418         }
1419         /* Check for last header */
1420         if (strlen(req->header[f])) 
1421                 f++;
1422         req->headers = f;
1423         /* Now we process any mime content */
1424         f = 0;
1425         req->line[f] = c;
1426         while(*c) {
1427                 if (*c == '\n') {
1428                         /* We've got a new line */
1429                         *c = 0;
1430 #if 0
1431                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1432 #endif                  
1433                         if (f >= SIP_MAX_LINES - 1) {
1434                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1435                         } else
1436                                 f++;
1437                         req->line[f] = c + 1;
1438                 } else if (*c == '\r') {
1439                         /* Ignore and eliminate \r's */
1440                         *c = 0;
1441                 }
1442                 c++;
1443         }
1444         /* Check for last line */
1445         if (strlen(req->line[f])) 
1446                 f++;
1447         req->lines = f;
1448         if (sipdebug)
1449                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1450         if (*c) 
1451                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1452 }
1453
1454 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1455 {
1456         char *m;
1457         char *c;
1458         char *a;
1459         char host[258];
1460         int len = -1;
1461         int portno;
1462         int peercapability, peernoncodeccapability;
1463         struct sockaddr_in sin;
1464         char *codecs;
1465         struct hostent *hp;
1466         int codec;
1467         int iterator;
1468
1469         /* Get codec and RTP info from SDP */
1470         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1471                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1472                 return -1;
1473         }
1474         m = get_sdp(req, "m");
1475         c = get_sdp(req, "c");
1476         if (!strlen(m) || !strlen(c)) {
1477                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1478                 return -1;
1479         }
1480         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1481                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1482                 return -1;
1483         }
1484         /* XXX This could block for a long time, and block the main thread! XXX */
1485         hp = gethostbyname(host);
1486         if (!hp) {
1487                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1488                 return -1;
1489         }
1490         if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1491                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
1492                 return -1;
1493         }
1494         sin.sin_family = AF_INET;
1495         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1496         sin.sin_port = htons(portno);
1497         if (p->rtp)
1498                 ast_rtp_set_peer(p->rtp, &sin);
1499 #if 0
1500         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1501 #endif  
1502         // Scan through the RTP payload types specified in a "m=" line:
1503         ast_rtp_pt_clear(p->rtp);
1504         codecs = m + len;
1505         while(strlen(codecs)) {
1506                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1507                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1508                         return -1;
1509                 }
1510                 ast_rtp_set_m_type(p->rtp, codec);
1511                 codecs += len;
1512                 /* Skip over any whitespace */
1513                 while(*codecs && (*codecs < 33)) codecs++;
1514         }
1515
1516         // Next, scan through each "a=rtpmap:" line, noting each
1517         // specified RTP payload type (with corresponding MIME subtype):
1518         sdpLineNum_iterator_init(&iterator);
1519         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1520           char* mimeSubtype = strdup(a); // ensures we have enough space
1521           if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1522           // Note: should really look at the 'freq' and '#chans' params too
1523           ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1524           free(mimeSubtype);
1525         }
1526
1527         // Now gather all of the codecs that were asked for:
1528         ast_rtp_get_current_formats(p->rtp,
1529                                 &peercapability, &peernoncodeccapability);
1530         p->capability = capability & peercapability;
1531         p->noncodeccapability = noncodeccapability & peernoncodeccapability;
1532         if (sipdebug) {
1533                 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1534                             capability, peercapability, p->capability);
1535                 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1536                             noncodeccapability, peernoncodeccapability,
1537                             p->noncodeccapability);
1538         }
1539         if (!p->capability) {
1540                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1541                 return -1;
1542         }
1543         if (p->owner) {
1544                 if (!(p->owner->nativeformats & p->capability)) {
1545                         ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %d and not %d\n", p->capability, p->owner->nativeformats);
1546                         p->owner->nativeformats = sip_codec_choose(p->capability);
1547                         ast_set_read_format(p->owner, p->owner->readformat);
1548                         ast_set_write_format(p->owner, p->owner->writeformat);
1549                 }
1550                 if (p->owner->bridge) {
1551                         /* Turn on/off music on hold if we are holding/unholding */
1552                         if (sin.sin_addr.s_addr) {
1553                                 ast_moh_stop(p->owner->bridge);
1554                         } else {
1555                                 ast_moh_start(p->owner->bridge, NULL);
1556                         }
1557                 }
1558         }
1559         return 0;
1560         
1561 }
1562
1563 static int add_header(struct sip_request *req, char *var, char *value)
1564 {
1565         if (req->len >= sizeof(req->data) - 4) {
1566                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1567                 return -1;
1568         }
1569         if (req->lines) {
1570                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1571                 return -1;
1572         }
1573         req->header[req->headers] = req->data + req->len;
1574         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1575         req->len += strlen(req->header[req->headers]);
1576         if (req->headers < SIP_MAX_HEADERS)
1577                 req->headers++;
1578         else {
1579                 ast_log(LOG_WARNING, "Out of header space\n");
1580                 return -1;
1581         }
1582         return 0;       
1583 }
1584
1585 static int add_blank_header(struct sip_request *req)
1586 {
1587         if (req->len >= sizeof(req->data) - 4) {
1588                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1589                 return -1;
1590         }
1591         if (req->lines) {
1592                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1593                 return -1;
1594         }
1595         req->header[req->headers] = req->data + req->len;
1596         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1597         req->len += strlen(req->header[req->headers]);
1598         if (req->headers < SIP_MAX_HEADERS)
1599                 req->headers++;
1600         else {
1601                 ast_log(LOG_WARNING, "Out of header space\n");
1602                 return -1;
1603         }
1604         return 0;       
1605 }
1606
1607 static int add_line(struct sip_request *req, char *line)
1608 {
1609         if (req->len >= sizeof(req->data) - 4) {
1610                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1611                 return -1;
1612         }
1613         if (!req->lines) {
1614                 /* Add extra empty return */
1615                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1616                 req->len += strlen(req->data + req->len);
1617         }
1618         req->line[req->lines] = req->data + req->len;
1619         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1620         req->len += strlen(req->line[req->lines]);
1621         if (req->lines < SIP_MAX_LINES)
1622                 req->lines++;
1623         else {
1624                 ast_log(LOG_WARNING, "Out of line space\n");
1625                 return -1;
1626         }
1627         return 0;       
1628 }
1629
1630 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1631 {
1632         char *tmp;
1633         tmp = get_header(orig, field);
1634         if (strlen(tmp)) {
1635                 /* Add what we're responding to */
1636                 return add_header(req, field, tmp);
1637         }
1638         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1639         return -1;
1640 }
1641
1642 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1643 {
1644         char *tmp;
1645         int start = 0;
1646         int copied = 0;
1647         for (;;) {
1648                 tmp = __get_header(orig, field, &start);
1649                 if (strlen(tmp)) {
1650                         /* Add what we're responding to */
1651                         add_header(req, field, tmp);
1652                         copied++;
1653                 } else
1654                         break;
1655         }
1656         return copied ? 0 : -1;
1657 }
1658
1659 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1660 {
1661         char *tmp;
1662         int start = 0;
1663         int copied = 0;
1664         char new[256];
1665         for (;;) {
1666                 tmp = __get_header(orig, field, &start);
1667                 if (strlen(tmp)) {
1668                         if (!copied && p->nat) {
1669                                 /* SLD: FIXME: Nice try, but the received= should not have a port */
1670                                 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
1671                                 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1672                                         snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1673                                 else
1674                                         snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1675                                 add_header(req, field, new);
1676                         } else {
1677                                 /* Add what we're responding to */
1678                                 add_header(req, field, tmp);
1679                         }
1680                         copied++;
1681                 } else
1682                         break;
1683         }
1684         if (!copied) {
1685                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1686                 return -1;
1687         }
1688         return 0;
1689 }
1690
1691 /* Add Route: header into request per learned route */
1692 static void add_route(struct sip_request *req, struct sip_route *route)
1693 {
1694         char r[256], *p;
1695         int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
1696
1697         if (!route) return;
1698
1699         p = r;
1700         while (route) {
1701                 n = strlen(route->hop);
1702                 if ((n+3)>rem) break;
1703                 if (p != r) {
1704                         *p++ = ',';
1705                         --rem;
1706                 }
1707                 *p++ = '<';
1708                 strcpy(p, route->hop);  p += n;
1709                 *p++ = '>';
1710                 rem -= (n+2);
1711                 route = route->next;
1712         }
1713         *p = '\0';
1714         add_header(req, "Route", r);
1715 }
1716
1717 static void set_destination(struct sip_pvt *p, char *uri)
1718 {
1719         char *h, *maddr, hostname[256];
1720         int port, hn;
1721         struct hostent *hp;
1722
1723         /* Parse uri to h (host) and port - uri is already just the part inside the <> */
1724         /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
1725
1726         if (sipdebug)
1727                 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
1728
1729         h = strchr(uri, '@');
1730         if (!h) {
1731                 ast_log(LOG_WARNING, "set_destination: Can't parse sip URI '%s'\n", uri);
1732                 return;
1733         }
1734         ++h;
1735         hn = strcspn(h, ":;>");
1736         hostname[255] = '\0';
1737         strncpy(hostname, h, (hn>255)?255:hn);
1738         h+=hn;
1739         /* Is "port" present? if not default to 5060 */
1740         if (*h == ':') {
1741                 /* Parse port */
1742                 ++h;
1743                 port = strtol(h, &h, 10);
1744         }
1745         else
1746                 port = 5060;
1747
1748         /* Got the hostname:port - but maybe there's a ";maddr=" to override address? */
1749         maddr = strstr(h, ";maddr=");
1750         if (maddr) {
1751                 maddr += 7;
1752                 hn = strspn(maddr, "0123456789.");
1753                 strncpy(hostname, maddr, (hn>255)?255:hn);
1754         }
1755         
1756         hp = gethostbyname(hostname);
1757         if (hp == NULL)  {
1758                 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", h);
1759                 return;
1760         }
1761         p->sa.sin_family = AF_INET;
1762         memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
1763         p->sa.sin_port = htons(port);
1764         ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
1765 }
1766
1767 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1768 {
1769         /* Initialize a response */
1770         if (req->headers || req->len) {
1771                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1772                 return -1;
1773         }
1774         req->header[req->headers] = req->data + req->len;
1775         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1776         req->len += strlen(req->header[req->headers]);
1777         if (req->headers < SIP_MAX_HEADERS)
1778                 req->headers++;
1779         else
1780                 ast_log(LOG_WARNING, "Out of header space\n");
1781         return 0;
1782 }
1783
1784 static int init_req(struct sip_request *req, char *resp, char *recip)
1785 {
1786         /* Initialize a response */
1787         if (req->headers || req->len) {
1788                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1789                 return -1;
1790         }
1791         req->header[req->headers] = req->data + req->len;
1792         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1793         req->len += strlen(req->header[req->headers]);
1794         if (req->headers < SIP_MAX_HEADERS)
1795                 req->headers++;
1796         else
1797                 ast_log(LOG_WARNING, "Out of header space\n");
1798         return 0;
1799 }
1800
1801 static void append_contact(struct sip_request *req, struct sip_pvt *p)
1802 {
1803         /* Add contact header */
1804         char contact2[256] ="", *c, contact[256];
1805         char *from;
1806         if (p->outgoing)
1807                 from = get_header(req, "From");
1808         else
1809                 from = get_header(req, "To");
1810         strncpy(contact2, from, sizeof(contact2)-1);
1811         if (strlen(contact2)) {
1812                 c = ditch_braces(contact2);
1813                 snprintf(contact, sizeof(contact), "<%s>", c);
1814                 add_header(req, "Contact", contact);
1815         }
1816 }
1817
1818 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1819 {
1820         char newto[256] = "", *ot;
1821         memset(resp, 0, sizeof(*resp));
1822         init_resp(resp, msg, req);
1823         copy_via_headers(p, resp, req, "Via");
1824         if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
1825         copy_header(resp, req, "From");
1826         ot = get_header(req, "To");
1827         if (!strstr(ot, "tag=")) {
1828                 /* Add the proper tag if we don't have it already.  If they have specified
1829                    their tag, use it.  Otherwise, use our own tag */
1830                 if (strlen(p->theirtag))
1831                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1832                 else if (p->tag)
1833                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1834                 else
1835                         strncpy(newto, ot, sizeof(newto) - 1);
1836                 ot = newto;
1837         }
1838         add_header(resp, "To", ot);
1839         copy_header(resp, req, "Call-ID");
1840         copy_header(resp, req, "CSeq");
1841         add_header(resp, "User-Agent", "Asterisk PBX");
1842         if (p->expirey) {
1843                 /* For registration responses, we also need expirey and
1844                    contact info */
1845                 char tmp[80];
1846                 char contact[256];
1847                 char *c;
1848                 if ((c=getsipuri(ot))) {
1849                         snprintf(contact, sizeof(contact), "<%s@%s:%d>", c, inet_ntoa(p->ourip), ourport);
1850                         free(c);
1851                 } else {
1852                         snprintf(contact, sizeof(contact), "<%s:%d>", inet_ntoa(p->ourip), ourport);
1853                 }
1854                 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1855                 add_header(resp, "Expires", tmp);
1856                 add_header(resp, "Contact", contact);
1857         } else {
1858                 char contact[256];
1859                 /* XXX This isn't exactly right and it's implemented
1860                        very stupidly *sigh* XXX */
1861                 char *c;
1862                 if ((c=getsipuri(ot))) {
1863                         snprintf(contact, sizeof(contact), "<%s@%s:%d>", c, inet_ntoa(p->ourip), ourport);
1864                         free(c);
1865                 } else {
1866                         snprintf(contact, sizeof(contact), "<%s:%d>", inet_ntoa(p->ourip), ourport);
1867                 }
1868                 add_header(resp, "Contact", contact);
1869         }
1870         return 0;
1871 }
1872
1873 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1874 {
1875         struct sip_request *orig = &p->initreq;
1876         char stripped[80] ="";
1877         char tmp[80];
1878         char newto[256];
1879         char *c, *n;
1880         char *ot, *of;
1881
1882         memset(req, 0, sizeof(struct sip_request));
1883         
1884         if (inc)
1885                 p->ocseq++;
1886
1887         if (p->outgoing)
1888                 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1889         else
1890                 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1891         
1892         c = strchr(stripped, '<');
1893         if (c) 
1894                 c++;
1895         else
1896                 c = stripped;
1897         n = strchr(c, '>');
1898         if (n)
1899                 *n = '\0';
1900         
1901         init_req(req, msg, c);
1902
1903         snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1904
1905         add_header(req, "Via", p->via);
1906         if (p->route) {
1907                 set_destination(p, p->route->hop);
1908                 add_route(req, p->route->next);
1909         }
1910
1911         ot = get_header(orig, "To");
1912         of = get_header(orig, "From");
1913
1914         if (!strstr(ot, "tag=")) {
1915                 /* Add the proper tag if we don't have it already.  If they have specified
1916                    their tag, use it.  Otherwise, use our own tag */
1917                 if (strlen(p->theirtag))
1918                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1919                 else
1920                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1921                 ot = newto;
1922         }
1923
1924         if (p->outgoing) {
1925                 add_header(req, "From", of);
1926                 add_header(req, "To", ot);
1927         } else {
1928                 add_header(req, "From", ot);
1929                 add_header(req, "To", of);
1930         }
1931         append_contact(req, p);
1932         copy_header(req, orig, "Call-ID");
1933         add_header(req, "CSeq", tmp);
1934
1935         add_header(req, "User-Agent", "Asterisk PBX");
1936         return 0;
1937 }
1938
1939 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
1940 {
1941         struct sip_request resp;
1942         int seqno = 0;
1943         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
1944                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
1945                 return -1;
1946         }
1947         respprep(&resp, p, msg, req);
1948         add_header(&resp, "Content-Length", "0");
1949         add_blank_header(&resp);
1950         return send_response(p, &resp, reliable, seqno);
1951 }
1952
1953 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req) 
1954 {
1955         return __transmit_response(p, msg, req, 0);
1956 }
1957 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
1958 {
1959         return __transmit_response(p, msg, req, 1);
1960 }
1961
1962 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
1963 {
1964         struct sip_request resp;
1965         respprep(&resp, p, msg, req);
1966         add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
1967         add_header(&resp, "Accept", "application/sdp");
1968         add_header(&resp, "Content-Length", "0");
1969         add_blank_header(&resp);
1970         return send_response(p, &resp, 0, 0);
1971 }
1972
1973 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
1974 {
1975         struct sip_request resp;
1976         char tmp[256];
1977         int seqno = 0;
1978         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
1979                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
1980                 return -1;
1981         }
1982         snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
1983         respprep(&resp, p, msg, req);
1984         add_header(&resp, "Proxy-Authenticate", tmp);
1985         add_header(&resp, "Content-Length", "0");
1986         add_blank_header(&resp);
1987         return send_response(p, &resp, reliable, seqno);
1988 }
1989
1990 static int add_text(struct sip_request *req, char *text)
1991 {
1992         /* XXX Convert \n's to \r\n's XXX */
1993         int len = strlen(text);
1994         char clen[256];
1995         snprintf(clen, sizeof(clen), "%d", len);
1996         add_header(req, "Content-Type", "text/plain");
1997         add_header(req, "Content-Length", clen);
1998         add_line(req, text);
1999         return 0;
2000 }
2001
2002 static int add_digit(struct sip_request *req, char digit)
2003 {
2004         char tmp[256];
2005         int len;
2006         char clen[256];
2007         snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2008         len = strlen(tmp);
2009         snprintf(clen, sizeof(clen), "%d", len);
2010         add_header(req, "Content-Type", "application/dtmf-relay");
2011         add_header(req, "Content-Length", clen);
2012         add_line(req, tmp);
2013         return 0;
2014 }
2015
2016 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
2017 {
2018         int len;
2019         int codec;
2020         int alreadysent = 0;
2021         char costr[80];
2022         struct sockaddr_in sin;
2023         struct sip_codec_pref *cur;
2024         char v[256];
2025         char s[256];
2026         char o[256];
2027         char c[256];
2028         char t[256];
2029         char m[256];
2030         char a[1024] = "";
2031         int x;
2032         struct sockaddr_in dest;
2033         /* XXX We break with the "recommendation" and send our IP, in order that our
2034                peer doesn't have to gethostbyname() us XXX */
2035         len = 0;
2036         if (!p->rtp) {
2037                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2038                 return -1;
2039         }
2040         ast_rtp_get_us(p->rtp, &sin);
2041         if (rtp) {
2042                 ast_rtp_get_peer(rtp, &dest);
2043         } else {
2044                 dest.sin_addr = p->ourip;
2045                 dest.sin_port = sin.sin_port;
2046         }
2047         if (sipdebug)
2048                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
2049         snprintf(v, sizeof(v), "v=0\r\n");
2050         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2051         snprintf(s, sizeof(s), "s=session\r\n");
2052         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2053         snprintf(t, sizeof(t), "t=0 0\r\n");
2054         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2055         /* Start by sending our preferred codecs */
2056         cur = prefs;
2057         while(cur) {
2058                 if (p->capability & cur->codec) {
2059                         if (sipdebug)
2060                                 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2061                         codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2062                         if (codec > -1) {
2063                                 snprintf(costr, sizeof(costr), " %d", codec);
2064                                 strcat(m, costr);
2065                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2066                                 strcat(a, costr);
2067                         }
2068                 }
2069                 alreadysent |= cur->codec;
2070                 cur = cur->next;
2071         }
2072         /* Now send any other common codecs, and non-codec formats: */
2073         for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2074                 if ((p->capability & x) && !(alreadysent & x)) {
2075                         if (sipdebug)
2076                                 ast_verbose("Answering with capability %d\n", x);       
2077                         codec = ast_rtp_lookup_code(p->rtp, 1, x);
2078                         if (codec > -1) {
2079                         snprintf(costr, sizeof(costr), " %d", codec);
2080                                 strcat(m, costr);
2081                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2082                                 strcat(a, costr);
2083                         }
2084                 }
2085         }
2086         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2087                 if (p->noncodeccapability & x) {
2088                         if (sipdebug)
2089                                 ast_verbose("Answering with non-codec capability %d\n", x);
2090                         codec = ast_rtp_lookup_code(p->rtp, 0, x);
2091                         if (codec > -1) {
2092                                 snprintf(costr, sizeof(costr), " %d", codec);
2093                                 strcat(m, costr);
2094                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2095                                 strcat(a, costr);
2096                                 if (x == AST_RTP_DTMF) {
2097                                   /* Indicate we support DTMF...  Not sure about 16, but MSN supports it so dang it, we will too... */
2098                                   snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2099                                            codec);
2100                                   strcat(a, costr);
2101                                 }
2102                         }
2103                 }
2104         }
2105         strcat(m, "\r\n");
2106         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2107         snprintf(costr, sizeof(costr), "%d", len);
2108         add_header(resp, "Content-Type", "application/sdp");
2109         add_header(resp, "Content-Length", costr);
2110         add_line(resp, v);
2111         add_line(resp, o);
2112         add_line(resp, s);
2113         add_line(resp, c);
2114         add_line(resp, t);
2115         add_line(resp, m);
2116         add_line(resp, a);
2117         return 0;
2118 }
2119
2120 static void copy_request(struct sip_request *dst,struct sip_request *src)
2121 {
2122         long offset;
2123         int x;
2124         offset = ((void *)dst) - ((void *)src);
2125         /* First copy stuff */
2126         memcpy(dst, src, sizeof(*dst));
2127         /* Now fix pointer arithmetic */
2128         for (x=0;x<src->headers;x++)
2129                 dst->header[x] += offset;
2130         for (x=0;x<src->lines;x++)
2131                 dst->line[x] += offset;
2132 }
2133
2134 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2135 {
2136         struct sip_request resp;
2137         int seqno;
2138         if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2139                 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2140                 return -1;
2141         }
2142         respprep(&resp, p, msg, req);
2143         add_sdp(&resp, p, NULL);
2144         return send_response(p, &resp, retrans, seqno);
2145 }
2146
2147 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
2148 {
2149         struct sip_request resp;
2150         if (p->canreinvite == REINVITE_UPDATE)
2151                 reqprep(&resp, p, "UPDATE", 1);
2152         else
2153                 reqprep(&resp, p, "INVITE", 1);
2154         add_sdp(&resp, p, rtp);
2155         return send_request(p, &resp, 1, p->ocseq);
2156 }
2157
2158 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2159 {
2160         char invite[256];
2161         char from[256];
2162         char to[256];
2163         char tmp[80];
2164         char cid[256];
2165         char *l = callerid, *n=NULL;
2166         if (p->owner && p->owner->callerid) {
2167                 strcpy(cid, p->owner->callerid);
2168                 ast_callerid_parse(cid, &n, &l);
2169                 if (l) 
2170                         ast_shrink_phone_number(l);
2171                 if (!l || !ast_isphonenumber(l))
2172                                 l = callerid;
2173         }
2174         if (!n)
2175                 n = l;
2176         snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%08x", n, l, inet_ntoa(p->ourip), ourport, p->tag);
2177
2178         if (strlen(p->username)) {
2179                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2180                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2181                 } else {
2182                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
2183                 }
2184         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2185                 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2186         } else {
2187                 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
2188         }
2189         /* If there is a VXML URL append it to the SIP URL */
2190         if (vxml_url)
2191         {
2192                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2193         }
2194         else
2195         {
2196                 snprintf(to, sizeof(to), "<%s>", invite );
2197         }
2198         memset(req, 0, sizeof(struct sip_request));
2199         init_req(req, cmd, invite);
2200         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2201
2202         add_header(req, "Via", p->via);
2203         /* SLD: FIXME?: do Route: here too?  I think not cos this is the first request.
2204          * OTOH, then we won't have anything in p->route anyway */
2205         add_header(req, "From", from);
2206         {
2207                 char contact2[256] ="", *c, contact[256];
2208                 /* XXX This isn't exactly right and it's implemented
2209                        very stupidly *sigh* XXX */
2210                 strncpy(contact2, from, sizeof(contact2)-1);
2211                 c = ditch_braces(contact2);
2212                 snprintf(contact, sizeof(contact), "<%s>", c);
2213                 add_header(req, "Contact", contact);
2214         }
2215         add_header(req, "To", to);
2216         add_header(req, "Call-ID", p->callid);
2217         add_header(req, "CSeq", tmp);
2218         add_header(req, "User-Agent", "Asterisk PBX");
2219 }
2220
2221 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2222 {
2223         struct sip_request req;
2224         initreqprep(&req, p, cmd, vxml_url);
2225         if (auth)
2226                 add_header(&req, "Proxy-Authorization", auth);
2227         if (sdp) {
2228                 add_sdp(&req, p, NULL);
2229         } else {
2230                 add_header(&req, "Content-Length", "0");
2231                 add_blank_header(&req);
2232         }
2233         if (!p->initreq.headers) {
2234                 /* Use this as the basis */
2235                 copy_request(&p->initreq, &req);
2236                 parse(&p->initreq);
2237         }
2238         p->lastinvite = p->ocseq;
2239         return send_request(p, &req, 1, p->ocseq);
2240 }
2241
2242 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2243 {
2244         struct sip_request req;
2245         char tmp[256];
2246         char tmp2[256];
2247         char clen[20];
2248         initreqprep(&req, p, "NOTIFY", NULL);
2249         add_header(&req, "Event", "message-summary");
2250         add_header(&req, "Content-Type", "application/simple-message-summary");
2251
2252         snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", newmsgs ? "yes" : "no");
2253         snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2254         snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2255         add_header(&req, "Content-Length", clen);
2256         add_line(&req, tmp);
2257         add_line(&req, tmp2);
2258
2259         if (!p->initreq.headers) {
2260                 /* Use this as the basis */
2261                 copy_request(&p->initreq, &req);
2262                 parse(&p->initreq);
2263         }
2264
2265         p->lastinvite = p->ocseq;
2266         return send_request(p, &req, 1, p->ocseq);
2267 }
2268
2269 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2270
2271 static int sip_reregister(void *data) 
2272 {
2273         /* if we are here, we know that we need to reregister. */
2274         struct sip_registry *r=(struct sip_registry *)data;
2275         return sip_do_register(r);
2276         
2277 }
2278
2279
2280 static int sip_do_register(struct sip_registry *r)
2281 {
2282         int res;
2283         ast_pthread_mutex_lock(&r->lock);
2284         res=transmit_register(r, "REGISTER", NULL);
2285         ast_pthread_mutex_unlock(&r->lock);
2286         return res;
2287 }
2288
2289 static int sip_reg_timeout(void *data)
2290 {
2291         /* if we are here, our registration timed out, so we'll just do it over */
2292         struct sip_registry *r=data;
2293         int res;
2294         ast_pthread_mutex_lock(&r->lock);
2295         ast_log(LOG_NOTICE, "Registration timed out, trying again\n"); 
2296         r->regstate=REG_STATE_UNREGISTERED;
2297         /* cancel ourselves first!!! */
2298         /* ast_sched_del(sched,r->timeout); */
2299         res=transmit_register(r, "REGISTER", NULL);
2300         ast_pthread_mutex_unlock(&r->lock);
2301         return res;
2302 }
2303
2304 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2305 {
2306         struct sip_request req;
2307         char from[256];
2308         char to[256];
2309         char tmp[80];
2310         char via[80];
2311         char addr[80];
2312         struct sip_pvt *p;
2313         /* exit if we are already in process with this registrar ?*/
2314         if ( r == NULL || (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
2315                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2316                 return 0;
2317         }
2318
2319
2320         if (!(p=r->call)) {
2321                 if (!r->callid_valid) {
2322                   build_callid(r->callid, sizeof(r->callid), __ourip);
2323                   r->callid_valid=1;
2324                 }
2325                 p=sip_alloc( r->callid, &r->addr, 0);
2326                 p->outgoing = 1;
2327                 r->call=p;
2328                 p->registry=r;
2329                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2330                 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2331                 strncpy(p->username, r->username, sizeof(p->username)-1);
2332         }
2333
2334         /* set up a timeout */
2335         if (auth==NULL && !r->timeout)  {
2336                 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
2337                 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
2338         }
2339
2340         snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2341         snprintf(to, sizeof(to),     "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2342         
2343         snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
2344
2345         memset(&req, 0, sizeof(req));
2346         init_req(&req, cmd, addr);
2347
2348         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2349
2350         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
2351         add_header(&req, "Via", via);
2352         add_header(&req, "From", from);
2353         add_header(&req, "To", to);
2354         {
2355                 char contact[256];
2356                 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
2357                 add_header(&req, "Contact", contact);
2358         }
2359         add_header(&req, "Call-ID", p->callid);
2360         add_header(&req, "CSeq", tmp);
2361         add_header(&req, "User-Agent", "Asterisk PBX");
2362         if (auth) 
2363                 add_header(&req, "Authorization", auth);
2364
2365         snprintf(tmp, sizeof(tmp), "%d", default_expirey);
2366         add_header(&req, "Expires", tmp);
2367         add_header(&req, "Event", "registration");
2368         copy_request(&p->initreq, &req);
2369         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2370         return send_request(p, &req, 1, p->ocseq);
2371 }
2372
2373 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2374 {
2375         struct sip_request req;
2376         reqprep(&req, p, "MESSAGE", 1);
2377         add_text(&req, text);
2378         return send_request(p, &req, 1, p->ocseq);
2379 }
2380
2381 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2382 {
2383         struct sip_request req;
2384         reqprep(&req, p, "INFO", 1);
2385         add_digit(&req, digit);
2386         return send_request(p, &req, 1, p->ocseq);
2387 }
2388
2389 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable)
2390 {
2391         struct sip_request resp;
2392         reqprep(&resp, p, msg, inc);
2393         add_header(&resp, "Content-Length", "0");
2394         add_blank_header(&resp);
2395         return send_request(p, &resp, reliable, p->ocseq);
2396 }
2397
2398 static int expire_register(void *data)
2399 {
2400         struct sip_peer *p = data;
2401         memset(&p->addr, 0, sizeof(p->addr));
2402         p->expire = -1;
2403         return 0;
2404 }
2405
2406 static int sip_poke_peer(struct sip_peer *peer);
2407
2408 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2409 {
2410         char contact[80]= ""; 
2411         char *expires = get_header(req, "Expires");
2412         int expirey = atoi(expires);
2413         char *c, *n, *pt;
2414         int port;
2415         struct hostent *hp;
2416         struct sockaddr_in oldsin;
2417         if (!strlen(expires)) {
2418                 expires = strstr(get_header(req, "Contact"), "expires=");
2419                 if (expires) 
2420                         if (sscanf(expires + 8, "%d;", &expirey) != 1)
2421                                 expirey = 0;
2422         }
2423         /* Look for brackets */
2424         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2425         c = contact;
2426         
2427         if ((n=strchr(c, '<'))) {
2428                 c = n + 1;
2429                 n = strchr(c, '>');
2430                 /* Lose the part after the > */
2431                 if (n) 
2432                         *n = '\0';
2433         }
2434         if (!strcasecmp(c, "*")) {
2435                 /* This means remove all registrations and return OK */
2436                 memset(&p->addr, 0, sizeof(p->addr));
2437                 if (p->expire > -1)
2438                         ast_sched_del(sched, p->expire);
2439                 p->expire = -1;
2440                 if (option_verbose > 2)
2441                         ast_verbose(VERBOSE_PREFIX_3 "Unegistered SIP '%s'\n", p->username);
2442                 return 0;
2443         }
2444         /* Make sure it's a SIP URL */
2445         if (strncasecmp(c, "sip:", 4)) {
2446                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2447         } else
2448                 c += 4;
2449         /* Ditch q */
2450         n = strchr(c, ';');
2451         if (n) 
2452                 *n = '\0';
2453         /* Grab host */
2454         n = strchr(c, '@');
2455         if (!n) {
2456                 n = c;
2457                 c = NULL;
2458         } else {
2459                 *n = '\0';
2460                 n++;
2461         }
2462         pt = strchr(n, ':');
2463         if (pt) {
2464                 *pt = '\0';
2465                 pt++;
2466                 port = atoi(pt);
2467         } else
2468                 port = DEFAULT_SIP_PORT;
2469         memcpy(&oldsin, &p->addr, sizeof(oldsin));
2470         if (!p->nat) {
2471                 /* XXX This could block for a long time XXX */
2472                 hp = gethostbyname(n);
2473                 if (!hp)  {
2474                         ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2475                         return -1;
2476                 }
2477                 p->addr.sin_family = AF_INET;
2478                 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2479                 p->addr.sin_port = htons(port);
2480         } else {
2481                 /* Don't trust the contact field.  Just use what they came to us
2482                    with */
2483                 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2484         }
2485         if (c)
2486                 strncpy(p->username, c, sizeof(p->username) - 1);
2487         else
2488                 strcpy(p->username, "");
2489         if (p->expire > -1)
2490                 ast_sched_del(sched, p->expire);
2491         if ((expirey < 1) || (expirey > max_expirey))
2492                 expirey = max_expirey;
2493         p->expire = ast_sched_add(sched, (expirey + 10) * 1000, expire_register, p);
2494         pvt->expirey = expirey;
2495         if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2496                 sip_poke_peer(p);
2497                 if (option_verbose > 2)
2498                         ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", p->username, inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), expirey);
2499         }
2500         return 0;
2501 }
2502
2503 static void free_old_route(struct sip_route *route)
2504 {
2505         struct sip_route *next;
2506         while (route) {
2507                 next = route->next;
2508                 free(route);
2509                 route = next;
2510         }
2511 }
2512
2513 static void list_route(struct sip_route *route)
2514 {
2515         if (!route) {
2516                 ast_verbose("list_route: no route\n");
2517                 return;
2518         }
2519         while (route) {
2520                 ast_verbose("list_route: hop: <%s>\n", route->hop);
2521                 route = route->next;
2522         }
2523 }
2524
2525 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
2526 {
2527         struct sip_route *thishop, *head, *tail;
2528         int start = 0;
2529         int len;
2530         char *rr, *contact, *c;
2531
2532         if (p->route) {
2533                 free_old_route(p->route);
2534                 p->route = NULL;
2535         }
2536         /* We build up head, then assign it to p->route when we're done */
2537         head = NULL;  tail = head;
2538         /* 1st pass through all the hops in any Record-Route headers */
2539         for (;;) {
2540                 /* Each Record-Route header */
2541                 rr = __get_header(req, "Record-Route", &start);
2542                 /*ast_verbose("Record-Route: %s\n", rr);*/
2543                 if (*rr == '\0') break;
2544                 for (;;) {
2545                         /* Each route entry */
2546                         /* Find < */
2547                         rr = strchr(rr, '<');
2548                         if (!rr) break; /* No more hops */
2549                         ++rr;
2550                         len = strcspn(rr, ">");
2551                         /* Make a struct route */
2552                         thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2553                         if (thishop) {
2554                                 strncpy(thishop->hop, rr, len);
2555                                 thishop->hop[len] = '\0';
2556                                 ast_verbose("build_route: Record-Route hop: <%s>\n", thishop->hop);
2557                                 /* Link in */
2558                                 if (backwards) {
2559                                         /* Link in at head so they end up in reverse order */
2560                                         thishop->next = head;
2561                                         head = thishop;
2562                                         /* If this was the first then it'll be the tail */
2563                                         if (!tail) tail = thishop;
2564                                 } else {
2565                                         /* Link in at the end */
2566                                         if (tail)
2567                                                 tail->next = thishop;
2568                                         else
2569                                                 head = thishop;
2570                                         tail = thishop;
2571                                 }
2572                         }
2573                         rr += len+1;
2574                 }
2575         }
2576         /* 2nd append the Contact: if there is one */
2577         /* Can be multiple Contact headers, comma separated values - we just take the first */
2578         contact = get_header(req, "Contact");
2579         if (strlen(contact)) {
2580                 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
2581                 /* Look for <: delimited address */
2582                 c = strchr(contact, '<');
2583                 if (c) {
2584                         /* Take to > */
2585                         ++c;
2586                         len = strcspn(c, ">");
2587                 } else {
2588                         /* No <> - just take the lot */
2589                         c = contact; len = strlen(contact);
2590                 }
2591                 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2592                 strncpy(thishop->hop, c, len);
2593                 thishop->hop[len] = '\0';
2594                 /* Goes at the end */
2595                 if (tail)
2596                         tail->next = thishop;
2597                 else
2598                         head = thishop;
2599         }
2600         /* Store as new route */
2601         p->route = head;
2602
2603         /* For debugging dump what we ended up with */
2604         if (sipdebug)
2605                 list_route(p->route);
2606 }
2607
2608 static void md5_hash(char *output, char *input)
2609 {
2610                 struct MD5Context md5;
2611                 unsigned char digest[16];
2612                 char *ptr;
2613                 int x;
2614                 MD5Init(&md5);
2615                 MD5Update(&md5, input, strlen(input));
2616                 MD5Final(digest, &md5);
2617                 ptr = output;
2618                 for (x=0;x<16;x++)
2619                         ptr += sprintf(ptr, "%2.2x", digest[x]);
2620 }
2621
2622 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri, int reliable)
2623 {
2624         int res = -1;
2625         /* Always OK if no secret */
2626         if (!strlen(secret))
2627                 return 0;
2628         if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2629                 snprintf(randdata, randlen, "%08x", rand());
2630                 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
2631                 /* Schedule auto destroy in 15 seconds */
2632                 sip_scheddestroy(p, 15000);
2633                 res = 1;
2634         } else {
2635                 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2636                    an example in the spec of just what it is you're doing a hash on. */
2637                 char a1[256];
2638                 char a2[256];
2639                 char a1_hash[256];
2640                 char a2_hash[256];
2641                 char resp[256];
2642                 char resp_hash[256];
2643                 char tmp[256] = "";
2644                 char *c;
2645                 char *response ="";
2646                 char *resp_uri ="";
2647
2648                 /* Find their response among the mess that we'r sent for comparison */
2649                 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2650                 c = tmp;
2651
2652                 while(c) {
2653                         while (*c && (*c < 33)) c++;
2654                         if (!*c)
2655                                 break;
2656                         if (!strncasecmp(c, "response=", strlen("response="))) {
2657                                 c+= strlen("response=");
2658                                 if ((*c == '\"')) {
2659                                         response=++c;
2660                                         if((c = strchr(c,'\"')))
2661                                                 *c = '\0';
2662
2663                                 } else {
2664                                         response=c;
2665                                         if((c = strchr(c,',')))
2666                                                 *c = '\0';
2667                                 }
2668
2669                         } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2670                                 c+= strlen("uri=");
2671                                 if ((*c == '\"')) {
2672                                         resp_uri=++c;
2673                                         if((c = strchr(c,'\"')))
2674                                                 *c = '\0';
2675                                 } else {
2676                                         resp_uri=c;
2677                                         if((c = strchr(c,',')))
2678                                                 *c = '\0';
2679                                 }
2680
2681                         } else
2682                                 c = strchr(c, ',');
2683                         if (c)
2684                                 c++;
2685                 }
2686                 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2687                 if(strlen(resp_uri))
2688                         snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2689                 else
2690                         snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2691                 md5_hash(a1_hash, a1);
2692                 md5_hash(a2_hash, a2);
2693                 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2694                 md5_hash(resp_hash, resp);
2695
2696                 /* resp_hash now has the expected response, compare the two */
2697
2698                 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2699                         /* Auth is OK */
2700                         res = 0;
2701                 }
2702                 /* Assume success ;-) */
2703                 /* Eliminate random data */
2704                 strcpy(randdata, "");
2705         }
2706         return res;
2707 }
2708
2709 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2710 {
2711         int res = -1;
2712         struct sip_peer *peer;
2713         char tmp[256] = "";
2714         char *name, *c;
2715         char *t;
2716         /* Terminate URI */
2717         t = uri;
2718         while(*t && (*t > 32) && (*t != ';'))
2719                 t++;
2720         *t = '\0';
2721         
2722         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2723         c = ditch_braces(tmp);
2724         if (!strncmp(c, "sip:", 4)) {
2725                 name = c + 4;
2726         } else {
2727                 name = c;
2728                 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
2729         }
2730         c = strchr(name, '@');
2731         if (c) 
2732                 *c = '\0';
2733         ast_pthread_mutex_lock(&peerl.lock);
2734         peer = peerl.peers;
2735         while(peer) {
2736                 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2737                         p->nat = peer->nat;
2738                         transmit_response(p, "100 Trying", req);
2739                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri, 0))) {
2740                                 sip_cancel_destroy(p);
2741                                 if (parse_contact(p, peer, req)) {
2742                                         ast_log(LOG_WARNING, "Failed to parse contact info\n");
2743                                 } else {
2744                                         /* Say OK and ask subsystem to retransmit msg counter */
2745                                         transmit_response(p, "200 OK", req);
2746                                         peer->lastmsgssent = -1;
2747                                         res = 0;
2748                                 }
2749                         } 
2750                         break;
2751                 }       
2752                 peer = peer->next;
2753         }
2754         ast_pthread_mutex_unlock(&peerl.lock);
2755         if (res < 0)
2756                 transmit_response(p, "401 Unauthorized", &p->initreq);
2757         return res;
2758 }
2759
2760 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2761 {
2762         char tmp[256] = "", *c, *a;
2763         struct sip_request *req;
2764         
2765         req = oreq;
2766         if (!req)
2767                 req = &p->initreq;
2768         strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2769         c = ditch_braces(tmp);
2770         if (strncmp(c, "sip:", 4)) {
2771                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2772                 return -1;
2773         }
2774         c += 4;
2775         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2776                 *a = '\0';
2777         }
2778         if (sipdebug)
2779                 ast_verbose("Looking for %s in %s\n", c, p->context);
2780         if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2781                 if (!oreq)
2782                         strncpy(p->exten, c, sizeof(p->exten) - 1);
2783                 return 0;
2784         }
2785
2786         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2787                 return 1;
2788         }
2789         
2790         return -1;
2791 }
2792
2793 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2794 {
2795         char tmp[256] = "", *c, *a;
2796         char tmp2[256] = "", *c2, *a2;
2797         char tmp3[256];
2798         char tmp4[256];
2799         char tmp5[256] = "";            /* CallID to replace */
2800         struct sip_request *req;
2801         struct sip_pvt *p2;
2802         
2803         req = oreq;
2804         if (!req)
2805                 req = &p->initreq;
2806         strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2807         strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2808         strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2809         strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2810         
2811         c = ditch_braces(tmp);
2812         c2 = ditch_braces(tmp2);
2813         
2814                 
2815         if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2816                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2817                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c2);
2818                 return -1;
2819         }
2820         c += 4;
2821         c2 += 4;
2822         if ((a = strchr(c, '?'))) {
2823                 /* Search for arguemnts */
2824                 *a = '\0';
2825                 a++;
2826                 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
2827                         strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
2828                         if ((a = strchr(tmp5, '%'))) {
2829                                 /* Yuck!  Pingtel converts the '@' to a %40, icky icky!  Convert
2830                                    back to an '@' */
2831                                 if ((a[1] == '4') && (a[2] == '0')) {
2832                                         *a = '@';
2833                                         memmove(a + 1, a+3, strlen(a + 3));
2834                                 }
2835                         }
2836                         if ((a = strchr(tmp5, '%'))) 
2837                                 *a = '\0';
2838                 }
2839         }
2840         
2841         if ((a = strchr(c, '@')))
2842                 *a = '\0';
2843         if ((a = strchr(c, ';'))) 
2844                 *a = '\0';
2845         
2846
2847         if ((a2 = strchr(c2, '@')))
2848                 *a2 = '\0';
2849
2850         if ((a2 = strchr(c2, ';'))) 
2851                 *a2 = '\0';
2852         
2853         
2854         if (sipdebug) {
2855                 ast_verbose("Looking for %s in %s\n", c, p->context);
2856                 ast_verbose("Looking for %s in %s\n", c2, p->context);
2857         }
2858         if (strlen(tmp5)) {     
2859                 /* This is a supervised transfer */
2860                 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
2861                 
2862                 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
2863                 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
2864                 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
2865                 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
2866                 p->refer_call = NULL;
2867                 ast_pthread_mutex_lock(&iflock);
2868                 /* Search interfaces and find the match */
2869                 p2 = iflist;
2870                 while(p2) {
2871                         if (!strcmp(p2->callid, tmp5)) {
2872                                 /* Go ahead and lock it before returning */
2873                                 ast_pthread_mutex_lock(&p2->lock);
2874                                 p->refer_call = p2;
2875                                 break;
2876                         }
2877                         p2 = p2->next;
2878                 }
2879                 ast_pthread_mutex_unlock(&iflock);
2880                 if (p->refer_call)
2881                         return 0;
2882                 else
2883                         ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
2884         } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2885                 /* This is an unsupervised transfer */
2886                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
2887                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
2888                 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
2889                 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
2890                 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
2891                 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
2892                 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
2893                 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
2894                 p->refer_call = NULL;
2895                 return 0;
2896         } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2897                 return 1;
2898         }
2899
2900         return -1;
2901 }
2902
2903
2904 static int check_via(struct sip_pvt *p, struct sip_request *req)
2905 {
2906         char via[256] = "";
2907         char *c, *pt;
2908         struct hostent *hp;
2909
2910         memset(via, 0, sizeof(via));
2911         strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
2912         c = strchr(via, ';');
2913         if (c) 
2914                 *c = '\0';
2915         c = strchr(via, ' ');
2916         if (c) {
2917                 *c = '\0';
2918                 c++;
2919                 while(*c && (*c < 33))
2920                         c++;
2921                 if (strcmp(via, "SIP/2.0/UDP")) {
2922                         ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
2923                         return -1;
2924                 }
2925                 pt = strchr(c, ':');
2926                 if (pt) {
2927                         *pt = '\0';
2928                         pt++;
2929                 }
2930                 hp = gethostbyname(c);
2931                 if (!hp) {
2932                         ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
2933                         return -1;
2934                 }
2935                 memset(&p->sa, 0, sizeof(p->sa));
2936                 p->sa.sin_family = AF_INET;
2937                 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2938                 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
2939                 if (sipdebug) {
2940                         if (p->nat)
2941                                 ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2942                         else
2943                                 ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2944                 }
2945         }
2946         return 0;
2947 }
2948
2949 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri)
2950 {
2951         struct sip_user *user;
2952         struct sip_peer *peer;
2953         char *of, from[256] = "", *c;
2954         int res = 0;
2955         char *t;
2956         /* Terminate URI */
2957         t = uri;
2958         while(*t && (*t > 32) && (*t != ';'))
2959                 t++;
2960         *t = '\0';
2961         of = get_header(req, "From");
2962         strncpy(from, of, sizeof(from) - 1);
2963         of = ditch_braces(from);
2964         if (strncmp(of, "sip:", 4)) {
2965                 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2966         } else
2967                 of += 4;
2968         /* Get just the username part */
2969         if ((c = strchr(of, '@')))
2970                 *c = '\0';
2971         if ((c = strchr(of, ':')))
2972                 *c = '\0';
2973         strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2974         if (!strlen(of))
2975                         return 0;
2976         ast_pthread_mutex_lock(&userl.lock);
2977         user = userl.users;
2978         while(user) {
2979                 if (!strcasecmp(user->name, of)) {
2980                         p->nat = user->nat;
2981                         if (p->rtp) {
2982                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
2983                                 ast_rtp_setnat(p->rtp, p->nat);
2984                         }
2985                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri, 1))) {
2986                                 sip_cancel_destroy(p);
2987                                 strncpy(p->context, user->context, sizeof(p->context) - 1);
2988                                 if (strlen(user->callerid) && strlen(p->callerid)) 
2989                                         strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2990                                 strncpy(p->username, user->name, sizeof(p->username) - 1);
2991                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)  -1);
2992                                 p->canreinvite = user->canreinvite;
2993                                 p->amaflags = user->amaflags;
2994                                 if (user->dtmfmode) {
2995                                         p->dtmfmode = user->dtmfmode;
2996                                         if (p->dtmfmode & SIP_DTMF_RFC2833)
2997                                                 p->noncodeccapability |= AST_RTP_DTMF;
2998                                         else
2999                                                 p->noncodeccapability &= ~AST_RTP_DTMF;
3000                                 }
3001                         }
3002                         break;
3003                 }
3004                 user = user->next;
3005         }
3006         ast_pthread_mutex_unlock(&userl.lock);
3007         if (!user) {
3008         /* If we didn't find a user match, check for peers */
3009                 ast_pthread_mutex_lock(&peerl.lock);
3010                 peer = peerl.peers;
3011                 while(peer) {
3012                         if (!memcmp(&peer->addr, &p->recv, sizeof(peer->addr))) {
3013                                 /* Take the peer */
3014                                 p->nat = peer->nat;
3015                                 if (p->rtp) {
3016                                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
3017                                         ast_rtp_setnat(p->rtp, p->nat);
3018                                 }
3019                                 p->canreinvite = peer->canreinvite;
3020                                 strncpy(p->username, peer->name, sizeof(p->username) - 1);
3021                                 if (peer->dtmfmode) {
3022                                         p->dtmfmode = peer->dtmfmode;
3023                                         if (p->dtmfmode & SIP_DTMF_RFC2833)
3024                                                 p->noncodeccapability |= AST_RTP_DTMF;
3025                                         else
3026                                                 p->noncodeccapability &= ~AST_RTP_DTMF;
3027                                 }
3028                                 break;
3029                         }
3030                         peer = peer->next;
3031                 }
3032                 ast_pthread_mutex_unlock(&peerl.lock);
3033         }
3034         return res;
3035 }
3036
3037 static int get_msg_text(char *buf, int len, struct sip_request *req)
3038 {
3039         int x;
3040         strcpy(buf, "");
3041         for (x=0;x<req->lines;x++) {
3042                 strncat(buf, req->line[x], len - strlen(buf) - 5);
3043                 strcat(buf, "\n");
3044         }
3045         return 0;
3046 }
3047
3048 static void receive_message(struct sip_pvt *p, struct sip_request *req)
3049 {
3050         char buf[1024];
3051         struct ast_frame f;
3052         if (get_msg_text(buf, sizeof(buf), req)) {
3053                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
3054                 return;
3055         }
3056         if (p->owner) {
3057                 if (sipdebug)
3058                         ast_verbose("Message received: '%s'\n", buf);
3059                   memset(&f, 0, sizeof(f));
3060                   f.frametype = AST_FRAME_TEXT;
3061                   f.subclass = 0;
3062                   f.offset = 0;
3063                   f.data = buf;
3064                   f.datalen = strlen(buf);
3065                   ast_queue_frame(p->owner, &f, 0);
3066         }
3067 }
3068
3069 static int sip_show_users(int fd, int argc, char *argv[])
3070 {
3071 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
3072         struct sip_user *user;
3073         if (argc != 3) 
3074                 return RESULT_SHOWUSAGE;
3075         ast_pthread_mutex_lock(&userl.lock);
3076         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
3077         for(user=userl.users;user;user=user->next) {
3078                 ast_cli(fd, FORMAT, user->name, user->secret, user->methods, 
3079                                 user->context,
3080                                 user->ha ? "Yes" : "No");
3081         }
3082         ast_pthread_mutex_unlock(&userl.lock);
3083         return RESULT_SUCCESS;
3084 #undef FORMAT
3085 }
3086
3087 static int sip_show_peers(int fd, int argc, char *argv[])
3088 {
3089 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s %-10s\n"
3090 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-8d %-10s\n"
3091         struct sip_peer *peer;
3092         char name[256] = "";
3093         if (argc != 3)
3094                 return RESULT_SHOWUSAGE;
3095         ast_pthread_mutex_lock(&peerl.lock);
3096         ast_cli(fd, FORMAT2, "Name/username", "Host", "   ", "Mask", "Port", "Status");
3097         for (peer = peerl.peers;peer;peer = peer->next) {
3098                 char nm[20] = "";
3099                 char status[20];
3100                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
3101                 if (strlen(peer->username))
3102                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);