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