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