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