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