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