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