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