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