ec18409aad3b1584faf0a03446b8289eceeb68a1
[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 transmit_refer(struct sip_pvt *p, char *dest);
371 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
372 static char *getsipuri(char *header);
373 static void free_old_route(struct sip_route *route);
374 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
375
376 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
377 {
378         int res;
379         if (p->nat)
380             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
381         else
382             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
383         if (res != len) {
384                 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));
385         }
386         return res;
387 }
388
389 static void sip_destroy(struct sip_pvt *p);
390
391 static int retrans_pkt(void *data)
392 {
393         struct sip_pkt *pkt=data;
394         int res = 0;
395         ast_pthread_mutex_lock(&pkt->owner->lock);
396         if (1 /* !p->owner->needdestroy */) {
397                 if (pkt->retrans < MAX_RETRANS) {
398                         pkt->retrans++;
399                         if (sipdebug) {
400                                 if (pkt->owner->nat)
401                                         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));
402                                 else
403                                         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));
404                         }
405                         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
406                         res = 1;
407                 } else {
408                         ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
409                         pkt->retransid = -1;
410                         if (pkt->owner->owner) {
411                                 /* XXX Potential deadlocK?? XXX */
412                                 ast_queue_hangup(pkt->owner->owner, 1);
413                         } else {
414                                 /* If no owner, destroy now */
415                                 ast_pthread_mutex_unlock(&pkt->owner->lock);
416                                 sip_destroy(pkt->owner);
417                                 pkt = NULL;
418                         }
419                 }
420         } else {
421                 /* Don't bother retransmitting.  It's about to be killed anyway */
422                 pkt->retransid = -1;
423                 if (pkt->owner->owner) {
424                         /* XXX Potential deadlocK?? XXX */
425                         ast_queue_hangup(pkt->owner->owner, 1);
426                 } else {
427                         /* If no owner, destroy now */
428                         ast_pthread_mutex_unlock(&pkt->owner->lock);
429                         sip_destroy(pkt->owner);
430                         pkt=NULL;
431                 }
432         }
433         if (pkt)
434                 ast_pthread_mutex_unlock(&pkt->owner->lock);
435         return res;
436 }
437
438 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
439 {
440         struct sip_pkt *pkt;
441         pkt = malloc(sizeof(struct sip_pkt) + len);
442         if (!pkt)
443                 return -1;
444         memset(pkt, 0, sizeof(struct sip_pkt));
445         memcpy(pkt->data, data, len);
446         pkt->packetlen = len;
447         pkt->next = p->packets;
448         pkt->owner = p;
449         pkt->seqno = seqno;
450         pkt->resp = resp;
451         /* Schedule retransmission */
452         pkt->retransid = ast_sched_add(sched, 1000, retrans_pkt, pkt);
453         pkt->next = p->packets;
454         p->packets = pkt;
455         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
456         if (!strncasecmp(pkt->data, "INVITE", 6)) {
457                 /* Note this is a pending invite */
458                 p->pendinginvite = seqno;
459         }
460         return 0;
461 }
462
463 static int __sip_autodestruct(void *data)
464 {
465         struct sip_pvt *p = data;
466         p->autokillid = -1;
467         ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
468         if (p->owner) {
469                 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
470                 ast_queue_hangup(p->owner, 0);
471         } else {
472                 sip_destroy(p);
473         }
474         return 0;
475 }
476
477 static int sip_scheddestroy(struct sip_pvt *p, int ms)
478 {
479         if (p->autokillid > -1)
480                 ast_sched_del(sched, p->autokillid);
481         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
482         return 0;
483 }
484
485 static int sip_cancel_destroy(struct sip_pvt *p)
486 {
487         if (p->autokillid > -1)
488                 ast_sched_del(sched, p->autokillid);
489         p->autokillid = -1;
490         return 0;
491 }
492
493 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
494 {
495         struct sip_pkt *cur, *prev = NULL;
496         int res = -1;
497         int resetinvite = 0;
498         cur = p->packets;
499         while(cur) {
500                 if ((cur->seqno == seqno) && (cur->resp == resp)) {
501                         if (!resp && (seqno == p->pendinginvite)) {
502                                 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
503                                 p->pendinginvite = 0;
504                                 resetinvite = 1;
505                         }
506                         /* this is our baby */
507                         if (prev)
508                                 prev->next = cur->next;
509                         else
510                                 p->packets = cur->next;
511                         if (cur->retransid > -1)
512                                 ast_sched_del(sched, cur->retransid);
513                         free(cur);
514                         res = 0;
515                         break;
516                 }
517                 prev = cur;
518                 cur = cur->next;
519         }
520         ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
521         return res;
522 }
523
524 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
525 {
526         int res;
527         if (sipdebug) {
528                 if (p->nat)
529                         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));
530                 else
531                         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));
532         }
533         if (reliable)
534                 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
535         else
536                 res = __sip_xmit(p, req->data, req->len);
537         if (res > 0)
538                 res = 0;
539         return res;
540 }
541
542 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
543 {
544         int res;
545         if (sipdebug) {
546                 if (p->nat)
547                         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));
548                 else
549                         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));
550         }
551         if (reliable)
552                 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
553         else
554                 res = __sip_xmit(p, req->data, req->len);
555         return res;
556 }
557
558 static char *ditch_braces(char *tmp)
559 {
560         char *c = tmp;
561         char *n;
562         c = tmp;
563         if ((n = strchr(tmp, '<')) ) {
564                 c = n + 1;
565                 while(*c && *c != '>') c++;
566                 if (*c != '>') {
567                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
568                 } else {
569                         *c = '\0';
570                 }
571                 return n+1;
572         }
573         return c;
574 }
575
576 static int sip_sendtext(struct ast_channel *ast, char *text)
577 {
578         struct sip_pvt *p = ast->pvt->pvt;
579         if (sipdebug) 
580                 ast_verbose("Sending text %s on %s\n", text, ast->name);
581         if (!p)
582                 return -1;
583         if (!text || !strlen(text))
584                 return 0;
585         if (sipdebug)
586                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
587         transmit_message_with_text(p, text);
588         return 0;       
589 }
590
591 static int create_addr(struct sip_pvt *r, char *peer)
592 {
593         struct hostent *hp;
594         struct sip_peer *p;
595         int found=0;
596         char *port;
597
598         r->sa.sin_family = AF_INET;
599         ast_pthread_mutex_lock(&peerl.lock);
600         p = peerl.peers;
601         while(p) {
602                 if (!strcasecmp(p->name, peer)) {
603                         found++;
604                         r->capability = p->capability;
605                         r->nat = p->nat;
606                         if (r->rtp) {
607                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
608                                 ast_rtp_setnat(r->rtp, r->nat);
609                         }
610                         strncpy(r->peername, p->username, sizeof(r->peername)-1);
611                         strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
612                         strncpy(r->username, p->username, sizeof(r->username)-1);
613                         strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
614                         if (!strlen(r->tohost)) {
615                                 if (p->addr.sin_addr.s_addr)
616                                         snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
617                                 else
618                                         snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
619                         }
620                         if (strlen(p->fromdomain))
621                                 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
622                         if (strlen(p->fromuser))
623                                 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
624                         r->insecure = p->insecure;
625                         r->canreinvite = p->canreinvite;
626                         r->maxtime = p->maxms;
627                         r->callgroup = p->callgroup;
628                         r->pickupgroup = p->pickupgroup;
629                         if (p->dtmfmode) {
630                                 r->dtmfmode = p->dtmfmode;
631                                 if (r->dtmfmode & SIP_DTMF_RFC2833)
632                                         r->noncodeccapability |= AST_RTP_DTMF;
633                                 else
634                                         r->noncodeccapability &= ~AST_RTP_DTMF;
635                         }
636                         strncpy(r->context, p->context,sizeof(r->context)-1);
637                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
638                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
639                                 if (p->addr.sin_addr.s_addr) {
640                                         r->sa.sin_addr = p->addr.sin_addr;
641                                         r->sa.sin_port = p->addr.sin_port;
642                                 } else {
643                                         r->sa.sin_addr = p->defaddr.sin_addr;
644                                         r->sa.sin_port = p->defaddr.sin_port;
645                                 }
646                                 memcpy(&r->recv, &r->sa, sizeof(r->recv));
647                                 break;
648                         }
649                 }
650                 p = p->next;
651         }
652         ast_pthread_mutex_unlock(&peerl.lock);
653         if (!p && !found) {
654                 if ((port=strchr(peer, ':'))) {
655                         *port='\0';
656                         port++;
657                 }
658                 hp = gethostbyname(peer);
659                 if (hp) {
660                         strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
661                         memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
662                         if (port) {
663                                 r->sa.sin_port = htons(atoi(port));
664                         } else {
665                                 r->sa.sin_port = htons(DEFAULT_SIP_PORT);
666                         }
667                         memcpy(&r->recv, &r->sa, sizeof(r->recv));
668                         return 0;
669                 } else {
670                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
671                         return -1;
672                 }
673         } else if (!p)
674                 return -1;
675         else
676                 return 0;
677 }
678
679 static int auto_congest(void *nothing)
680 {
681         struct sip_pvt *p = nothing;
682         ast_pthread_mutex_lock(&p->lock);
683         p->initid = -1;
684         if (p->owner) {
685                 if (!pthread_mutex_trylock(&p->owner->lock)) {
686                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
687                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
688                         ast_pthread_mutex_unlock(&p->owner->lock);
689                 }
690         }
691         ast_pthread_mutex_unlock(&p->lock);
692         return 0;
693 }
694
695 static void sip_prefs_free(void)
696 {
697         struct sip_codec_pref *cur, *next;
698         cur = prefs;
699         while(cur) {
700                 next = cur->next;
701                 free(cur);
702                 cur = next;
703         }
704         prefs = NULL;
705 }
706
707 static void sip_pref_remove(int format)
708 {
709         struct sip_codec_pref *cur, *prev=NULL;
710         cur = prefs;
711         while(cur) {
712                 if (cur->codec == format) {
713                         if (prev)
714                                 prev->next = cur->next;
715                         else
716                                 prefs = cur->next;
717                         free(cur);
718                         return;
719                 }
720                 prev = cur;
721                 cur = cur->next;
722         }
723 }
724
725 static int sip_pref_append(int format)
726 {
727         struct sip_codec_pref *cur, *tmp;
728         sip_pref_remove(format);
729         tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
730         if (!tmp)
731                 return -1;
732         memset(tmp, 0, sizeof(struct sip_codec_pref));
733         tmp->codec = format;
734         if (prefs) {
735                 cur = prefs;
736                 while(cur->next)
737                         cur = cur->next;
738                 cur->next = tmp;
739         } else
740                 prefs = tmp;
741         return 0;
742 }
743
744 static int sip_codec_choose(int formats)
745 {
746         struct sip_codec_pref *cur;
747         cur = prefs;
748         while(cur) {
749                 if (formats & cur->codec)
750                         return cur->codec;
751                 cur = cur->next;
752         }
753         return ast_best_codec(formats);
754 }
755
756 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
757 {
758         int res;
759         struct sip_pvt *p;
760         char *vxml_url = NULL;
761         struct varshead *headp;
762         struct ast_var_t *current;
763         
764         p = ast->pvt->pvt;
765         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
766                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
767                 return -1;
768         }
769
770         /* Check whether there is a VXML_URL variable */
771         headp=&ast->varshead;
772         AST_LIST_TRAVERSE(headp,current,entries) {
773                 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
774                 {
775                         vxml_url = ast_var_value(current);
776                         break;
777                 }
778         }
779         
780         res = 0;
781         p->outgoing = 1;
782         transmit_invite(p, "INVITE", 1, NULL, vxml_url);
783         if (p->maxtime) {
784                 /* Initialize auto-congest time */
785                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
786         }
787         return res;
788 }
789
790 static void __sip_destroy(struct sip_pvt *p, int lockowner)
791 {
792         struct sip_pvt *cur, *prev = NULL;
793         struct sip_pkt *cp;
794         if (sipdebug)
795                 ast_log(LOG_DEBUG, "Destorying call '%s'\n", p->callid);
796         if (p->stateid > -1)
797                 ast_extension_state_del(p->stateid, NULL);
798         if (p->initid > -1)
799                 ast_sched_del(sched, p->initid);
800         if (p->autokillid > -1)
801                 ast_sched_del(sched, p->autokillid);
802
803         if (p->rtp) {
804                 ast_rtp_destroy(p->rtp);
805         }
806         if (p->route) {
807                 free_old_route(p->route);
808                 p->route = NULL;
809         }
810         /* Unlink us from the owner if we have one */
811         if (p->owner) {
812                 if (lockowner)
813                         ast_pthread_mutex_lock(&p->owner->lock);
814                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
815                 p->owner->pvt->pvt = NULL;
816                 if (lockowner)
817                         ast_pthread_mutex_unlock(&p->owner->lock);
818         }
819         cur = iflist;
820         while(cur) {
821                 if (cur == p) {
822                         if (prev)
823                                 prev->next = cur->next;
824                         else
825                                 iflist = cur->next;
826                         break;
827                 }
828                 prev = cur;
829                 cur = cur->next;
830         }
831         if (!cur) {
832                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
833         } else {
834                 if (p->initid > -1)
835                         ast_sched_del(sched, p->initid);
836                 while((cp = p->packets)) {
837                         p->packets = p->packets->next;
838                         if (cp->retransid > -1)
839                                 ast_sched_del(sched, cp->retransid);
840                         free(cp);
841                 }
842                 free(p);
843         }
844 }
845 static void sip_destroy(struct sip_pvt *p)
846 {
847         ast_pthread_mutex_lock(&iflock);
848         __sip_destroy(p, 1);
849         ast_pthread_mutex_unlock(&iflock);
850 }
851
852 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
853
854
855 static int sip_hangup(struct ast_channel *ast)
856 {
857         struct sip_pvt *p = ast->pvt->pvt;
858         int needcancel = 0;
859         int needdestroy = 0;
860         if (option_debug)
861                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
862         if (!ast->pvt->pvt) {
863                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
864                 return 0;
865         }
866         ast_pthread_mutex_lock(&p->lock);
867         /* Determine how to disconnect */
868         if (p->owner != ast) {
869                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
870                 ast_pthread_mutex_unlock(&p->lock);
871                 return 0;
872         }
873         if (!ast || (ast->_state != AST_STATE_UP))
874                 needcancel = 1;
875         /* Disconnect */
876         p = ast->pvt->pvt;
877         if (p->vad) {
878             ast_dsp_free(p->vad);
879         }
880         p->owner = NULL;
881         ast->pvt->pvt = NULL;
882
883         needdestroy = 1;
884         /* Start the process if it's not already started */
885         if (!p->alreadygone && strlen(p->initreq.data)) {
886                 if (needcancel) {
887                         if (p->outgoing) {
888                                 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
889                                 /* Actually don't destroy us yet, wait for the 487 on our original 
890                                    INVITE, but do set an autodestruct just in case. */
891                                 needdestroy = 0;
892                                 sip_scheddestroy(p, 15000);
893                         } else
894                                 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
895                 } else {
896                         if (!p->pendinginvite) {
897                                 /* Send a hangup */
898                                 transmit_request_with_auth(p, "BYE", 0, 1);
899                         } else {
900                                 /* Note we will need a BYE when this all settles out
901                                    but we can't send one while we have "INVITE" outstanding. */
902                                 p->pendingbye = 1;
903                         }
904                 }
905         }
906         p->needdestroy = needdestroy;
907         ast_pthread_mutex_unlock(&p->lock);
908         return 0;
909 }
910
911 static int sip_answer(struct ast_channel *ast)
912 {
913         int res = 0,fmt;
914         char *codec;
915         struct sip_pvt *p = ast->pvt->pvt;
916
917         
918         if (ast->_state != AST_STATE_UP) {
919         
920         
921         
922                 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
923                 if (codec) {
924                         ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
925                         fmt=ast_getformatbyname(codec);
926                         if (fmt) {
927                                 p->capability=fmt;
928                         } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
929                 }
930
931                 ast_setstate(ast, AST_STATE_UP);
932                 if (option_debug)
933                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
934                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
935         }
936         return res;
937 }
938
939 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
940 {
941         struct sip_pvt *p = ast->pvt->pvt;
942         int res = 0;
943         if (frame->frametype != AST_FRAME_VOICE) {
944                 if (frame->frametype == AST_FRAME_IMAGE)
945                         return 0;
946                 else {
947                         ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
948                         return 0;
949                 }
950         } else {
951                 if (!(frame->subclass & ast->nativeformats)) {
952                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
953                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
954                         return -1;
955                 }
956         }
957         if (p) {
958                 ast_pthread_mutex_lock(&p->lock);
959                 if (p->rtp) {
960                         if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
961                                 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
962                                 p->progress = 1;
963                         }
964                         res =  ast_rtp_write(p->rtp, frame);
965                 }
966                 ast_pthread_mutex_unlock(&p->lock);
967         }
968         return res;
969 }
970
971 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
972 {
973         struct sip_pvt *p = newchan->pvt->pvt;
974         ast_pthread_mutex_lock(&p->lock);
975         if (p->owner != oldchan) {
976                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
977                 ast_pthread_mutex_unlock(&p->lock);
978                 return -1;
979         }
980         p->owner = newchan;
981         ast_pthread_mutex_unlock(&p->lock);
982         return 0;
983 }
984
985 static int sip_senddigit(struct ast_channel *ast, char digit)
986 {
987         struct sip_pvt *p = ast->pvt->pvt;
988         if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
989                 transmit_info_with_digit(p, digit);
990         }
991         if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
992                 ast_rtp_senddigit(p->rtp, digit);
993         }
994         /* If in-band DTMF is desired, send that */
995         if (p->dtmfmode & SIP_DTMF_INBAND)
996                 return -1;
997         return 0;
998 }
999
1000 static int sip_transfer(struct ast_channel *ast, char *dest)
1001 {
1002         struct sip_pvt *p = ast->pvt->pvt;
1003         int res;
1004         res = transmit_refer(p, dest);
1005         return res;
1006 }
1007
1008 static int sip_indicate(struct ast_channel *ast, int condition)
1009 {
1010         struct sip_pvt *p = ast->pvt->pvt;
1011         switch(condition) {
1012         case AST_CONTROL_RINGING:
1013                 if (ast->_state == AST_STATE_RING) {
1014                         if (!p->progress) {
1015                                 transmit_response(p, "180 Ringing", &p->initreq);
1016                                 break;
1017                         } else {
1018                                 /* Oops, we've sent progress tones.  Let Asterisk do it instead */
1019                         }
1020                 }
1021                 return -1;
1022         case AST_CONTROL_BUSY:
1023                 if (ast->_state != AST_STATE_UP) {
1024                         transmit_response(p, "486 Busy Here", &p->initreq);
1025                         p->alreadygone = 1;
1026                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1027                         break;
1028                 }
1029                 return -1;
1030         case AST_CONTROL_CONGESTION:
1031                 if (ast->_state != AST_STATE_UP) {
1032                         transmit_response(p, "503 Service Unavailable", &p->initreq);
1033                         p->alreadygone = 1;
1034                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1035                         break;
1036                 }
1037                 return -1;
1038         case AST_CONTROL_PROGRESS:
1039                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1040                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1041                         p->progress = 1;
1042                         break;
1043                 }
1044                 return -1;
1045         case -1:
1046                 return -1;
1047         default:
1048                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1049                 return -1;
1050         }
1051         return 0;
1052 }
1053
1054
1055
1056 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1057 {
1058         struct ast_channel *tmp;
1059         int fmt;
1060         tmp = ast_channel_alloc(1);
1061         if (tmp) {
1062                 /* Select our native format based on codec preference until we receive
1063                    something from another device to the contrary. */
1064                 if (i->capability)
1065                         tmp->nativeformats = sip_codec_choose(i->capability);
1066                 else 
1067                         tmp->nativeformats = sip_codec_choose(capability);
1068                 fmt = ast_best_codec(tmp->nativeformats);
1069                 if (title)
1070                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1071                 else
1072                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
1073                 tmp->type = type;
1074                 if (i->dtmfmode & SIP_DTMF_INBAND) {
1075                     i->vad = ast_dsp_new();
1076                     ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1077                 }
1078                 tmp->fds[0] = ast_rtp_fd(i->rtp);
1079                 ast_setstate(tmp, state);
1080                 if (state == AST_STATE_RING)
1081                         tmp->rings = 1;
1082                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1083                 tmp->writeformat = fmt;
1084                 tmp->pvt->rawwriteformat = fmt;
1085                 tmp->readformat = fmt;
1086                 tmp->pvt->rawreadformat = fmt;
1087                 tmp->pvt->pvt = i;
1088                 tmp->pvt->send_text = sip_sendtext;
1089                 tmp->pvt->call = sip_call;
1090                 tmp->pvt->hangup = sip_hangup;
1091                 tmp->pvt->answer = sip_answer;
1092                 tmp->pvt->read = sip_read;
1093                 tmp->pvt->write = sip_write;
1094                 tmp->pvt->indicate = sip_indicate;
1095                 tmp->pvt->transfer = sip_transfer;
1096                 tmp->pvt->fixup = sip_fixup;
1097                 tmp->pvt->send_digit = sip_senddigit;
1098                 tmp->pvt->bridge = ast_rtp_bridge;
1099                 tmp->callgroup = i->callgroup;
1100                 tmp->pickupgroup = i->pickupgroup;
1101                 if (strlen(i->accountcode))
1102                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1103                 if (i->amaflags)
1104                         tmp->amaflags = i->amaflags;
1105                 if (strlen(i->language))
1106                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1107                 i->owner = tmp;
1108                 ast_pthread_mutex_lock(&usecnt_lock);
1109                 usecnt++;
1110                 ast_pthread_mutex_unlock(&usecnt_lock);
1111                 ast_update_use_count();
1112                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1113                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1114                 if (strlen(i->callerid))
1115                         tmp->callerid = strdup(i->callerid);
1116                 if (strlen(i->rdnis))
1117                         tmp->rdnis = strdup(i->rdnis);
1118                 tmp->priority = 1;
1119                 if (state != AST_STATE_DOWN) {
1120                         if (ast_pbx_start(tmp)) {
1121                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1122                                 ast_hangup(tmp);
1123                                 tmp = NULL;
1124                         }
1125                 }
1126         } else
1127                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1128         return tmp;
1129 }
1130
1131 static struct cfalias {
1132         char *fullname;
1133         char *shortname;
1134 } aliases[] = {
1135         { "Content-Type", "c" },
1136         { "Content-Encoding", "e" },
1137         { "From", "f" },
1138         { "Call-ID", "i" },
1139         { "Contact", "m" },
1140         { "Content-Length", "l" },
1141         { "Subject", "s" },
1142         { "To", "t" },
1143         { "Via", "v" },
1144 };
1145
1146 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1147   if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1148     char* r = line + nameLen + 1;
1149     while (*r && (*r < 33)) ++r;
1150     return r;
1151   }
1152
1153   return "";
1154 }
1155
1156 static char *get_sdp(struct sip_request *req, char *name) {
1157   int x;
1158   int len = strlen(name);
1159   char *r;
1160
1161   for (x=0; x<req->lines; x++) {
1162     r = get_sdp_by_line(req->line[x], name, len);
1163     if (r[0] != '\0') return r;
1164   }
1165   return "";
1166 }
1167
1168 static void sdpLineNum_iterator_init(int* iterator) {
1169   *iterator = 0;
1170 }
1171
1172 static char* get_sdp_iterate(int* iterator,
1173                              struct sip_request *req, char *name) {
1174   int len = strlen(name);
1175   char *r;
1176   while (*iterator < req->lines) {
1177     r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1178     if (r[0] != '\0') return r;
1179   }
1180   return "";
1181 }
1182
1183 static char *__get_header(struct sip_request *req, char *name, int *start)
1184 {
1185         int x;
1186         int len = strlen(name);
1187         char *r;
1188         for (x=*start;x<req->headers;x++) {
1189                 if (!strncasecmp(req->header[x], name, len) && 
1190                                 (req->header[x][len] == ':')) {
1191                                         r = req->header[x] + len + 1;
1192                                         while(*r && (*r < 33))
1193                                                         r++;
1194                                         *start = x+1;
1195                                         return r;
1196                 }
1197         }
1198         /* Try aliases */
1199         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
1200                 if (!strcasecmp(aliases[x].fullname, name))
1201                         return __get_header(req, aliases[x].shortname, start);
1202
1203         /* Don't return NULL, so get_header is always a valid pointer */
1204         return "";
1205 }
1206
1207 static char *get_header(struct sip_request *req, char *name)
1208 {
1209         int start = 0;
1210         return __get_header(req, name, &start);
1211 }
1212
1213 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1214 {
1215         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
1216         struct ast_frame *f;
1217         static struct ast_frame null_frame = { AST_FRAME_NULL, };
1218         f = ast_rtp_read(p->rtp);
1219         /* Don't send RFC2833 if we're not supposed to */
1220         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1221                 return &null_frame;
1222         if (p->owner) {
1223                 /* We already hold the channel lock */
1224                 if (f->frametype == AST_FRAME_VOICE) {
1225                         if (f->subclass != p->owner->nativeformats) {
1226                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1227                                 p->owner->nativeformats = f->subclass;
1228                                 ast_set_read_format(p->owner, p->owner->readformat);
1229                                 ast_set_write_format(p->owner, p->owner->writeformat);
1230                         }
1231             if (p->dtmfmode & SIP_DTMF_INBAND) {
1232                    f = ast_dsp_process(p->owner,p->vad,f,0);
1233             }
1234                 }
1235         }
1236         return f;
1237 }
1238
1239 static struct ast_frame *sip_read(struct ast_channel *ast)
1240 {
1241         struct ast_frame *fr;
1242         struct sip_pvt *p = ast->pvt->pvt;
1243         ast_pthread_mutex_lock(&p->lock);
1244         fr = sip_rtp_read(p);
1245         ast_pthread_mutex_unlock(&p->lock);
1246         return fr;
1247 }
1248
1249 static void build_callid(char *callid, int len, struct in_addr ourip)
1250 {
1251         int res;
1252         int val;
1253         int x;
1254         for (x=0;x<4;x++) {
1255                 val = rand();
1256                 res = snprintf(callid, len, "%08x", val);
1257                 len -= res;
1258                 callid += res;
1259         }
1260         /* It's not important that we really use our right IP here... */
1261         snprintf(callid, len, "@%s", inet_ntoa(ourip));
1262 }
1263
1264 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1265 {
1266         struct sip_pvt *p;
1267
1268         p = malloc(sizeof(struct sip_pvt));
1269         if (!p)
1270                 return NULL;
1271         /* Keep track of stuff */
1272         memset(p, 0, sizeof(struct sip_pvt));
1273         p->initid = -1;
1274         p->autokillid = -1;
1275         p->stateid = -1;
1276         p->rtp = ast_rtp_new(NULL, NULL);
1277         p->branch = rand();     
1278         p->tag = rand();
1279         
1280         /* Start with 101 instead of 1 */
1281         p->ocseq = 101;
1282         if (!p->rtp) {
1283                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1284                 free(p);
1285                 return NULL;
1286         }
1287         ast_rtp_settos(p->rtp, tos);
1288         if (useglobalnat && sin) {
1289                 /* Setup NAT structure according to global settings if we have an address */
1290                 p->nat = globalnat;
1291                 memcpy(&p->recv, sin, sizeof(p->recv));
1292                 ast_rtp_setnat(p->rtp, p->nat);
1293         }
1294         ast_pthread_mutex_init(&p->lock);
1295 #if 0
1296         ast_rtp_set_data(p->rtp, p);
1297         ast_rtp_set_callback(p->rtp, rtpready);
1298 #endif  
1299         if (sin) {
1300                 memcpy(&p->sa, sin, sizeof(p->sa));
1301                 if (ast_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1302                         memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1303         } else {
1304                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1305         }
1306         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
1307         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1308         if (!callid)
1309                 build_callid(p->callid, sizeof(p->callid), p->ourip);
1310         else
1311                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1312         /* Assume reinvite OK and via INVITE */
1313         p->canreinvite = globalcanreinvite;
1314         p->dtmfmode = globaldtmfmode;
1315         if (p->dtmfmode & SIP_DTMF_RFC2833)
1316                 p->noncodeccapability |= AST_RTP_DTMF;
1317         strncpy(p->context, context, sizeof(p->context) - 1);
1318         strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1319         /* Add to list */
1320         ast_pthread_mutex_lock(&iflock);
1321         p->next = iflist;
1322         iflist = p;
1323         ast_pthread_mutex_unlock(&iflock);
1324         if (option_debug)
1325                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1326         return p;
1327 }
1328
1329 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1330 {
1331         struct sip_pvt *p;
1332         char *callid;
1333         callid = get_header(req, "Call-ID");
1334         if (!strlen(callid)) {
1335                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1336                 return NULL;
1337         }
1338         ast_pthread_mutex_lock(&iflock);
1339         p = iflist;
1340         while(p) {
1341                 if (!strcmp(p->callid, callid)) {
1342                         /* Found the call */
1343 #if 0
1344                         if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1345                             (p->sa.sin_port != sin->sin_port))) {
1346                                         char orig[80];
1347                                         char new[80];
1348                                         snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1349                                         snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1350                                         ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1351                                         ast_pthread_mutex_unlock(&iflock);
1352                                         return NULL;
1353                         }
1354 #endif
1355                         ast_pthread_mutex_lock(&p->lock);
1356                         ast_pthread_mutex_unlock(&iflock);
1357                         return p;
1358                 }
1359                 p = p->next;
1360         }
1361         ast_pthread_mutex_unlock(&iflock);
1362         return sip_alloc(callid, sin, 1);
1363 }
1364
1365 static int sip_register(char *value, int lineno)
1366 {
1367         struct sip_registry *reg;
1368         char copy[256] = "";
1369         char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1370         char *porta=NULL;
1371         char *contact=NULL;
1372         char *stringp=NULL;
1373         
1374         struct hostent *hp;
1375         if (!value)
1376                 return -1;
1377         strncpy(copy, value, sizeof(copy)-1);
1378         stringp=copy;
1379         username = stringp;
1380         hostname = strrchr(stringp, '@');
1381         if (hostname) {
1382                 *hostname = '\0';
1383                 hostname++;
1384         }
1385         if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1386                 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port] at line %d", lineno);
1387                 return -1;
1388         }
1389         stringp=username;
1390         username = strsep(&stringp, ":");
1391         if (username) {
1392                 secret = strsep(&stringp, ":");
1393                 if (secret) 
1394                         authuser = strsep(&stringp, ":");
1395         }
1396         stringp = hostname;
1397         hostname = strsep(&stringp, "/");
1398         if (hostname) 
1399                 contact = strsep(&stringp, "/");
1400         if (!contact || !strlen(contact))
1401                 contact = "s";
1402         stringp=hostname;
1403         hostname = strsep(&stringp, ":");
1404         porta = strsep(&stringp, ":");
1405         
1406         if (porta && !atoi(porta)) {
1407                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1408                 return -1;
1409         }
1410         hp = gethostbyname(hostname);
1411         if (!hp) {
1412                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1413                 return -1;
1414         }
1415         reg = malloc(sizeof(struct sip_registry));
1416         if (reg) {
1417                 memset(reg, 0, sizeof(struct sip_registry));
1418                 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1419                 if (username)
1420                         strncpy(reg->username, username, sizeof(reg->username)-1);
1421                 if (hostname)
1422                         strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1423                 if (authuser)
1424                         strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1425                 if (secret)
1426                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1427                 reg->expire = -1;
1428                 reg->timeout =  -1;
1429                 reg->refresh = default_expiry;
1430                 reg->addr.sin_family = AF_INET;
1431                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
1432                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1433                 reg->next = registrations;
1434                 reg->callid_valid = 0;
1435                 reg->ocseq = 101;
1436                 registrations = reg;
1437         } else {
1438                 ast_log(LOG_ERROR, "Out of memory\n");
1439                 return -1;
1440         }
1441         return 0;
1442 }
1443
1444 static void parse(struct sip_request *req)
1445 {
1446         /* Divide fields by NULL's */
1447         char *c;
1448         int f = 0;
1449         c = req->data;
1450
1451         /* First header starts immediately */
1452         req->header[f] = c;
1453         while(*c) {
1454                 if (*c == '\n') {
1455                         /* We've got a new header */
1456                         *c = 0;
1457
1458 #if 0
1459                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1460 #endif                  
1461                         if (!strlen(req->header[f])) {
1462                                 /* Line by itself means we're now in content */
1463                                 c++;
1464                                 break;
1465                         }
1466                         if (f >= SIP_MAX_HEADERS - 1) {
1467                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1468                         } else
1469                                 f++;
1470                         req->header[f] = c + 1;
1471                 } else if (*c == '\r') {
1472                         /* Ignore but eliminate \r's */
1473                         *c = 0;
1474                 }
1475                 c++;
1476         }
1477         /* Check for last header */
1478         if (strlen(req->header[f])) 
1479                 f++;
1480         req->headers = f;
1481         /* Now we process any mime content */
1482         f = 0;
1483         req->line[f] = c;
1484         while(*c) {
1485                 if (*c == '\n') {
1486                         /* We've got a new line */
1487                         *c = 0;
1488 #if 0
1489                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1490 #endif                  
1491                         if (f >= SIP_MAX_LINES - 1) {
1492                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1493                         } else
1494                                 f++;
1495                         req->line[f] = c + 1;
1496                 } else if (*c == '\r') {
1497                         /* Ignore and eliminate \r's */
1498                         *c = 0;
1499                 }
1500                 c++;
1501         }
1502         /* Check for last line */
1503         if (strlen(req->line[f])) 
1504                 f++;
1505         req->lines = f;
1506         if (sipdebug)
1507                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1508         if (*c) 
1509                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1510 }
1511
1512 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1513 {
1514         char *m;
1515         char *c;
1516         char *a;
1517         char host[258];
1518         int len = -1;
1519         int portno;
1520         int peercapability, peernoncodeccapability;
1521         struct sockaddr_in sin;
1522         char *codecs;
1523         struct hostent *hp;
1524         int codec;
1525         int iterator;
1526
1527         /* Get codec and RTP info from SDP */
1528         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1529                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1530                 return -1;
1531         }
1532         m = get_sdp(req, "m");
1533         c = get_sdp(req, "c");
1534         if (!strlen(m) || !strlen(c)) {
1535                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1536                 return -1;
1537         }
1538         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1539                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1540                 return -1;
1541         }
1542         /* XXX This could block for a long time, and block the main thread! XXX */
1543         hp = gethostbyname(host);
1544         if (!hp) {
1545                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1546                 return -1;
1547         }
1548         if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1549                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
1550                 return -1;
1551         }
1552         sin.sin_family = AF_INET;
1553         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1554         sin.sin_port = htons(portno);
1555         if (p->rtp)
1556                 ast_rtp_set_peer(p->rtp, &sin);
1557 #if 0
1558         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1559 #endif  
1560         // Scan through the RTP payload types specified in a "m=" line:
1561         ast_rtp_pt_clear(p->rtp);
1562         codecs = m + len;
1563         while(strlen(codecs)) {
1564                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1565                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1566                         return -1;
1567                 }
1568                 ast_rtp_set_m_type(p->rtp, codec);
1569                 codecs += len;
1570                 /* Skip over any whitespace */
1571                 while(*codecs && (*codecs < 33)) codecs++;
1572         }
1573
1574         // Next, scan through each "a=rtpmap:" line, noting each
1575         // specified RTP payload type (with corresponding MIME subtype):
1576         sdpLineNum_iterator_init(&iterator);
1577         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1578           char* mimeSubtype = strdup(a); // ensures we have enough space
1579           if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1580           // Note: should really look at the 'freq' and '#chans' params too
1581           ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1582           free(mimeSubtype);
1583         }
1584
1585         // Now gather all of the codecs that were asked for:
1586         ast_rtp_get_current_formats(p->rtp,
1587                                 &peercapability, &peernoncodeccapability);
1588         p->capability = capability & peercapability;
1589         p->noncodeccapability = noncodeccapability & peernoncodeccapability;
1590         if (sipdebug) {
1591                 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1592                             capability, peercapability, p->capability);
1593                 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1594                             noncodeccapability, peernoncodeccapability,
1595                             p->noncodeccapability);
1596         }
1597         if (!p->capability) {
1598                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1599                 return -1;
1600         }
1601         if (p->owner) {
1602                 if (!(p->owner->nativeformats & p->capability)) {
1603                         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);
1604                         p->owner->nativeformats = sip_codec_choose(p->capability);
1605                         ast_set_read_format(p->owner, p->owner->readformat);
1606                         ast_set_write_format(p->owner, p->owner->writeformat);
1607                 }
1608                 if (p->owner->bridge) {
1609                         /* Turn on/off music on hold if we are holding/unholding */
1610                         if (sin.sin_addr.s_addr) {
1611                                 ast_moh_stop(p->owner->bridge);
1612                         } else {
1613                                 ast_moh_start(p->owner->bridge, NULL);
1614                         }
1615                 }
1616         }
1617         return 0;
1618         
1619 }
1620
1621 static int add_header(struct sip_request *req, char *var, char *value)
1622 {
1623         if (req->len >= sizeof(req->data) - 4) {
1624                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1625                 return -1;
1626         }
1627         if (req->lines) {
1628                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1629                 return -1;
1630         }
1631         req->header[req->headers] = req->data + req->len;
1632         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1633         req->len += strlen(req->header[req->headers]);
1634         if (req->headers < SIP_MAX_HEADERS)
1635                 req->headers++;
1636         else {
1637                 ast_log(LOG_WARNING, "Out of header space\n");
1638                 return -1;
1639         }
1640         return 0;       
1641 }
1642
1643 static int add_blank_header(struct sip_request *req)
1644 {
1645         if (req->len >= sizeof(req->data) - 4) {
1646                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1647                 return -1;
1648         }
1649         if (req->lines) {
1650                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1651                 return -1;
1652         }
1653         req->header[req->headers] = req->data + req->len;
1654         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1655         req->len += strlen(req->header[req->headers]);
1656         if (req->headers < SIP_MAX_HEADERS)
1657                 req->headers++;
1658         else {
1659                 ast_log(LOG_WARNING, "Out of header space\n");
1660                 return -1;
1661         }
1662         return 0;       
1663 }
1664
1665 static int add_line(struct sip_request *req, char *line)
1666 {
1667         if (req->len >= sizeof(req->data) - 4) {
1668                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1669                 return -1;
1670         }
1671         if (!req->lines) {
1672                 /* Add extra empty return */
1673                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1674                 req->len += strlen(req->data + req->len);
1675         }
1676         req->line[req->lines] = req->data + req->len;
1677         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1678         req->len += strlen(req->line[req->lines]);
1679         if (req->lines < SIP_MAX_LINES)
1680                 req->lines++;
1681         else {
1682                 ast_log(LOG_WARNING, "Out of line space\n");
1683                 return -1;
1684         }
1685         return 0;       
1686 }
1687
1688 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1689 {
1690         char *tmp;
1691         tmp = get_header(orig, field);
1692         if (strlen(tmp)) {
1693                 /* Add what we're responding to */
1694                 return add_header(req, field, tmp);
1695         }
1696         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1697         return -1;
1698 }
1699
1700 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1701 {
1702         char *tmp;
1703         int start = 0;
1704         int copied = 0;
1705         for (;;) {
1706                 tmp = __get_header(orig, field, &start);
1707                 if (strlen(tmp)) {
1708                         /* Add what we're responding to */
1709                         add_header(req, field, tmp);
1710                         copied++;
1711                 } else
1712                         break;
1713         }
1714         return copied ? 0 : -1;
1715 }
1716
1717 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1718 {
1719         char *tmp;
1720         int start = 0;
1721         int copied = 0;
1722         char new[256];
1723         for (;;) {
1724                 tmp = __get_header(orig, field, &start);
1725                 if (strlen(tmp)) {
1726                         if (!copied && p->nat) {
1727                                 /* SLD: FIXME: Nice try, but the received= should not have a port */
1728                                 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
1729                                 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1730                                         snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1731                                 else
1732                                         snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1733                                 add_header(req, field, new);
1734                         } else {
1735                                 /* Add what we're responding to */
1736                                 add_header(req, field, tmp);
1737                         }
1738                         copied++;
1739                 } else
1740                         break;
1741         }
1742         if (!copied) {
1743                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1744                 return -1;
1745         }
1746         return 0;
1747 }
1748
1749 /* Add Route: header into request per learned route */
1750 static void add_route(struct sip_request *req, struct sip_route *route)
1751 {
1752         char r[256], *p;
1753         int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
1754
1755         if (!route) return;
1756
1757         p = r;
1758         while (route) {
1759                 n = strlen(route->hop);
1760                 if ((n+3)>rem) break;
1761                 if (p != r) {
1762                         *p++ = ',';
1763                         --rem;
1764                 }
1765                 *p++ = '<';
1766                 strcpy(p, route->hop);  p += n;
1767                 *p++ = '>';
1768                 rem -= (n+2);
1769                 route = route->next;
1770         }
1771         *p = '\0';
1772         add_header(req, "Route", r);
1773 }
1774
1775 static void set_destination(struct sip_pvt *p, char *uri)
1776 {
1777         char *h, *maddr, hostname[256];
1778         int port, hn;
1779         struct hostent *hp;
1780
1781         /* Parse uri to h (host) and port - uri is already just the part inside the <> */
1782         /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
1783
1784         if (sipdebug)
1785                 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
1786
1787         /* Find and parse hostname */
1788         h = strchr(uri, '@');
1789         if (h)
1790                 ++h;
1791         else {
1792                 h = uri;
1793                 if (strncmp(h, "sip:", 4) == 0)
1794                         h += 4;
1795                 else if (strncmp(h, "sips:", 5) == 0)
1796                         h += 5;
1797         }
1798         hn = strcspn(h, ":;>");
1799         if (hn>255) hn=255;
1800         strncpy(hostname, h, hn);  hostname[hn] = '\0';
1801         h+=hn;
1802
1803         /* Is "port" present? if not default to 5060 */
1804         if (*h == ':') {
1805                 /* Parse port */
1806                 ++h;
1807                 port = strtol(h, &h, 10);
1808         }
1809         else
1810                 port = 5060;
1811
1812         /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
1813         maddr = strstr(h, "maddr=");
1814         if (maddr) {
1815                 maddr += 6;
1816                 hn = strspn(maddr, "0123456789.");
1817                 if (hn>255) hn=255;
1818                 strncpy(hostname, maddr, hn);  hostname[hn] = '\0';
1819         }
1820         
1821         hp = gethostbyname(hostname);
1822         if (hp == NULL)  {
1823                 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
1824                 return;
1825         }
1826         p->sa.sin_family = AF_INET;
1827         memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
1828         p->sa.sin_port = htons(port);
1829         if (sipdebug)
1830                 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
1831 }
1832
1833 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
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, "SIP/2.0 %s\r\n", resp);
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 init_req(struct sip_request *req, char *resp, char *recip)
1851 {
1852         /* Initialize a response */
1853         if (req->headers || req->len) {
1854                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1855                 return -1;
1856         }
1857         req->header[req->headers] = req->data + req->len;
1858         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1859         req->len += strlen(req->header[req->headers]);
1860         if (req->headers < SIP_MAX_HEADERS)
1861                 req->headers++;
1862         else
1863                 ast_log(LOG_WARNING, "Out of header space\n");
1864         return 0;
1865 }
1866
1867 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1868 {
1869         char newto[256] = "", *ot;
1870         memset(resp, 0, sizeof(*resp));
1871         init_resp(resp, msg, req);
1872         copy_via_headers(p, resp, req, "Via");
1873         if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
1874         copy_header(resp, req, "From");
1875         ot = get_header(req, "To");
1876         if (!strstr(ot, "tag=")) {
1877                 /* Add the proper tag if we don't have it already.  If they have specified
1878                    their tag, use it.  Otherwise, use our own tag */
1879                 if (strlen(p->theirtag) && p->outgoing)
1880                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1881                 else if (p->tag && !p->outgoing)
1882                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
1883                 else
1884                         strncpy(newto, ot, sizeof(newto) - 1);
1885                 ot = newto;
1886         }
1887         add_header(resp, "To", ot);
1888         copy_header(resp, req, "Call-ID");
1889         copy_header(resp, req, "CSeq");
1890         add_header(resp, "User-Agent", "Asterisk PBX");
1891         if (p->expiry) {
1892                 /* For registration responses, we also need expiry and
1893                    contact info */
1894                 char contact[256];
1895                 char tmp[256];
1896                 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
1897                 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
1898                 add_header(resp, "Expires", tmp);
1899                 add_header(resp, "Contact", contact);
1900         } else {
1901                 add_header(resp, "Contact", p->our_contact);
1902         }
1903         return 0;
1904 }
1905
1906 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
1907 {
1908         struct sip_request *orig = &p->initreq;
1909         char stripped[80] ="";
1910         char tmp[80];
1911         char newto[256];
1912         char *c, *n;
1913         char *ot, *of;
1914
1915         memset(req, 0, sizeof(struct sip_request));
1916         
1917         if (!seqno) {
1918                 p->ocseq++;
1919                 seqno = p->ocseq;
1920         }
1921
1922         if (p->outgoing)
1923                 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1924         else
1925                 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1926         
1927         c = strchr(stripped, '<');
1928         if (c) 
1929                 c++;
1930         else
1931                 c = stripped;
1932         n = strchr(c, '>');
1933         if (n)
1934                 *n = '\0';
1935         n = strchr(c, ';');
1936         if (n)
1937                 *n = '\0';
1938         
1939         init_req(req, msg, c);
1940
1941         snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
1942
1943         add_header(req, "Via", p->via);
1944         if (p->route) {
1945                 set_destination(p, p->route->hop);
1946                 add_route(req, p->route->next);
1947         }
1948
1949         ot = get_header(orig, "To");
1950         of = get_header(orig, "From");
1951
1952         /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
1953            as our original request, including tag (or presumably lack thereof) */
1954         if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
1955                 /* Add the proper tag if we don't have it already.  If they have specified
1956                    their tag, use it.  Otherwise, use our own tag */
1957                 if (p->outgoing && strlen(p->theirtag))
1958                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1959                 else if (!p->outgoing)
1960                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
1961                 else
1962                         snprintf(newto, sizeof(newto), "%s", ot);
1963                 ot = newto;
1964         }
1965
1966         if (p->outgoing) {
1967                 add_header(req, "From", of);
1968                 add_header(req, "To", ot);
1969         } else {
1970                 add_header(req, "From", ot);
1971                 add_header(req, "To", of);
1972         }
1973         add_header(req, "Contact", p->our_contact);
1974         copy_header(req, orig, "Call-ID");
1975         add_header(req, "CSeq", tmp);
1976
1977         add_header(req, "User-Agent", "Asterisk PBX");
1978         return 0;
1979 }
1980
1981 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
1982 {
1983         struct sip_request resp;
1984         int seqno = 0;
1985         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
1986                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
1987                 return -1;
1988         }
1989         respprep(&resp, p, msg, req);
1990         add_header(&resp, "Content-Length", "0");
1991         add_blank_header(&resp);
1992         return send_response(p, &resp, reliable, seqno);
1993 }
1994
1995 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req) 
1996 {
1997         return __transmit_response(p, msg, req, 0);
1998 }
1999 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2000 {
2001         return __transmit_response(p, msg, req, 1);
2002 }
2003
2004 static void append_date(struct sip_request *req)
2005 {
2006         char tmpdat[256];
2007         struct tm tm;
2008         time_t t;
2009         time(&t);
2010         gmtime_r(&t, &tm);
2011         strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2012         add_header(req, "Date", tmpdat);
2013 }
2014
2015 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2016 {
2017         struct sip_request resp;
2018         respprep(&resp, p, msg, req);
2019         append_date(&resp);
2020         add_header(&resp, "Content-Length", "0");
2021         add_blank_header(&resp);
2022         return send_response(p, &resp, 0, 0);
2023 }
2024
2025 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2026 {
2027         struct sip_request resp;
2028         respprep(&resp, p, msg, req);
2029         add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
2030         add_header(&resp, "Accept", "application/sdp");
2031         add_header(&resp, "Content-Length", "0");
2032         add_blank_header(&resp);
2033         return send_response(p, &resp, 0, 0);
2034 }
2035
2036 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2037 {
2038         struct sip_request resp;
2039         char tmp[256];
2040         int seqno = 0;
2041         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2042                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2043                 return -1;
2044         }
2045         snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2046         respprep(&resp, p, msg, req);
2047         add_header(&resp, "Proxy-Authenticate", tmp);
2048         add_header(&resp, "Content-Length", "0");
2049         add_blank_header(&resp);
2050         return send_response(p, &resp, reliable, seqno);
2051 }
2052
2053 static int add_text(struct sip_request *req, char *text)
2054 {
2055         /* XXX Convert \n's to \r\n's XXX */
2056         int len = strlen(text);
2057         char clen[256];
2058         snprintf(clen, sizeof(clen), "%d", len);
2059         add_header(req, "Content-Type", "text/plain");
2060         add_header(req, "Content-Length", clen);
2061         add_line(req, text);
2062         return 0;
2063 }
2064
2065 static int add_digit(struct sip_request *req, char digit)
2066 {
2067         char tmp[256];
2068         int len;
2069         char clen[256];
2070         snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2071         len = strlen(tmp);
2072         snprintf(clen, sizeof(clen), "%d", len);
2073         add_header(req, "Content-Type", "application/dtmf-relay");
2074         add_header(req, "Content-Length", clen);
2075         add_line(req, tmp);
2076         return 0;
2077 }
2078
2079 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
2080 {
2081         int len;
2082         int codec;
2083         int alreadysent = 0;
2084         char costr[80];
2085         struct sockaddr_in sin;
2086         struct sip_codec_pref *cur;
2087         char v[256];
2088         char s[256];
2089         char o[256];
2090         char c[256];
2091         char t[256];
2092         char m[256];
2093         char a[1024] = "";
2094         int x;
2095         struct sockaddr_in dest;
2096         /* XXX We break with the "recommendation" and send our IP, in order that our
2097                peer doesn't have to gethostbyname() us XXX */
2098         len = 0;
2099         if (!p->rtp) {
2100                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2101                 return -1;
2102         }
2103         ast_rtp_get_us(p->rtp, &sin);
2104         if (p->redirip.sin_addr.s_addr) {
2105                 dest.sin_port = p->redirip.sin_port;
2106                 dest.sin_addr = p->redirip.sin_addr;
2107         } else if (rtp) {
2108                 ast_rtp_get_peer(rtp, &dest);
2109         } else {
2110                 dest.sin_addr = p->ourip;
2111                 dest.sin_port = sin.sin_port;
2112         }
2113         if (sipdebug)
2114                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
2115         snprintf(v, sizeof(v), "v=0\r\n");
2116         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2117         snprintf(s, sizeof(s), "s=session\r\n");
2118         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2119         snprintf(t, sizeof(t), "t=0 0\r\n");
2120         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2121         /* Start by sending our preferred codecs */
2122         cur = prefs;
2123         while(cur) {
2124                 if (p->capability & cur->codec) {
2125                         if (sipdebug)
2126                                 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2127                         codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2128                         if (codec > -1) {
2129                                 snprintf(costr, sizeof(costr), " %d", codec);
2130                                 strcat(m, costr);
2131                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2132                                 strcat(a, costr);
2133                         }
2134                 }
2135                 alreadysent |= cur->codec;
2136                 cur = cur->next;
2137         }
2138         /* Now send any other common codecs, and non-codec formats: */
2139         for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2140                 if ((p->capability & x) && !(alreadysent & x)) {
2141                         if (sipdebug)
2142                                 ast_verbose("Answering with capability %d\n", x);       
2143                         codec = ast_rtp_lookup_code(p->rtp, 1, x);
2144                         if (codec > -1) {
2145                         snprintf(costr, sizeof(costr), " %d", codec);
2146                                 strcat(m, costr);
2147                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2148                                 strcat(a, costr);
2149                         }
2150                 }
2151         }
2152         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2153                 if (p->noncodeccapability & x) {
2154                         if (sipdebug)
2155                                 ast_verbose("Answering with non-codec capability %d\n", x);
2156                         codec = ast_rtp_lookup_code(p->rtp, 0, x);
2157                         if (codec > -1) {
2158                                 snprintf(costr, sizeof(costr), " %d", codec);
2159                                 strcat(m, costr);
2160                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2161                                 strcat(a, costr);
2162                                 if (x == AST_RTP_DTMF) {
2163                                   /* Indicate we support DTMF...  Not sure about 16, but MSN supports it so dang it, we will too... */
2164                                   snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2165                                            codec);
2166                                   strcat(a, costr);
2167                                 }
2168                         }
2169                 }
2170         }
2171         strcat(m, "\r\n");
2172         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2173         snprintf(costr, sizeof(costr), "%d", len);
2174         add_header(resp, "Content-Type", "application/sdp");
2175         add_header(resp, "Content-Length", costr);
2176         add_line(resp, v);
2177         add_line(resp, o);
2178         add_line(resp, s);
2179         add_line(resp, c);
2180         add_line(resp, t);
2181         add_line(resp, m);
2182         add_line(resp, a);
2183         return 0;
2184 }
2185
2186 static void copy_request(struct sip_request *dst,struct sip_request *src)
2187 {
2188         long offset;
2189         int x;
2190         offset = ((void *)dst) - ((void *)src);
2191         /* First copy stuff */
2192         memcpy(dst, src, sizeof(*dst));
2193         /* Now fix pointer arithmetic */
2194         for (x=0;x<src->headers;x++)
2195                 dst->header[x] += offset;
2196         for (x=0;x<src->lines;x++)
2197                 dst->line[x] += offset;
2198 }
2199
2200 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2201 {
2202         struct sip_request resp;
2203         int seqno;
2204         if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2205                 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2206                 return -1;
2207         }
2208         respprep(&resp, p, msg, req);
2209         add_sdp(&resp, p, NULL);
2210         return send_response(p, &resp, retrans, seqno);
2211 }
2212
2213 static int determine_firstline_parts( struct sip_request *req ) {
2214
2215   char *e, *cmd;
2216   int len;
2217   
2218   cmd= req->header[0];
2219   while(*cmd && (*cmd < 33)) {
2220     cmd++;
2221   }
2222   if (!*cmd) {
2223     return -1;
2224   }
2225   e= cmd;
2226   while(*e && (*e > 32)) {
2227     e++;
2228   }
2229   /* Get the command */
2230   if (*e) {
2231     *e = '\0';
2232     e++;
2233   }
2234   req->rlPart1= cmd;
2235   while( *e && ( *e < 33 ) ) {
2236     e++; 
2237   }
2238   if( !*e ) {
2239     return -1;
2240   }
2241     
2242   if ( !strcasecmp(cmd, "SIP/2.0") ) {
2243     /* We have a response */
2244     req->rlPart2= e;
2245     len= strlen( req->rlPart2 );
2246     if( len < 2 ) { return -1; }
2247     e+= len - 1;
2248     while( *e && *e<33 ) {
2249       e--; 
2250     }
2251     *(++e)= '\0';
2252   } else {
2253     /* We have a request */
2254     if( *e == '<' ) { 
2255       e++;
2256       if( !*e ) { return -1; }  
2257     }
2258     req->rlPart2= e;
2259     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2260       return -1;
2261     }
2262     while( isspace( *(--e) ) ) {}
2263     if( *e == '>' ) {
2264       *e= '\0';
2265     } else {
2266       *(++e)= '\0';
2267     }
2268   }
2269   return 1;
2270 }
2271
2272 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
2273 {
2274         struct sip_request req;
2275         if (p->canreinvite == REINVITE_UPDATE)
2276                 reqprep(&req, p, "UPDATE", 0);
2277         else
2278                 reqprep(&req, p, "INVITE", 0);
2279         add_sdp(&req, p, rtp);
2280         /* Use this as the basis */
2281         copy_request(&p->initreq, &req);
2282         parse(&p->initreq);
2283         determine_firstline_parts(&p->initreq);
2284         p->lastinvite = p->ocseq;
2285         p->outgoing = 1;
2286         return send_request(p, &req, 1, p->ocseq);
2287 }
2288
2289 static void build_contact(struct sip_pvt *p)
2290 {
2291         /* Construct Contact: header */
2292         if (ourport != 5060)
2293                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
2294         else
2295                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
2296 }
2297
2298 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2299 {
2300         char invite[256];
2301         char from[256];
2302         char to[256];
2303         char tmp[80];
2304         char cid[256];
2305         char *l = callerid, *n=NULL;
2306         if (p->owner && p->owner->callerid) {
2307                 strcpy(cid, p->owner->callerid);
2308                 ast_callerid_parse(cid, &n, &l);
2309                 if (l) 
2310                         ast_shrink_phone_number(l);
2311                 if (!l || !ast_isphonenumber(l))
2312                                 l = callerid;
2313         }
2314         if (!n || !strlen(n))
2315                 n = l;
2316         /* Allow user to be overridden */
2317         if (strlen(p->fromuser))
2318                 l = p->fromuser;
2319
2320         if ((ourport != 5060) && !strlen(p->fromdomain))
2321                 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);
2322         else
2323                 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2324
2325         if (strlen(p->username)) {
2326                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2327                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2328                 } else {
2329                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2330                 }
2331         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2332                 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2333         } else {
2334                 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2335         }
2336         strncpy(p->uri, invite, sizeof(p->uri) - 1);
2337         /* If there is a VXML URL append it to the SIP URL */
2338         if (vxml_url)
2339         {
2340                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2341         }
2342         else
2343         {
2344                 snprintf(to, sizeof(to), "<%s>", invite );
2345         }
2346         memset(req, 0, sizeof(struct sip_request));
2347         init_req(req, cmd, invite);
2348         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2349
2350         add_header(req, "Via", p->via);
2351         /* SLD: FIXME?: do Route: here too?  I think not cos this is the first request.
2352          * OTOH, then we won't have anything in p->route anyway */
2353         add_header(req, "From", from);
2354         strncpy(p->exten, l, sizeof(p->exten) - 1);
2355         build_contact(p);
2356         add_header(req, "To", to);
2357         add_header(req, "Contact", p->our_contact);
2358         add_header(req, "Call-ID", p->callid);
2359         add_header(req, "CSeq", tmp);
2360         add_header(req, "User-Agent", "Asterisk PBX");
2361 }
2362
2363 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2364 {
2365         struct sip_request req;
2366         initreqprep(&req, p, cmd, vxml_url);
2367         if (auth)
2368                 add_header(&req, "Proxy-Authorization", auth);
2369         if (sdp) {
2370                 add_sdp(&req, p, NULL);
2371         } else {
2372                 add_header(&req, "Content-Length", "0");
2373                 add_blank_header(&req);
2374         }
2375         if (!p->initreq.headers) {
2376                 /* Use this as the basis */
2377                 copy_request(&p->initreq, &req);
2378                 parse(&p->initreq);
2379                 determine_firstline_parts(&p->initreq);
2380         }
2381         p->lastinvite = p->ocseq;
2382         return send_request(p, &req, 1, p->ocseq);
2383 }
2384
2385 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2386 {
2387         char tmp[2000];
2388         char from[256], to[256];
2389         char *t, *c, *a;
2390         char *mfrom, *mto;
2391         struct sip_request req;
2392         char clen[20];
2393         
2394         strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2395
2396         c = ditch_braces(from);
2397         if (strncmp(c, "sip:", 4)) {
2398                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2399                 return -1;
2400         }
2401         if ((a = strchr(c, ';'))) {
2402                 *a = '\0';
2403         }
2404         mfrom = c;
2405                 
2406         reqprep(&req, p, "NOTIFY", 0);
2407
2408         if (p->subscribed == 1) {
2409             strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2410
2411             c = ditch_braces(to);
2412             if (strncmp(c, "sip:", 4)) {
2413                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2414                 return -1;
2415             }
2416             if ((a = strchr(c, ';'))) {
2417                 *a = '\0';
2418             }
2419             mto = c;
2420
2421             add_header(&req, "Content-Type", "application/xpidf+xml");
2422
2423             if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2424                 state = 2;
2425             else if (state==AST_EXTENSION_INUSE)
2426                 state = 1;
2427             else
2428                 state = 0;
2429             
2430             t = tmp;            
2431             sprintf(t, "<?xml version=\"1.0\"?>\n");
2432             t = tmp + strlen(tmp);
2433             sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2434             t = tmp + strlen(tmp);
2435             sprintf(t, "<presence>\n");
2436             t = tmp + strlen(tmp);
2437             sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2438             t = tmp + strlen(tmp);
2439             sprintf(t, "<atom id=\"%s\">\n", p->exten);
2440             t = tmp + strlen(tmp);
2441             sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2442             t = tmp + strlen(tmp);
2443             sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2444             t = tmp + strlen(tmp);
2445             sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2446             t = tmp + strlen(tmp);
2447             sprintf(t, "</address>\n</atom>\n</presence>\n");           
2448         } else {
2449             add_header(&req, "Event", "dialog");
2450             add_header(&req, "Content-Type", "application/dialog-info+xml");
2451         
2452             t = tmp;            
2453             sprintf(t, "<?xml version=\"1.0\"?>\n");
2454             t = tmp + strlen(tmp);
2455             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);
2456             t = tmp + strlen(tmp);
2457             sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2458             t = tmp + strlen(tmp);
2459             sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2460             t = tmp + strlen(tmp);
2461             sprintf(t, "</dialog>\n</dialog-info>\n");  
2462         }
2463
2464         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2465         add_header(&req, "Content-Length", clen);
2466         add_line(&req, tmp);
2467
2468         return send_request(p, &req, 1, p->ocseq);
2469 }
2470
2471 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2472 {
2473         struct sip_request req;
2474         char tmp[256];
2475         char tmp2[256];
2476         char clen[20];
2477         initreqprep(&req, p, "NOTIFY", NULL);
2478         add_header(&req, "Event", "message-summary");
2479         add_header(&req, "Content-Type", notifymime);
2480
2481         snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
2482         snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2483         snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2484         add_header(&req, "Content-Length", clen);
2485         add_line(&req, tmp);
2486         add_line(&req, tmp2);
2487
2488         if (!p->initreq.headers) {
2489                 /* Use this as the basis */
2490                 copy_request(&p->initreq, &req);
2491                 parse(&p->initreq);
2492                 determine_firstline_parts(&p->initreq);
2493         }
2494
2495         return send_request(p, &req, 1, p->ocseq);
2496 }
2497
2498 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2499
2500 static int sip_reregister(void *data) 
2501 {
2502         /* if we are here, we know that we need to reregister. */
2503         struct sip_registry *r=(struct sip_registry *)data;
2504         r->expire = -1;
2505         sip_do_register(r);
2506         return 0;
2507 }
2508
2509
2510 static int sip_do_register(struct sip_registry *r)
2511 {
2512         int res;
2513         ast_pthread_mutex_lock(&r->lock);
2514         res=transmit_register(r, "REGISTER", NULL);
2515         ast_pthread_mutex_unlock(&r->lock);
2516         return res;
2517 }
2518
2519 static int sip_reg_timeout(void *data)
2520 {
2521         /* if we are here, our registration timed out, so we'll just do it over */
2522         struct sip_registry *r=data;
2523         struct sip_pvt *p;
2524         int res;
2525         ast_pthread_mutex_lock(&r->lock);
2526         ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr)); 
2527         if (r->call) {
2528                 /* Unlink us, destroy old call.  Locking is not relevent here because all this happens
2529                    in the single SIP manager thread. */
2530                 p = r->call;
2531                 p->registry = NULL;
2532                 r->call = NULL;
2533                 p->needdestroy = 1;
2534         }
2535         r->regstate=REG_STATE_UNREGISTERED;
2536         r->timeout = -1;
2537         res=transmit_register(r, "REGISTER", NULL);
2538         ast_pthread_mutex_unlock(&r->lock);
2539         return 0;
2540 }
2541
2542 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2543 {
2544         struct sip_request req;
2545         char from[256];
2546         char to[256];
2547         char tmp[80];
2548         char via[80];
2549         char addr[80];
2550         struct sip_pvt *p;
2551         /* exit if we are already in process with this registrar ?*/
2552         if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
2553                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2554                 return 0;
2555         }
2556
2557         if (r->call) {
2558                 if (!auth) {
2559                         ast_log(LOG_WARNING, "Already have a call??\n");
2560                         return 0;
2561                 } else
2562                         p = r->call;
2563         } else {
2564                 if (!r->callid_valid) {
2565                         build_callid(r->callid, sizeof(r->callid), __ourip);
2566                         r->callid_valid = 1;
2567                 }
2568                 p=sip_alloc( r->callid, &r->addr, 0);
2569                 if (!p) {
2570                         ast_log(LOG_WARNING, "Unable to allocate registration call\n");
2571                         return 0;
2572                 }
2573                 p->outgoing = 1;
2574                 r->call=p;
2575                 p->registry=r;
2576                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2577                 if (strlen(r->authuser))
2578                         strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
2579                 else
2580                         strncpy(p->peername, r->username, sizeof(p->peername)-1);
2581                 strncpy(p->username, r->username, sizeof(p->username)-1);
2582                 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
2583                 build_contact(p);
2584         }
2585
2586         /* set up a timeout */
2587         if (auth==NULL)  {
2588                 if (r->timeout > -1) {
2589                         ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
2590                         ast_sched_del(sched, r->timeout);
2591                 }
2592                 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
2593                 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
2594         }
2595
2596         snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
2597         snprintf(to, sizeof(to),     "<sip:%s@%s>", r->username, r->hostname);
2598         
2599         snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
2600         strncpy(p->uri, addr, sizeof(p->uri) - 1);
2601
2602         memset(&req, 0, sizeof(req));
2603         init_req(&req, cmd, addr);
2604
2605         snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
2606         p->ocseq = r->ocseq;
2607
2608         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
2609         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2610         add_header(&req, "Via", via);
2611         add_header(&req, "From", from);
2612         add_header(&req, "To", to);
2613         add_header(&req, "Call-ID", p->callid);
2614         add_header(&req, "CSeq", tmp);
2615         add_header(&req, "User-Agent", "Asterisk PBX");
2616         if (auth) 
2617                 add_header(&req, "Authorization", auth);
2618
2619         snprintf(tmp, sizeof(tmp), "%d", default_expiry);
2620         add_header(&req, "Expires", tmp);
2621         add_header(&req, "Contact", p->our_contact);
2622         add_header(&req, "Event", "registration");
2623         add_header(&req, "Content-length", "0");
2624         add_blank_header(&req);
2625         copy_request(&p->initreq, &req);
2626         parse(&p->initreq);
2627         determine_firstline_parts(&p->initreq);
2628         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2629         return send_request(p, &req, 1, p->ocseq);
2630 }
2631
2632 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2633 {
2634         struct sip_request req;
2635         reqprep(&req, p, "MESSAGE", 0);
2636         add_text(&req, text);
2637         return send_request(p, &req, 1, p->ocseq);
2638 }
2639
2640 static int transmit_refer(struct sip_pvt *p, char *dest)
2641 {
2642         struct sip_request req;
2643         char from[256];
2644         char *of, *c;
2645         char referto[256];
2646         if (p->outgoing) 
2647                 of = get_header(&p->initreq, "To");
2648         else
2649                 of = get_header(&p->initreq, "From");
2650         strncpy(from, of, sizeof(from) - 1);
2651         of = ditch_braces(from);
2652         if (strncmp(of, "sip:", 4)) {
2653                 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2654         } else
2655                 of += 4;
2656         /* Get just the username part */
2657         if ((c = strchr(of, '@'))) {
2658                 *c = '\0';
2659                 c++;
2660         }
2661         if (c) {
2662                 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
2663         } else {
2664                 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
2665         }
2666
2667         reqprep(&req, p, "REFER", 0);
2668         add_header(&req, "Refer-To", referto);
2669         add_header(&req, "Referred-By", callerid);
2670         return send_request(p, &req, 1, p->ocseq);
2671 }
2672
2673 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2674 {
2675         struct sip_request req;
2676         reqprep(&req, p, "INFO", 0);
2677         add_digit(&req, digit);
2678         return send_request(p, &req, 1, p->ocseq);
2679 }
2680
2681 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
2682 {
2683         struct sip_request resp;
2684         reqprep(&resp, p, msg, seqno);
2685         add_header(&resp, "Content-Length", "0");
2686         add_blank_header(&resp);
2687         return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
2688 }
2689
2690 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
2691 {
2692         struct sip_request resp;
2693         reqprep(&resp, p, msg, seqno);
2694         if (*p->realm)
2695         {
2696                 char digest[256];
2697                 memset(digest,0,sizeof(digest));
2698                 build_reply_digest(p, msg, digest, sizeof(digest));
2699                 add_header(&resp, "Proxy-Authorization", digest);
2700         }
2701
2702         add_header(&resp, "Content-Length", "0");
2703         add_blank_header(&resp);
2704         return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);      
2705 }
2706
2707 static int expire_register(void *data)
2708 {
2709         struct sip_peer *p = data;
2710         memset(&p->addr, 0, sizeof(p->addr));
2711         p->expire = -1;
2712         ast_device_state_changed("SIP/%s", p->name);
2713         return 0;
2714 }
2715
2716 static int sip_poke_peer(struct sip_peer *peer);
2717
2718 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2719 {
2720         char contact[80]= ""; 
2721         char *expires = get_header(req, "Expires");
2722         int expiry = atoi(expires);
2723         char *c, *n, *pt;
2724         int port;
2725         struct hostent *hp;
2726         struct sockaddr_in oldsin;
2727         if (!strlen(expires)) {
2728                 expires = strstr(get_header(req, "Contact"), "expires=");
2729                 if (expires) {
2730                         if (sscanf(expires + 8, "%d;", &expiry) != 1)
2731                                 expiry = default_expiry;
2732                 } else {
2733                         /* Nothing has been specified */
2734                         expiry = default_expiry;
2735                 }
2736         }
2737         /* Look for brackets */
2738         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2739         c = contact;
2740         
2741         if ((n=strchr(c, '<'))) {
2742                 c = n + 1;
2743                 n = strchr(c, '>');
2744                 /* Lose the part after the > */
2745                 if (n) 
2746                         *n = '\0';
2747         }
2748         if (!strcasecmp(c, "*") || !expiry) {
2749                 /* This means remove all registrations and return OK */
2750                 memset(&p->addr, 0, sizeof(p->addr));
2751                 if (p->expire > -1)
2752                         ast_sched_del(sched, p->expire);
2753                 p->expire = -1;
2754                 if (option_verbose > 2)
2755                         ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->username);
2756                 return 0;
2757         }
2758         /* Make sure it's a SIP URL */
2759         if (strncasecmp(c, "sip:", 4)) {
2760                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2761         } else
2762                 c += 4;
2763         /* Ditch q */
2764         n = strchr(c, ';');
2765         if (n) 
2766                 *n = '\0';
2767         /* Grab host */
2768         n = strchr(c, '@');
2769         if (!n) {
2770                 n = c;
2771                 c = NULL;
2772         } else {
2773                 *n = '\0';
2774                 n++;
2775         }
2776         pt = strchr(n, ':');
2777         if (pt) {
2778                 *pt = '\0';
2779                 pt++;
2780                 port = atoi(pt);
2781         } else
2782                 port = DEFAULT_SIP_PORT;
2783         memcpy(&oldsin, &p->addr, sizeof(oldsin));
2784         if (!p->nat) {
2785                 /* XXX This could block for a long time XXX */
2786                 hp = gethostbyname(n);
2787                 if (!hp)  {
2788                         ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2789                         return -1;
2790                 }
2791                 p->addr.sin_family = AF_INET;
2792                 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2793                 p->addr.sin_port = htons(port);
2794         } else {
2795                 /* Don't trust the contact field.  Just use what they came to us
2796                    with */
2797                 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2798         }
2799         if (c)
2800                 strncpy(p->username, c, sizeof(p->username) - 1);
2801         else
2802                 strcpy(p->username, "");
2803         if (p->expire > -1)
2804                 ast_sched_del(sched, p->expire);
2805         if ((expiry < 1) || (expiry > max_expiry))
2806                 expiry = max_expiry;
2807         p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, p);
2808         pvt->expiry = expiry;
2809         if (inaddrcmp(&p->addr, &oldsin)) {
2810                 sip_poke_peer(p);
2811                 if (option_verbose > 2)
2812                         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);
2813         }
2814         return 0;
2815 }
2816
2817 static void free_old_route(struct sip_route *route)
2818 {
2819         struct sip_route *next;
2820         while (route) {
2821                 next = route->next;
2822                 free(route);
2823                 route = next;
2824         }
2825 }
2826
2827 static void list_route(struct sip_route *route)
2828 {
2829         if (!route) {
2830                 ast_verbose("list_route: no route\n");
2831                 return;
2832         }
2833         while (route) {
2834                 ast_verbose("list_route: hop: <%s>\n", route->hop);
2835                 route = route->next;
2836         }
2837 }
2838
2839 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
2840 {
2841         struct sip_route *thishop, *head, *tail;
2842         int start = 0;
2843         int len;
2844         char *rr, *contact, *c;
2845
2846         if (p->route) {
2847                 free_old_route(p->route);
2848                 p->route = NULL;
2849         }
2850         /* We build up head, then assign it to p->route when we're done */
2851         head = NULL;  tail = head;
2852         /* 1st we pass through all the hops in any Record-Route headers */
2853         for (;;) {
2854                 /* Each Record-Route header */
2855                 rr = __get_header(req, "Record-Route", &start);
2856                 if (*rr == '\0') break;
2857                 for (;;) {
2858                         /* Each route entry */
2859                         /* Find < */
2860                         rr = strchr(rr, '<');
2861                         if (!rr) break; /* No more hops */
2862                         ++rr;
2863                         len = strcspn(rr, ">");
2864                         /* Make a struct route */
2865                         thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2866                         if (thishop) {
2867                                 strncpy(thishop->hop, rr, len);
2868                                 thishop->hop[len] = '\0';
2869                                 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
2870                                 /* Link in */
2871                                 if (backwards) {
2872                                         /* Link in at head so they end up in reverse order */
2873                                         thishop->next = head;
2874                                         head = thishop;
2875                                         /* If this was the first then it'll be the tail */
2876                                         if (!tail) tail = thishop;
2877                                 } else {
2878                                         thishop->next = NULL;
2879                                         /* Link in at the end */
2880                                         if (tail)
2881                                                 tail->next = thishop;
2882                                         else
2883                                                 head = thishop;
2884                                         tail = thishop;
2885                                 }
2886                         }
2887                         rr += len+1;
2888                 }
2889         }
2890         /* 2nd append the Contact: if there is one */
2891         /* Can be multiple Contact headers, comma separated values - we just take the first */
2892         contact = get_header(req, "Contact");
2893         if (strlen(contact)) {
2894                 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
2895                 /* Look for <: delimited address */
2896                 c = strchr(contact, '<');
2897                 if (c) {
2898                         /* Take to > */
2899                         ++c;
2900                         len = strcspn(c, ">");
2901                 } else {
2902                         /* No <> - just take the lot */
2903                         c = contact; len = strlen(contact);
2904                 }
2905                 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2906                 if (thishop) {
2907                         strncpy(thishop->hop, c, len);
2908                         thishop->hop[len] = '\0';
2909                         thishop->next = NULL;
2910                         /* Goes at the end */
2911                         if (tail)
2912                                 tail->next = thishop;
2913                         else
2914                                 head = thishop;
2915                 }
2916         }
2917         /* Store as new route */
2918         p->route = head;
2919
2920         /* For debugging dump what we ended up with */
2921         if (sipdebug)
2922                 list_route(p->route);
2923 }
2924
2925 static void md5_hash(char *output, char *input)
2926 {
2927                 struct MD5Context md5;
2928                 unsigned char digest[16];
2929                 char *ptr;
2930                 int x;
2931                 MD5Init(&md5);
2932                 MD5Update(&md5, input, strlen(input));
2933                 MD5Final(digest, &md5);
2934                 ptr = output;
2935                 for (x=0;x<16;x++)
2936                         ptr += sprintf(ptr, "%2.2x", digest[x]);
2937 }
2938
2939 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)
2940 {
2941         int res = -1;
2942         /* Always OK if no secret */
2943         if (!strlen(secret))
2944                 return 0;
2945         if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2946                 snprintf(randdata, randlen, "%08x", rand());
2947                 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
2948                 /* Schedule auto destroy in 15 seconds */
2949                 sip_scheddestroy(p, 15000);
2950                 res = 1;
2951         } else {
2952                 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2953                    an example in the spec of just what it is you're doing a hash on. */
2954                 char a1[256];
2955                 char a2[256];
2956                 char a1_hash[256];
2957                 char a2_hash[256];
2958                 char resp[256];
2959                 char resp_hash[256];
2960                 char tmp[256] = "";
2961                 char *c;
2962                 char *response ="";
2963                 char *resp_uri ="";
2964
2965                 /* Find their response among the mess that we'r sent for comparison */
2966                 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2967                 c = tmp;
2968
2969                 while(c) {
2970                         while (*c && (*c < 33)) c++;
2971                         if (!*c)
2972                                 break;
2973                         if (!strncasecmp(c, "response=", strlen("response="))) {
2974                                 c+= strlen("response=");
2975                                 if ((*c == '\"')) {
2976                                         response=++c;
2977                                         if((c = strchr(c,'\"')))
2978                                                 *c = '\0';
2979
2980                                 } else {
2981                                         response=c;
2982                                         if((c = strchr(c,',')))
2983                                                 *c = '\0';
2984                                 }
2985
2986                         } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2987                                 c+= strlen("uri=");
2988                                 if ((*c == '\"')) {
2989                                         resp_uri=++c;
2990                                         if((c = strchr(c,'\"')))
2991                                                 *c = '\0';
2992                                 } else {
2993                                         resp_uri=c;
2994                                         if((c = strchr(c,',')))
2995                                                 *c = '\0';
2996                                 }
2997
2998                         } else
2999                                 c = strchr(c, ',');
3000                         if (c)
3001                                 c++;
3002                 }
3003                 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
3004                 if(strlen(resp_uri))
3005                         snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
3006                 else
3007                         snprintf(a2, sizeof(a2), "%s:%s", method, uri);
3008                 md5_hash(a1_hash, a1);
3009                 md5_hash(a2_hash, a2);
3010                 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
3011                 md5_hash(resp_hash, resp);
3012
3013                 /* resp_hash now has the expected response, compare the two */
3014
3015                 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
3016                         /* Auth is OK */
3017                         res = 0;
3018                 }
3019                 /* Assume success ;-) */
3020                 /* Eliminate random data */
3021                 strcpy(randdata, "");
3022         }
3023         return res;
3024 }
3025
3026 static int cb_extensionstate(char *context, char* exten, int state, void *data)
3027 {
3028     struct sip_pvt *p = data;
3029     if (state == -1) {
3030         sip_scheddestroy(p, 15000);
3031         p->stateid = -1;
3032         return 0;
3033     }
3034     
3035     transmit_state_notify(p, state, 1);
3036     
3037     if (option_debug)
3038         ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %d for Notify User %s\n", exten, state, p->username);
3039     return 0;
3040 }
3041
3042 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
3043 {
3044         int res = -1;
3045         struct sip_peer *peer;
3046         char tmp[256] = "";
3047         char *name, *c;
3048         char *t;
3049         /* Terminate URI */
3050         t = uri;
3051         while(*t && (*t > 32) && (*t != ';'))
3052                 t++;
3053         *t = '\0';
3054         
3055         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
3056         c = ditch_braces(tmp);
3057         /* Ditch ;user=phone */
3058         name = strchr(c, ';');
3059         if (name)
3060                 *name = '\0';
3061
3062         if (!strncmp(c, "sip:", 4)) {
3063                 name = c + 4;
3064         } else {
3065                 name = c;
3066                 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
3067         }
3068         c = strchr(name, '@');
3069         if (c) 
3070                 *c = '\0';
3071         strncpy(p->exten, name, sizeof(p->exten) - 1);
3072         build_contact(p);
3073         ast_pthread_mutex_lock(&peerl.lock);
3074         peer = peerl.peers;
3075         while(peer) {
3076                 if (!strcasecmp(peer->name, name) && peer->dynamic) {
3077                         p->nat = peer->nat;
3078                         transmit_response(p, "100 Trying", req);
3079                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri, 0))) {
3080                                 sip_cancel_destroy(p);
3081                                 if (parse_contact(p, peer, req)) {
3082                                         ast_log(LOG_WARNING, "Failed to parse contact info\n");
3083                                 } else {
3084                                         /* Say OK and ask subsystem to retransmit msg counter */
3085                                         transmit_response_with_date(p, "200 OK", req);
3086                                         peer->lastmsgssent = -1;
3087                                         res = 0;
3088                                 }
3089                         } 
3090                         break;
3091                 }       
3092                 peer = peer->next;
3093         }
3094         ast_pthread_mutex_unlock(&peerl.lock);
3095         if (!res) {
3096             ast_device_state_changed("SIP/%s", peer->name);
3097         }
3098         if (res < 0)
3099                 transmit_response(p, "401 Unauthorized", &p->initreq);
3100         return res;
3101 }
3102
3103 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
3104 {
3105         char tmp[256] = "", *c, *a;
3106         struct sip_request *req;
3107         
3108         req = oreq;
3109         if (!req)
3110                 req = &p->initreq;
3111         strncpy(tmp, get_header(req, "Diversion"), sizeof(tmp) - 1);
3112         if (!strlen(tmp))
3113                 return 0;
3114         c = ditch_braces(tmp);
3115         if (strncmp(c, "sip:", 4)) {
3116                 ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", c);
3117                 return -1;
3118         }
3119         c += 4;
3120         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
3121                 *a = '\0';
3122         }
3123         if (sipdebug)
3124                 ast_verbose("RDNIS is %s\n", c);
3125         strncpy(p->rdnis, c, sizeof(p->rdnis) - 1);
3126
3127         return 0;
3128 }
3129 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
3130 {
3131         char tmp[256] = "", *c, *a;
3132         struct sip_request *req;
3133         
3134         req = oreq;
3135         if (!req)
3136                 req = &p->initreq;
3137         if (req->rlPart2)
3138                 strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
3139         c = ditch_braces(tmp);
3140         if (strncmp(c, "sip:", 4)) {
3141                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
3142                 return -1;
3143         }
3144         c += 4;
3145         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
3146                 *a = '\0';
3147         }
3148         if (sipdebug)
3149                 ast_verbose("Looking for %s in %s\n", c, p->context);
3150         if (ast_exists_extension(NULL, p->context, c, 1, NULL) ||
3151                 !strcmp(c, ast_pickup_ext())) {
3152                 if (!oreq)
3153                         strncpy(p->exten, c, sizeof(p->exten) - 1);
3154                 return 0;
3155         }
3156
3157         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL) ||
3158             !strncmp(c, ast_pickup_ext(),strlen(c))) {
3159                 return 1;
3160         }
3161         
3162         return -1;
3163 }
3164
3165 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
3166 {
3167         char tmp[256] = "", *c, *a;
3168         char tmp2[256] = "", *c2, *a2;
3169         char tmp3[256];
3170         char tmp4[256];
3171         char tmp5[256] = "";            /* CallID to replace */
3172         struct sip_request *req;
3173         struct sip_pvt *p2;
3174         
3175         req = oreq;
3176         if (!req)
3177                 req = &p->initreq;
3178         strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
3179         strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
3180         strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
3181         strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
3182         
3183         c = ditch_braces(tmp);
3184         c2 = ditch_braces(tmp2);
3185         
3186                 
3187         if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
3188                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
3189                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c2);
3190                 return -1;
3191         }
3192         c += 4;
3193         c2 += 4;
3194         if ((a = strchr(c, '?'))) {
3195                 /* Search for arguemnts */
3196                 *a = '\0';
3197                 a++;
3198                 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
3199                         strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
3200                         if ((a = strchr(tmp5, '%'))) {
3201                                 /* Yuck!  Pingtel converts the '@' to a %40, icky icky!  Convert
3202                                    back to an '@' */
3203                                 if ((a[1] == '4') && (a[2] == '0')) {
3204                                         *a = '@';
3205                                         memmove(a + 1, a+3, strlen(a + 3));
3206                                 }
3207                         }
3208                         if ((a = strchr(tmp5, '%'))) 
3209                                 *a = '\0';
3210                 }
3211         }
3212         
3213         if ((a = strchr(c, '@')))
3214                 *a = '\0';
3215         if ((a = strchr(c, ';'))) 
3216                 *a = '\0';
3217         
3218
3219         if ((a2 = strchr(c2, '@')))
3220                 *a2 = '\0';
3221
3222         if ((a2 = strchr(c2, ';'))) 
3223                 *a2 = '\0';
3224         
3225         
3226         if (sipdebug) {
3227                 ast_verbose("Looking for %s in %s\n", c, p->context);
3228                 ast_verbose("Looking for %s in %s\n", c2, p->context);
3229         }
3230         if (strlen(tmp5)) {     
3231                 /* This is a supervised transfer */
3232                 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
3233                 
3234                 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
3235                 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
3236                 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
3237                 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
3238                 p->refer_call = NULL;
3239                 ast_pthread_mutex_lock(&iflock);
3240                 /* Search interfaces and find the match */
3241                 p2 = iflist;
3242                 while(p2) {
3243                         if (!strcmp(p2->callid, tmp5)) {
3244                                 /* Go ahead and lock it before returning */
3245                                 ast_pthread_mutex_lock(&p2->lock);
3246                                 p->refer_call = p2;
3247                                 break;
3248                         }
3249                         p2 = p2->next;
3250                 }
3251                 ast_pthread_mutex_unlock(&iflock);
3252                 if (p->refer_call)
3253                         return 0;
3254                 else
3255                         ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
3256         } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
3257                 /* This is an unsupervised transfer */
3258                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
3259                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
3260                 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
3261                 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
3262                 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
3263                 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
3264                 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
3265                 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
3266                 p->refer_call = NULL;
3267                 return 0;
3268         } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
3269                 return 1;
3270         }
3271
3272         return -1;
3273 }
3274
3275
3276 static int check_via(struct sip_pvt *p, struct sip_request *req)
3277 {
3278         char via[256] = "";
3279         char *c, *pt;
3280         struct hostent *hp;
3281
3282         memset(via, 0, sizeof(via));
3283         strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
3284         c = strchr(via, ';');
3285         if (c) 
3286                 *c = '\0';
3287         c = strchr(via, ' ');
3288         if (c) {
3289                 *c = '\0';
3290                 c++;
3291                 while(*c && (*c < 33))
3292                         c++;
3293                 if (strcmp(via, "SIP/2.0/UDP")) {
3294                         ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
3295                         return -1;
3296                 }
3297                 pt = strchr(c, ':');
3298                 if (pt) {
3299                         *pt = '\0';
3300                         pt++;
3301                 }
3302                 hp = gethostbyname(c);
3303                 if (!hp) {
3304                         ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
3305                         return -1;
3306                 }
3307                 memset(&p->sa, 0, sizeof(p->sa));
3308                 p->sa.sin_family = AF_INET;
3309                 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
3310                 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
3311                 if (sipdebug) {
3312                         if (p->nat)
3313                                 ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
3314                         else
3315                                 ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
3316                 }
3317         }
3318         return 0;
3319 }
3320
3321 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri, int reliable)
3322 {
3323         struct sip_user *user;
3324         struct sip_peer *peer;
3325         char *of, from[256] = "", *c;
3326         int res = 0;
3327         char *t;
3328         /* Terminate URI */
3329         t = uri;
3330         while(*t && (*t > 32) && (*t != ';'))
3331                 t++;
3332         *t = '\0';
3333         of = get_header(req, "From");
3334         strncpy(from, of, sizeof(from) - 1);
3335         of = ditch_braces(from);
3336         if (strncmp(of, "sip:", 4)) {
3337                 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
3338         } else
3339                 of += 4;
3340         /* Get just the username part */
3341         if ((c = strchr(of, '@')))
3342                 *c = '\0';
3343         if ((c = strchr(of, ':')))
3344                 *c = '\0';
3345         strncpy(p->callerid, of, sizeof(p->callerid) - 1);
3346         if (!strlen(of))
3347                         return 0;
3348         ast_pthread_mutex_lock(&userl.lock);
3349         user = userl.users;
3350         while(user) {
3351                 if (!strcasecmp(user->name, of)) {
3352                         p->nat = user->nat;
3353                         if (p->rtp) {
3354                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
3355                                 ast_rtp_setnat(p->rtp, p->nat);
3356                         }
3357                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri, reliable))) {
3358                                 sip_cancel_destroy(p);
3359                                 if (strlen(user->context))
3360                                         strncpy(p->context, user->context, sizeof(p->context) - 1);
3361                                 if (strlen(user->callerid) && strlen(p->callerid)) 
3362                                         strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
3363                                 strncpy(p->username, user->name, sizeof(p->username) - 1);
3364                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)  -1);
3365                                 p->canreinvite = user->canreinvite;
3366                                 p->amaflags = user->amaflags;
3367                                 p->callgroup = user->callgroup;
3368                                 p->pickupgroup = user->pickupgroup;
3369                                 if (user->dtmfmode) {
3370                                         p->dtmfmode = user->dtmfmode;
3371                                         if (p->dtmfmode & SIP_DTMF_RFC2833)
3372                                                 p->noncodeccapability |= AST_RTP_DTMF;
3373                                         else
3374                                                 p->noncodeccapability &= ~AST_RTP_DTMF;
3375                                 }
3376                         }
3377                         break;
3378                 }
3379                 user = user->next;
3380         }
3381         ast_pthread_mutex_unlock(&userl.lock);
3382         if (!user) {
3383         /* If we didn't find a user match, check for peers */
3384                 ast_pthread_mutex_lock(&peerl.lock);
3385                 peer = peerl.peers;
3386                 while(peer) {
3387                         if (!inaddrcmp(&peer->addr, &p->recv) || 
3388                                 (peer->insecure && (peer->addr.sin_addr.s_addr == p->recv.sin_addr.s_addr))) {
3389                                 /* Take the peer */
3390                                 p->nat = peer->nat;
3391                                 if (p->rtp) {
3392                                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
3393                                         ast_rtp_setnat(p->rtp, p->nat);
3394                                 }
3395                                 p->canreinvite = peer->canreinvite;
3396                                 strncpy(p->username, peer->name, sizeof(p->username) - 1);
3397                                 if (strlen(peer->context))
3398                                         strncpy(p->context, peer->context, sizeof(p->context) - 1);
3399                                 p->callgroup = peer->callgroup;
3400                                 p->pickupgroup = peer->pickupgroup;
3401                                 if (peer->dtmfmode) {
3402                                         p->dtmfmode = peer->dtmfmode;
3403                                         if (p->dtmfmode & SIP_DTMF_RFC2833)
3404                                                 p->noncodeccapability |= AST_RTP_DTMF;
3405                                         else
3406                                                 p->noncodeccapability &= ~AST_RTP_DTMF;
3407                                 }
3408                                 break;
3409                         }
3410                         peer = peer->next;
3411                 }
3412                 ast_pthread_mutex_unlock(&peerl.lock);
3413         }
3414         return res;
3415 }
3416
3417 static int get_msg_text(char *buf, int len, struct sip_request *req)
3418 {
3419         int x;
3420         strcpy(buf, "");
3421         for (x=0;x<req->lines;x++) {
3422                 strncat(buf, req->line[x], len - strlen(buf) - 5);
3423                 strcat(buf, "\n");
3424         }
3425         return 0;
3426 }
3427
3428 static void receive_message(struct sip_pvt *p, struct sip_request *req)
3429 {
3430         char buf[1024];
3431         struct ast_frame f;
3432         if (get_msg_text(buf, sizeof(buf), req)) {
3433                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
3434                 return;
3435         }
3436         if (p->owner) {
3437                 if (sipdebug)
3438                         ast_verbose("Message received: '%s'\n", buf);
3439                   memset(&f, 0, sizeof(f));
3440                   f.frametype = AST_FRAME_TEXT;
3441                   f.subclass = 0;
3442                   f.offset = 0;
3443                   f.data = buf;
3444                   f.datalen = strlen(buf);
3445                   ast_queue_frame(p->owner, &f, 0);
3446         }
3447 }
3448
3449 static int sip_show_users(int fd, int argc, char *argv[])
3450 {
3451 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
3452         struct sip_user *user;
3453         if (argc != 3) 
3454                 return RESULT_SHOWUSAGE;
3455         ast_pthread_mutex_lock(&userl.lock);
3456         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
3457         for(user=userl.users;user;user=user->next) {
3458                 ast_cli(fd, FORMAT, user->name, user->secret, user->methods, 
3459                                 user->context,
3460                                 user->ha ? "Yes" : "No");
3461         }
3462         ast_pthread_mutex_unlock(&userl.lock);
3463         return RESULT_SUCCESS;
3464 #undef FORMAT
3465 }
3466
3467 static int sip_show_peers(int fd, int argc, char *argv[])
3468 {
3469 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s %-10s\n"
3470 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-8d %-10s\n"
3471         struct sip_peer *peer;
3472         char name[256] = "";
3473         if (argc != 3)
3474                 return RESULT_SHOWUSAGE;
3475         ast_pthread_mutex_lock(&peerl.lock);
3476         ast_cli(fd, FORMAT2, "Name/username", "Host", "   ", "Mask", "Port", "Status");
3477         for (peer = peerl.peers;peer;peer = peer->next) {
3478                 char nm[20] = "";
3479                 char status[20];
3480                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
3481                 if (strlen(peer->username))
3482                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
3483                 else
3484                         strncpy(name, peer->name, sizeof(name) - 1);
3485                 if (peer->maxms) {
3486                         if (peer->lastms < 0)
3487                                 strcpy(status, "UNREACHABLE");
3488                         else if (peer->lastms > peer->maxms) 
3489                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
3490                         else if (peer->lastms) 
3491                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
3492                         else 
3493                                 strcpy(status, "UNKNOWN");
3494                 } else 
3495                         strcpy(status, "Unmonitored");
3496                 ast_cli(fd, FORMAT, name, 
3497                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
3498                                         peer->dynamic ? "(D)" : "   ",
3499                                         nm,
3500                                         ntohs(peer->addr.sin_port), status);
3501         }
3502         ast_pthread_mutex_unlock(&peerl.lock);
3503         return RESULT_SUCCESS;
3504 #undef FORMAT
3505 #undef FORMAT2
3506 }
3507
3508 static char *regstate2str(int regstate)
3509 {
3510         switch(regstate) {
3511         case REG_STATE_UNREGISTERED:
3512                 return "Unregistered";
3513         case REG_STATE_REGSENT:
3514                 return "Request Sent";
3515         case REG_STATE_AUTHSENT:
3516                 return "Auth. Sent";
3517         case REG_STATE_REGISTERED:
3518                 return "Registered";
3519         case REG_STATE_REJECTED:
3520                 return "Rejected";
3521         case REG_STATE_TIMEOUT:
3522                 return "Timeout";
3523         case REG_STATE_NOAUTH:
3524                 return "No Authentication";
3525         default:
3526                 return "Unknown";
3527         }
3528 }
3529
3530 static int sip_show_registry(int fd, int argc, char *argv[])
3531 {
3532 #define FORMAT2 "%-20.20s  %-10.10s  %8.8s %-20.20s\n"
3533 #define FORMAT "%-20.20s  %-10.10s  %8d %-20.20s\n"
3534         struct sip_registry *reg;
3535         char host[80];
3536         if (argc != 3)
3537                 return RESULT_SHOWUSAGE;
3538         ast_pthread_mutex_lock(&peerl.lock);
3539         ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
3540         for (reg = registrations;reg;reg = reg->next) {
3541                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
3542                 ast_cli(fd, FORMAT, host,
3543                                         reg->username, reg->refresh, regstate2str(reg->regstate));
3544         }
3545         ast_pthread_mutex_unlock(&peerl.lock);
3546         return RESULT_SUCCESS;
3547 #undef FORMAT
3548 #undef FORMAT2
3549 }
3550
3551 static int sip_show_channels(int fd, int argc, char *argv[])
3552 {
3553 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
3554 #define FORMAT  "%-15.15s  %-10.10s  %-11.11s  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %d\n"
3555         struct sip_pvt *cur;
3556         int numchans = 0;
3557         if (argc != 3)
3558                 return RESULT_SHOWUSAGE;
3559         ast_pthread_mutex_lock(&iflock);
3560         cur = iflist;
3561         ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
3562         while (cur) {
3563                 if (!cur->subscribed) {
3564                         ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr), 
3565                                                 strlen(cur->username) ? cur->username : "(None)", 
3566