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