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