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