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