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