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