Make sure strncat is > 0
[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 ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
104
105 /* Protect the interface list (of sip_pvt's) */
106 static ast_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 ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
111
112 static ast_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         ast_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         ast_mutex_t lock;
323 } userl = { NULL, AST_MUTEX_INITIALIZER };
324
325 static struct ast_peer_list {
326         struct sip_peer *peers;
327         ast_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         ast_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_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_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_mutex_unlock(&pkt->owner->lock);
442                         sip_destroy(pkt->owner);
443                         pkt=NULL;
444                 }
445         }
446         if (pkt)
447                 ast_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_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_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_mutex_lock(&p->lock);
714         p->initid = -1;
715         if (p->owner) {
716                 if (!ast_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_mutex_unlock(&p->owner->lock);
720                 }
721         }
722         ast_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_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_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_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_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_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_mutex_unlock(&userl.lock);
928         return 0;
929 }
930
931 static void sip_destroy(struct sip_pvt *p)
932 {
933         ast_mutex_lock(&iflock);
934         __sip_destroy(p, 1);
935         ast_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_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_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_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_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_mutex_unlock(&p->lock);
1047                 }
1048         } else if (frame->frametype == AST_FRAME_VIDEO) {
1049                 if (p) {
1050                         ast_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_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_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_mutex_unlock(&p->lock);
1077                 return -1;
1078         }
1079         p->owner = newchan;
1080         ast_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_mutex_lock(&usecnt_lock);
1224                 usecnt++;
1225                 ast_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_mutex_lock(&p->lock);
1374         fr = sip_rtp_read(ast, p);
1375         ast_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_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_mutex_lock(&iflock);
1454         p->next = iflist;
1455         iflist = p;
1456         ast_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_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_mutex_lock(&p->lock);
1516                         ast_mutex_unlock(&iflock);
1517                         return p;
1518                 }
1519                 p = p->next;
1520         }
1521         ast_mutex_unlock(&iflock);
1522         p = sip_alloc(callid, sin, 1);
1523         if (p)
1524                 ast_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 (%s:%s)\n", var, value);
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 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
1927                                 /* SLD: FIXME: Nice try, but the received= should not have a port */
1928                                 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
1929                                 /* MAS: Yup, RFC says you can't do it.  No way to indicate PAT...
1930                                    good job fellas. */
1931                                 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1932                                         snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1933                                 else
1934 #endif                          
1935                                         snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1936                                 add_header(req, field, new);
1937                         } else {
1938                                 /* Add what we're responding to */
1939                                 add_header(req, field, tmp);
1940                         }
1941                         copied++;
1942                 } else
1943                         break;
1944         }
1945         if (!copied) {
1946                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1947                 return -1;
1948         }
1949         return 0;
1950 }
1951
1952 /* Add Route: header into request per learned route */
1953 static void add_route(struct sip_request *req, struct sip_route *route)
1954 {
1955         char r[256], *p;
1956         int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
1957
1958         if (!route) return;
1959
1960         p = r;
1961         while (route) {
1962                 n = strlen(route->hop);
1963                 if ((n+3)>rem) break;
1964                 if (p != r) {
1965                         *p++ = ',';
1966                         --rem;
1967                 }
1968                 *p++ = '<';
1969                 strcpy(p, route->hop);  p += n;
1970                 *p++ = '>';
1971                 rem -= (n+2);
1972                 route = route->next;
1973         }
1974         *p = '\0';
1975         add_header(req, "Route", r);
1976 }
1977
1978 static void set_destination(struct sip_pvt *p, char *uri)
1979 {
1980         char *h, *maddr, hostname[256];
1981         int port, hn;
1982         struct hostent *hp;
1983
1984         /* Parse uri to h (host) and port - uri is already just the part inside the <> */
1985         /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
1986
1987         if (sipdebug)
1988                 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
1989
1990         /* Find and parse hostname */
1991         h = strchr(uri, '@');
1992         if (h)
1993                 ++h;
1994         else {
1995                 h = uri;
1996                 if (strncmp(h, "sip:", 4) == 0)
1997                         h += 4;
1998                 else if (strncmp(h, "sips:", 5) == 0)
1999                         h += 5;
2000         }
2001         hn = strcspn(h, ":;>");
2002         if (hn>255) hn=255;
2003         strncpy(hostname, h, hn);  hostname[hn] = '\0';
2004         h+=hn;
2005
2006         /* Is "port" present? if not default to 5060 */
2007         if (*h == ':') {
2008                 /* Parse port */
2009                 ++h;
2010                 port = strtol(h, &h, 10);
2011         }
2012         else
2013                 port = 5060;
2014
2015         /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2016         maddr = strstr(h, "maddr=");
2017         if (maddr) {
2018                 maddr += 6;
2019                 hn = strspn(maddr, "0123456789.");
2020                 if (hn>255) hn=255;
2021                 strncpy(hostname, maddr, hn);  hostname[hn] = '\0';
2022         }
2023         
2024         hp = gethostbyname(hostname);
2025         if (hp == NULL)  {
2026                 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2027                 return;
2028         }
2029         p->sa.sin_family = AF_INET;
2030         memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2031         p->sa.sin_port = htons(port);
2032         if (sipdebug)
2033                 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2034 }
2035
2036 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2037 {
2038         /* Initialize a response */
2039         if (req->headers || req->len) {
2040                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2041                 return -1;
2042         }
2043         req->header[req->headers] = req->data + req->len;
2044         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2045         req->len += strlen(req->header[req->headers]);
2046         if (req->headers < SIP_MAX_HEADERS)
2047                 req->headers++;
2048         else
2049                 ast_log(LOG_WARNING, "Out of header space\n");
2050         return 0;
2051 }
2052
2053 static int init_req(struct sip_request *req, char *resp, char *recip)
2054 {
2055         /* Initialize a response */
2056         if (req->headers || req->len) {
2057                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2058                 return -1;
2059         }
2060         req->header[req->headers] = req->data + req->len;
2061         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2062         req->len += strlen(req->header[req->headers]);
2063         if (req->headers < SIP_MAX_HEADERS)
2064                 req->headers++;
2065         else
2066                 ast_log(LOG_WARNING, "Out of header space\n");
2067         return 0;
2068 }
2069
2070 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2071 {
2072         char newto[256] = "", *ot;
2073         memset(resp, 0, sizeof(*resp));
2074         init_resp(resp, msg, req);
2075         copy_via_headers(p, resp, req, "Via");
2076         if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2077         copy_header(resp, req, "From");
2078         ot = get_header(req, "To");
2079         if (!strstr(ot, "tag=")) {
2080                 /* Add the proper tag if we don't have it already.  If they have specified
2081                    their tag, use it.  Otherwise, use our own tag */
2082                 if (strlen(p->theirtag) && p->outgoing)
2083                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2084                 else if (p->tag && !p->outgoing)
2085                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2086                 else
2087                         strncpy(newto, ot, sizeof(newto) - 1);
2088                 ot = newto;
2089         }
2090         add_header(resp, "To", ot);
2091         copy_header(resp, req, "Call-ID");
2092         copy_header(resp, req, "CSeq");
2093         add_header(resp, "User-Agent", "Asterisk PBX");
2094         add_header(resp, "Allow", ALLOWED_METHODS);
2095         if (p->expiry) {
2096                 /* For registration responses, we also need expiry and
2097                    contact info */
2098                 char contact[256];
2099                 char tmp[256];
2100                 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2101                 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2102                 add_header(resp, "Expires", tmp);
2103                 add_header(resp, "Contact", contact);
2104         } else {
2105                 add_header(resp, "Contact", p->our_contact);
2106         }
2107         return 0;
2108 }
2109
2110 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
2111 {
2112         struct sip_request *orig = &p->initreq;
2113         char stripped[80] ="";
2114         char tmp[80];
2115         char newto[256];
2116         char *c, *n;
2117         char *ot, *of;
2118
2119         memset(req, 0, sizeof(struct sip_request));
2120         
2121         if (!seqno) {
2122                 p->ocseq++;
2123                 seqno = p->ocseq;
2124         }
2125
2126         if (p->outgoing)
2127                 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2128         else
2129                 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2130         
2131         c = strchr(stripped, '<');
2132         if (c) 
2133                 c++;
2134         else
2135                 c = stripped;
2136         n = strchr(c, '>');
2137         if (n)
2138                 *n = '\0';
2139         n = strchr(c, ';');
2140         if (n)
2141                 *n = '\0';
2142         
2143         init_req(req, msg, c);
2144
2145         snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2146
2147         add_header(req, "Via", p->via);
2148         if (p->route) {
2149                 set_destination(p, p->route->hop);
2150                 add_route(req, p->route->next);
2151         }
2152
2153         ot = get_header(orig, "To");
2154         of = get_header(orig, "From");
2155
2156         /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2157            as our original request, including tag (or presumably lack thereof) */
2158         if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2159                 /* Add the proper tag if we don't have it already.  If they have specified
2160                    their tag, use it.  Otherwise, use our own tag */
2161                 if (p->outgoing && strlen(p->theirtag))
2162                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2163                 else if (!p->outgoing)
2164                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2165                 else
2166                         snprintf(newto, sizeof(newto), "%s", ot);
2167                 ot = newto;
2168         }
2169
2170         if (p->outgoing) {
2171                 add_header(req, "From", of);
2172                 add_header(req, "To", ot);
2173         } else {
2174                 add_header(req, "From", ot);
2175                 add_header(req, "To", of);
2176         }
2177         add_header(req, "Contact", p->our_contact);
2178         copy_header(req, orig, "Call-ID");
2179         add_header(req, "CSeq", tmp);
2180
2181         add_header(req, "User-Agent", "Asterisk PBX");
2182         return 0;
2183 }
2184
2185 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2186 {
2187         struct sip_request resp;
2188         int seqno = 0;
2189         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2190                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2191                 return -1;
2192         }
2193         respprep(&resp, p, msg, req);
2194         add_header(&resp, "Content-Length", "0");
2195         add_blank_header(&resp);
2196         return send_response(p, &resp, reliable, seqno);
2197 }
2198
2199 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req) 
2200 {
2201         return __transmit_response(p, msg, req, 0);
2202 }
2203 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2204 {
2205         return __transmit_response(p, msg, req, 1);
2206 }
2207
2208 static void append_date(struct sip_request *req)
2209 {
2210         char tmpdat[256];
2211         struct tm tm;
2212         time_t t;
2213         time(&t);
2214         gmtime_r(&t, &tm);
2215         strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2216         add_header(req, "Date", tmpdat);
2217 }
2218
2219 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2220 {
2221         struct sip_request resp;
2222         respprep(&resp, p, msg, req);
2223         append_date(&resp);
2224         add_header(&resp, "Content-Length", "0");
2225         add_blank_header(&resp);
2226         return send_response(p, &resp, 0, 0);
2227 }
2228
2229 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2230 {
2231         struct sip_request resp;
2232         respprep(&resp, p, msg, req);
2233         add_header(&resp, "Accept", "application/sdp");
2234         add_header(&resp, "Content-Length", "0");
2235         add_blank_header(&resp);
2236         return send_response(p, &resp, 0, 0);
2237 }
2238
2239 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2240 {
2241         struct sip_request resp;
2242         char tmp[256];
2243         int seqno = 0;
2244         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2245                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2246                 return -1;
2247         }
2248         snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2249         respprep(&resp, p, msg, req);
2250         add_header(&resp, "Proxy-Authenticate", tmp);
2251         add_header(&resp, "Content-Length", "0");
2252         add_blank_header(&resp);
2253         return send_response(p, &resp, reliable, seqno);
2254 }
2255
2256 static int add_text(struct sip_request *req, char *text)
2257 {
2258         /* XXX Convert \n's to \r\n's XXX */
2259         int len = strlen(text);
2260         char clen[256];
2261         snprintf(clen, sizeof(clen), "%d", len);
2262         add_header(req, "Content-Type", "text/plain");
2263         add_header(req, "Content-Length", clen);
2264         add_line(req, text);
2265         return 0;
2266 }
2267
2268 static int add_digit(struct sip_request *req, char digit)
2269 {
2270         char tmp[256];
2271         int len;
2272         char clen[256];
2273         snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2274         len = strlen(tmp);
2275         snprintf(clen, sizeof(clen), "%d", len);
2276         add_header(req, "Content-Type", "application/dtmf-relay");
2277         add_header(req, "Content-Length", clen);
2278         add_line(req, tmp);
2279         return 0;
2280 }
2281
2282 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2283 {
2284         int len;
2285         int codec;
2286         int alreadysent = 0;
2287         char costr[80];
2288         struct sockaddr_in sin;
2289         struct sockaddr_in vsin;
2290         struct sip_codec_pref *cur;
2291         char v[256];
2292         char s[256];
2293         char o[256];
2294         char c[256];
2295         char t[256];
2296         char m[256];
2297         char m2[256];
2298         char a[1024] = "";
2299         char a2[1024] = "";
2300         int x;
2301         struct sockaddr_in dest;
2302         struct sockaddr_in vdest;
2303         /* XXX We break with the "recommendation" and send our IP, in order that our
2304                peer doesn't have to gethostbyname() us XXX */
2305         len = 0;
2306         if (!p->rtp) {
2307                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2308                 return -1;
2309         }
2310         ast_rtp_get_us(p->rtp, &sin);
2311         if (p->vrtp)
2312                 ast_rtp_get_us(p->vrtp, &vsin);
2313
2314         if (p->redirip.sin_addr.s_addr) {
2315                 dest.sin_port = p->redirip.sin_port;
2316                 dest.sin_addr = p->redirip.sin_addr;
2317         } else if (rtp) {
2318                 ast_rtp_get_peer(rtp, &dest);
2319         } else {
2320                 dest.sin_addr = p->ourip;
2321                 dest.sin_port = sin.sin_port;
2322         }
2323
2324         /* Determine video destination */
2325         if (p->vrtp) {
2326                 if (p->vredirip.sin_addr.s_addr) {
2327                         vdest.sin_port = p->vredirip.sin_port;
2328                         vdest.sin_addr = p->vredirip.sin_addr;
2329                 } else if (vrtp) {
2330                         ast_rtp_get_peer(vrtp, &vdest);
2331                 } else {
2332                         vdest.sin_addr = p->ourip;
2333                         vdest.sin_port = vsin.sin_port;
2334                 }
2335         }
2336         if (sipdebug)
2337                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
2338         if (sipdebug && p->vrtp)
2339                 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));     
2340         snprintf(v, sizeof(v), "v=0\r\n");
2341         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2342         snprintf(s, sizeof(s), "s=session\r\n");
2343         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2344         snprintf(t, sizeof(t), "t=0 0\r\n");
2345         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2346         snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2347         /* Start by sending our preferred codecs */
2348         cur = prefs;
2349         while(cur) {
2350                 if (p->capability & cur->codec) {
2351                         if (sipdebug)
2352                                 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2353                         codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2354                         if (codec > -1) {
2355                                 snprintf(costr, sizeof(costr), " %d", codec);
2356                                 if (cur->codec < AST_FORMAT_MAX_AUDIO) {
2357                                         strcat(m, costr);
2358                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2359                                         strcat(a, costr);
2360                                 } else {
2361                                         strcat(m2, costr);
2362                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2363                                         strcat(a2, costr);
2364                                 }
2365                         }
2366                 }
2367                 alreadysent |= cur->codec;
2368                 cur = cur->next;
2369         }
2370         /* Now send any other common codecs, and non-codec formats: */
2371         for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2372                 if ((p->capability & x) && !(alreadysent & x)) {
2373                         if (sipdebug)
2374                                 ast_verbose("Answering with capability %d\n", x);       
2375                         codec = ast_rtp_lookup_code(p->rtp, 1, x);
2376                         if (codec > -1) {
2377                                 snprintf(costr, sizeof(costr), " %d", codec);
2378                                 if (x < AST_FORMAT_MAX_AUDIO) {
2379                                         strcat(m, costr);
2380                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2381                                         strcat(a, costr);
2382                                 } else {
2383                                         strcat(m2, costr);
2384                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2385                                         strcat(a2, costr);
2386                                 }
2387                         }
2388                 }
2389         }
2390         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2391                 if (p->noncodeccapability & x) {
2392                         if (sipdebug)
2393                                 ast_verbose("Answering with non-codec capability %d\n", x);
2394                         codec = ast_rtp_lookup_code(p->rtp, 0, x);
2395                         if (codec > -1) {
2396                                 snprintf(costr, sizeof(costr), " %d", codec);
2397                                 strcat(m, costr);
2398                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2399                                 strcat(a, costr);
2400                                 if (x == AST_RTP_DTMF) {
2401                                   /* Indicate we support DTMF...  Not sure about 16, but MSN supports it so dang it, we will too... */
2402                                   snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2403                                            codec);
2404                                   strcat(a, costr);
2405                                 }
2406                         }
2407                 }
2408         }
2409         strcat(m, "\r\n");
2410         strcat(m2, "\r\n");
2411         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2412         if (p->vrtp)
2413                 len += strlen(m2) + strlen(a2);
2414         snprintf(costr, sizeof(costr), "%d", len);
2415         add_header(resp, "Content-Type", "application/sdp");
2416         add_header(resp, "Content-Length", costr);
2417         add_line(resp, v);
2418         add_line(resp, o);
2419         add_line(resp, s);
2420         add_line(resp, c);
2421         add_line(resp, t);
2422         add_line(resp, m);
2423         add_line(resp, a);
2424         if (p->vrtp) {
2425                 add_line(resp, m2);
2426                 add_line(resp, a2);
2427         }
2428         return 0;
2429 }
2430
2431 static void copy_request(struct sip_request *dst,struct sip_request *src)
2432 {
2433         long offset;
2434         int x;
2435         offset = ((void *)dst) - ((void *)src);
2436         /* First copy stuff */
2437         memcpy(dst, src, sizeof(*dst));
2438         /* Now fix pointer arithmetic */
2439         for (x=0;x<src->headers;x++)
2440                 dst->header[x] += offset;
2441         for (x=0;x<src->lines;x++)
2442                 dst->line[x] += offset;
2443 }
2444
2445 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2446 {
2447         struct sip_request resp;
2448         int seqno;
2449         if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2450                 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2451                 return -1;
2452         }
2453         respprep(&resp, p, msg, req);
2454         add_sdp(&resp, p, NULL, NULL);
2455         return send_response(p, &resp, retrans, seqno);
2456 }
2457
2458 static int determine_firstline_parts( struct sip_request *req ) {
2459
2460   char *e, *cmd;
2461   int len;
2462   
2463   cmd= req->header[0];
2464   while(*cmd && (*cmd < 33)) {
2465     cmd++;
2466   }
2467   if (!*cmd) {
2468     return -1;
2469   }
2470   e= cmd;
2471   while(*e && (*e > 32)) {
2472     e++;
2473   }
2474   /* Get the command */
2475   if (*e) {
2476     *e = '\0';
2477     e++;
2478   }
2479   req->rlPart1= cmd;
2480   while( *e && ( *e < 33 ) ) {
2481     e++; 
2482   }
2483   if( !*e ) {
2484     return -1;
2485   }
2486     
2487   if ( !strcasecmp(cmd, "SIP/2.0") ) {
2488     /* We have a response */
2489     req->rlPart2= e;
2490     len= strlen( req->rlPart2 );
2491     if( len < 2 ) { return -1; }
2492     e+= len - 1;
2493     while( *e && *e<33 ) {
2494       e--; 
2495     }
2496     *(++e)= '\0';
2497   } else {
2498     /* We have a request */
2499     if( *e == '<' ) { 
2500       e++;
2501       if( !*e ) { return -1; }  
2502     }
2503     req->rlPart2= e;
2504     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2505       return -1;
2506     }
2507     while( isspace( *(--e) ) ) {}
2508     if( *e == '>' ) {
2509       *e= '\0';
2510     } else {
2511       *(++e)= '\0';
2512     }
2513   }
2514   return 1;
2515 }
2516
2517 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2518 {
2519         struct sip_request req;
2520         if (p->canreinvite == REINVITE_UPDATE)
2521                 reqprep(&req, p, "UPDATE", 0);
2522         else
2523                 reqprep(&req, p, "INVITE", 0);
2524         add_header(&req, "Allow", ALLOWED_METHODS);
2525         add_sdp(&req, p, rtp, vrtp);
2526         /* Use this as the basis */
2527         copy_request(&p->initreq, &req);
2528         parse(&p->initreq);
2529         determine_firstline_parts(&p->initreq);
2530         p->lastinvite = p->ocseq;
2531         p->outgoing = 1;
2532         return send_request(p, &req, 1, p->ocseq);
2533 }
2534
2535 static void build_contact(struct sip_pvt *p)
2536 {
2537         /* Construct Contact: header */
2538         if (ourport != 5060)
2539                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
2540         else
2541                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
2542 }
2543
2544 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2545 {
2546         char invite[256];
2547         char from[256];
2548         char to[256];
2549         char tmp[80];
2550         char cid[256];
2551         char *l = callerid, *n=NULL;
2552         if (p->owner && p->owner->callerid) {
2553                 strcpy(cid, p->owner->callerid);
2554                 ast_callerid_parse(cid, &n, &l);
2555                 if (l) 
2556                         ast_shrink_phone_number(l);
2557                 if (!l || !ast_isphonenumber(l))
2558                                 l = callerid;
2559         }
2560         if (!n || !strlen(n))
2561                 n = l;
2562         /* Allow user to be overridden */
2563         if (strlen(p->fromuser))
2564                 l = p->fromuser;
2565
2566         if ((ourport != 5060) && !strlen(p->fromdomain))
2567                 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);
2568         else
2569                 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2570
2571         if (strlen(p->username)) {
2572                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2573                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2574                 } else {
2575                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2576                 }
2577         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2578                 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2579         } else {
2580                 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2581         }
2582         strncpy(p->uri, invite, sizeof(p->uri) - 1);
2583         /* If there is a VXML URL append it to the SIP URL */
2584         if (vxml_url)
2585         {
2586                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2587         }
2588         else
2589         {
2590                 snprintf(to, sizeof(to), "<%s>", invite );
2591         }
2592         memset(req, 0, sizeof(struct sip_request));
2593         init_req(req, cmd, invite);
2594         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2595
2596         add_header(req, "Via", p->via);
2597         /* SLD: FIXME?: do Route: here too?  I think not cos this is the first request.
2598          * OTOH, then we won't have anything in p->route anyway */
2599         add_header(req, "From", from);
2600         strncpy(p->exten, l, sizeof(p->exten) - 1);
2601         build_contact(p);
2602         add_header(req, "To", to);
2603         add_header(req, "Contact", p->our_contact);
2604         add_header(req, "Call-ID", p->callid);
2605         add_header(req, "CSeq", tmp);
2606         add_header(req, "User-Agent", "Asterisk PBX");
2607 }
2608
2609 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url, char *distinctive_ring)
2610 {
2611         struct sip_request req;
2612         initreqprep(&req, p, cmd, vxml_url);
2613         if (auth)
2614                 add_header(&req, "Proxy-Authorization", auth);
2615         
2616         if (distinctive_ring)
2617         {
2618                 add_header(&req, "Alert-info",distinctive_ring);
2619         }
2620         add_header(&req, "Allow", ALLOWED_METHODS);
2621         if (sdp) {
2622                 add_sdp(&req, p, NULL, NULL);
2623         } else {
2624                 add_header(&req, "Content-Length", "0");
2625                 add_blank_header(&req);
2626         }
2627
2628         if (!p->initreq.headers) {
2629                 /* Use this as the basis */
2630                 copy_request(&p->initreq, &req);
2631                 parse(&p->initreq);
2632                 determine_firstline_parts(&p->initreq);
2633         }
2634         p->lastinvite = p->ocseq;
2635         return send_request(p, &req, 1, p->ocseq);
2636 }
2637
2638 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2639 {
2640         char tmp[2000];
2641         char from[256], to[256];
2642         char *t, *c, *a;
2643         char *mfrom, *mto;
2644         struct sip_request req;
2645         char clen[20];
2646         
2647         strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2648
2649         c = ditch_braces(from);
2650         if (strncmp(c, "sip:", 4)) {
2651                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2652                 return -1;
2653         }
2654         if ((a = strchr(c, ';'))) {
2655                 *a = '\0';
2656         }
2657         mfrom = c;
2658                 
2659         reqprep(&req, p, "NOTIFY", 0);
2660
2661         if (p->subscribed == 1) {
2662             strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2663
2664             c = ditch_braces(to);
2665             if (strncmp(c, "sip:", 4)) {
2666                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2667                 return -1;
2668             }
2669             if ((a = strchr(c, ';'))) {
2670                 *a = '\0';
2671             }
2672             mto = c;
2673
2674             add_header(&req, "Content-Type", "application/xpidf+xml");
2675
2676             if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2677                 state = 2;
2678             else if (state==AST_EXTENSION_INUSE)
2679                 state = 1;
2680             else
2681                 state = 0;
2682             
2683             t = tmp;            
2684             sprintf(t, "<?xml version=\"1.0\"?>\n");
2685             t = tmp + strlen(tmp);
2686             sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2687             t = tmp + strlen(tmp);
2688             sprintf(t, "<presence>\n");
2689             t = tmp + strlen(tmp);
2690             sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2691             t = tmp + strlen(tmp);
2692             sprintf(t, "<atom id=\"%s\">\n", p->exten);
2693             t = tmp + strlen(tmp);
2694             sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2695             t = tmp + strlen(tmp);
2696             sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2697             t = tmp + strlen(tmp);
2698             sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2699             t = tmp + strlen(tmp);
2700             sprintf(t, "</address>\n</atom>\n</presence>\n");           
2701         } else {
2702             add_header(&req, "Event", "dialog");
2703             add_header(&req, "Content-Type", "application/dialog-info+xml");
2704         
2705             t = tmp;            
2706             sprintf(t, "<?xml version=\"1.0\"?>\n");
2707             t = tmp + strlen(tmp);
2708             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);
2709             t = tmp + strlen(tmp);
2710             sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2711             t = tmp + strlen(tmp);
2712             sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2713             t = tmp + strlen(tmp);
2714             sprintf(t, "</dialog>\n</dialog-info>\n");  
2715         }
2716
2717         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2718         add_header(&req, "Content-Length", clen);
2719         add_line(&req, tmp);
2720
2721         return send_request(p, &req, 1, p->ocseq);
2722 }
2723
2724 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2725 {
2726         struct sip_request req;
2727         char tmp[256];
2728         char tmp2[256];
2729         char clen[20];
2730         initreqprep(&req, p, "NOTIFY", NULL);
2731         add_header(&req, "Event", "message-summary");
2732         add_header(&req, "Content-Type", notifymime);
2733
2734         snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
2735         snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2736         snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2737         add_header(&req, "Content-Length", clen);
2738         add_line(&req, tmp);
2739         add_line(&req, tmp2);
2740
2741         if (!p->initreq.headers) {
2742                 /* Use this as the basis */
2743                 copy_request(&p->initreq, &req);
2744                 parse(&p->initreq);
2745                 determine_firstline_parts(&p->initreq);
2746         }
2747
2748         return send_request(p, &req, 1, p->ocseq);
2749 }
2750
2751 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2752
2753 static int sip_reregister(void *data) 
2754 {
2755         /* if we are here, we know that we need to reregister. */
2756         struct sip_registry *r=(struct sip_registry *)data;
2757         r->expire = -1;
2758         sip_do_register(r);
2759         return 0;
2760 }
2761
2762
2763 static int sip_do_register(struct sip_registry *r)
2764 {
2765         int res;
2766         ast_mutex_lock(&r->lock);
2767         res=transmit_register(r, "REGISTER", NULL);
2768         ast_mutex_unlock(&r->lock);
2769         return res;
2770 }
2771
2772 static int sip_reg_timeout(void *data)
2773 {
2774         /* if we are here, our registration timed out, so we'll just do it over */
2775         struct sip_registry *r=data;
2776         struct sip_pvt *p;
2777         int res;
2778         ast_mutex_lock(&r->lock);
2779         ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr)); 
2780         if (r->call) {
2781                 /* Unlink us, destroy old call.  Locking is not relevent here because all this happens
2782                    in the single SIP manager thread. */
2783                 p = r->call;
2784                 p->registry = NULL;
2785                 r->call = NULL;
2786                 p->needdestroy = 1;
2787         }
2788         r->regstate=REG_STATE_UNREGISTERED;
2789         r->timeout = -1;
2790         res=transmit_register(r, "REGISTER", NULL);
2791         ast_mutex_unlock(&r->lock);
2792         return 0;
2793 }
2794
2795 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2796 {
2797         struct sip_request req;
2798         char from[256];
2799         char to[256];
2800         char tmp[80];
2801         char via[80];
2802         char addr[80];
2803         struct sip_pvt *p;
2804         /* exit if we are already in process with this registrar ?*/
2805         if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
2806                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2807                 return 0;
2808         }
2809
2810         if (r->call) {
2811                 if (!auth) {
2812                         ast_log(LOG_WARNING, "Already have a call??\n");
2813                         return 0;
2814                 } else
2815                         p = r->call;
2816         } else {
2817                 if (!r->callid_valid) {
2818                         build_callid(r->callid, sizeof(r->callid), __ourip);
2819                         r->callid_valid = 1;
2820                 }
2821                 p=sip_alloc( r->callid, &r->addr, 0);
2822                 if (!p) {
2823                         ast_log(LOG_WARNING, "Unable to allocate registration call\n");
2824                         return 0;
2825                 }
2826                 p->outgoing = 1;
2827                 r->call=p;
2828                 p->registry=r;
2829                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2830                 if (strlen(r->authuser))
2831                         strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
2832                 else
2833                         strncpy(p->peername, r->username, sizeof(p->peername)-1);
2834                 strncpy(p->username, r->username, sizeof(p->username)-1);
2835                 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
2836                 /* Always bind to our IP if specified */
2837                 if (bindaddr.sin_addr.s_addr)
2838                         memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
2839                 build_contact(p);
2840         }
2841
2842         /* set up a timeout */
2843         if (auth==NULL)  {
2844                 if (r->timeout > -1) {
2845                         ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
2846                         ast_sched_del(sched, r->timeout);
2847                 }
2848                 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
2849                 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
2850         }
2851
2852         if (strchr(r->username, '@')) {
2853                 snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
2854                 snprintf(to, sizeof(to),     "<sip:%s>", r->username);
2855         } else {
2856                 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
2857                 snprintf(to, sizeof(to),     "<sip:%s@%s>", r->username, r->hostname);
2858         }
2859         
2860         snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
2861         strncpy(p->uri, addr, sizeof(p->uri) - 1);
2862
2863         memset(&req, 0, sizeof(req));
2864         init_req(&req, cmd, addr);
2865
2866         snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
2867         p->ocseq = r->ocseq;
2868
2869         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
2870         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2871         add_header(&req, "Via", via);
2872         add_header(&req, "From", from);
2873         add_header(&req, "To", to);
2874         add_header(&req, "Call-ID", p->callid);
2875         add_header(&req, "CSeq", tmp);
2876         add_header(&req, "User-Agent", "Asterisk PBX");
2877         if (auth) 
2878                 add_header(&req, "Authorization", auth);
2879
2880         snprintf(tmp, sizeof(tmp), "%d", default_expiry);
2881         add_header(&req, "Expires", tmp);
2882         add_header(&req, "Contact", p->our_contact);
2883         add_header(&req, "Event", "registration");
2884         add_header(&req, "Content-length", "0");
2885         add_blank_header(&req);
2886         copy_request(&p->initreq, &req);
2887         parse(&p->initreq);
2888         determine_firstline_parts(&p->initreq);
2889         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2890         return send_request(p, &req, 1, p->ocseq);
2891 }
2892
2893 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2894 {
2895         struct sip_request req;
2896         reqprep(&req, p, "MESSAGE", 0);
2897         add_text(&req, text);
2898         return send_request(p, &req, 1, p->ocseq);
2899 }
2900
2901 static int transmit_refer(struct sip_pvt *p, char *dest)
2902 {
2903         struct sip_request req;
2904         char from[256];
2905         char *of, *c;
2906         char referto[256];
2907         if (p->outgoing) 
2908                 of = get_header(&p->initreq, "To");
2909         else
2910                 of = get_header(&p->initreq, "From");
2911         strncpy(from, of, sizeof(from) - 1);
2912         of = ditch_braces(from);
2913         strncpy(p->from,of,sizeof(p->from) - 1);
2914         if (strncmp(of, "sip:", 4)) {
2915                 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2916         } else
2917                 of += 4;
2918         /* Get just the username part */
2919         if ((c = strchr(of, '@'))) {
2920                 *c = '\0';
2921                 c++;
2922         }
2923         if (c) {
2924                 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
2925         } else {
2926                 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
2927         }
2928
2929         reqprep(&req, p, "REFER", 0);
2930         add_header(&req, "Refer-To", referto);
2931         add_header(&req, "Referred-By", callerid);
2932         return send_request(p, &req, 1, p->ocseq);
2933 }
2934
2935 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2936 {
2937         struct sip_request req;
2938         reqprep(&req, p, "INFO", 0);
2939         add_digit(&req, digit);
2940         return send_request(p, &req, 1, p->ocseq);
2941 }
2942
2943 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
2944 {
2945         struct sip_request resp;
2946         reqprep(&resp, p, msg, seqno);
2947         add_header(&resp, "Content-Length", "0");
2948         add_blank_header(&resp);
2949         return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
2950 }
2951
2952 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
2953 {
2954         struct sip_request resp;
2955         reqprep(&resp, p, msg, seqno);
2956         if (*p->realm)
2957         {
2958                 char digest[256];
2959                 memset(digest,0,sizeof(digest));
2960                 build_reply_digest(p, msg, digest, sizeof(digest));
2961                 add_header(&resp, "Proxy-Authorization", digest);
2962         }
2963
2964         add_header(&resp, "Content-Length", "0");
2965         add_blank_header(&resp);
2966         return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);      
2967 }
2968
2969 static int expire_register(void *data)
2970 {
2971         struct sip_peer *p = data;
2972         memset(&p->addr, 0, sizeof(p->addr));
2973         p->expire = -1;
2974         ast_device_state_changed("SIP/%s", p->name);
2975         return 0;
2976 }
2977
2978 static int sip_poke_peer(struct sip_peer *peer);
2979
2980 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2981 {
2982         char contact[80]= ""; 
2983         char *expires = get_header(req, "Expires");
2984         int expiry = atoi(expires);
2985         char *c, *n, *pt;
2986         int port;
2987         struct hostent *hp;
2988         struct sockaddr_in oldsin;
2989         if (!strlen(expires)) {
2990                 expires = strstr(get_header(req, "Contact"), "expires=");
2991                 if (expires) {
2992                         if (sscanf(expires + 8, "%d;", &expiry) != 1)
2993                                 expiry = default_expiry;
2994                 } else {
2995                         /* Nothing has been specified */
2996                         expiry = default_expiry;
2997                 }
2998         }
2999         /* Look for brackets */
3000         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
3001         c = contact;
3002         
3003         if ((n=strchr(c, '<'))) {
3004                 c = n + 1;
3005                 n = strchr(c, '>');
3006                 /* Lose the part after the > */
3007                 if (n) 
3008                         *n = '\0';
3009         }
3010         if (!strcasecmp(c, "*") || !expiry) {
3011                 /* This means remove all registrations and return OK */
3012                 memset(&p->addr, 0, sizeof(p->addr));
3013                 if (p->expire > -1)
3014                         ast_sched_del(sched, p->expire);
3015                 p->expire = -1;
3016                 if (option_verbose > 2)
3017                         ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->username);
3018                 return 0;
3019         }
3020         /* Make sure it's a SIP URL */
3021         if (strncasecmp(c, "sip:", 4)) {
3022                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
3023         } else
3024                 c += 4;
3025         /* Ditch q */
3026         n = strchr(c, ';');
3027         if (n) 
3028                 *n = '\0';
3029         /* Grab host */
3030         n = strchr(c, '@');
3031         if (!n) {
3032                 n = c;
3033                 c = NULL;
3034         } else {
3035                 *n = '\0';
3036                 n++;
3037         }
3038         pt = strchr(n, ':');
3039         if (pt) {
3040                 *pt = '\0';
3041                 pt++;
3042                 port = atoi(pt);
3043         } else
3044                 port = DEFAULT_SIP_PORT;
3045         memcpy(&oldsin, &p->addr, sizeof(oldsin));
3046         if (!p->nat) {
3047                 /* XXX This could block for a long time XXX */
3048                 hp = gethostbyname(n);
3049                 if (!hp)  {
3050                         ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
3051                         return -1;
3052                 }
3053                 p->addr.sin_family = AF_INET;
3054                 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
3055                 p->addr.sin_port = htons(port);
3056         } else {
3057                 /* Don't trust the contact field.  Just use what they came to us
3058                    with */
3059                 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
3060         }
3061         if (c)
3062                 strncpy(p->username, c, sizeof(p->username) - 1);
3063         else
3064                 strcpy(p->username, "");
3065         if (p->expire > -1)
3066                 ast_sched_del(sched, p->expire);
3067         if ((expiry < 1) || (expiry > max_expiry))
3068                 expiry = max_expiry;
3069         p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, p);
3070         pvt->expiry = expiry;
3071         if (inaddrcmp(&p->addr, &oldsin)) {
3072                 sip_poke_peer(p);
3073                 if (option_verbose > 2)
3074                         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);
3075         }
3076         return 0;
3077 }
3078
3079 static void free_old_route(struct sip_route *route)
3080 {
3081         struct sip_route *next;
3082         while (route) {
3083                 next = route->next;
3084                 free(route);
3085                 route = next;
3086         }
3087 }
3088
3089 static void list_route(struct sip_route *route)
3090 {
3091         if (!route) {
3092                 ast_verbose("list_route: no route\n");
3093                 return;
3094         }
3095         while (route) {
3096                 ast_verbose("list_route: hop: <%s>\n", route->hop);
3097                 route = route->next;
3098         }
3099 }
3100
3101 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
3102 {
3103         struct sip_route *thishop, *head, *tail;
3104         int start = 0;
3105         int len;
3106         char *rr, *contact, *c;
3107
3108         if (p->route) {
3109                 free_old_route(p->route);
3110                 p->route = NULL;
3111         }
3112         /* We build up head, then assign it to p->route when we're done */
3113         head = NULL;  tail = head;
3114         /* 1st we pass through all the hops in any Record-Route headers */
3115         for (;;) {
3116                 /* Each Record-Route header */