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