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