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