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