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