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