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