Merge regex for iax2 show peers (bug #3223)
[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) 2004, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
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_pvt.h>
22 #include <asterisk/config.h>
23 #include <asterisk/logger.h>
24 #include <asterisk/module.h>
25 #include <asterisk/pbx.h>
26 #include <asterisk/options.h>
27 #include <asterisk/lock.h>
28 #include <asterisk/sched.h>
29 #include <asterisk/io.h>
30 #include <asterisk/rtp.h>
31 #include <asterisk/acl.h>
32 #include <asterisk/manager.h>
33 #include <asterisk/callerid.h>
34 #include <asterisk/cli.h>
35 #include <asterisk/md5.h>
36 #include <asterisk/app.h>
37 #include <asterisk/musiconhold.h>
38 #include <asterisk/dsp.h>
39 #include <asterisk/features.h>
40 #include <asterisk/acl.h>
41 #include <asterisk/srv.h>
42 #include <asterisk/astdb.h>
43 #include <asterisk/causes.h>
44 #include <asterisk/utils.h>
45 #include <asterisk/file.h>
46 #include <asterisk/astobj.h>
47 #ifdef OSP_SUPPORT
48 #include <asterisk/astosp.h>
49 #endif
50 #include <sys/socket.h>
51 #include <sys/ioctl.h>
52 #include <net/if.h>
53 #include <errno.h>
54 #include <unistd.h>
55 #include <stdlib.h>
56 #include <fcntl.h>
57 #include <netdb.h>
58 #include <arpa/inet.h>
59 #include <signal.h>
60 #include <sys/signal.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/ip.h>
63
64 #ifndef DEFAULT_USERAGENT
65 #define DEFAULT_USERAGENT "Asterisk PBX"
66 #endif
67  
68 #define VIDEO_CODEC_MASK        0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
69 #ifndef IPTOS_MINCOST
70 #define IPTOS_MINCOST 0x02
71 #endif
72
73 /* #define VOCAL_DATA_HACK */
74
75 #define SIPDUMPER
76 #define DEFAULT_DEFAULT_EXPIRY  120
77 #define DEFAULT_MAX_EXPIRY      3600
78 #define DEFAULT_REGISTRATION_TIMEOUT    20
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 
84                                            EXPIRY_GUARD_SECS */
85 #define EXPIRY_GUARD_MIN        500     /* This is the minimum guard time applied. If 
86                                            GUARD_PCT turns out to be lower than this, it 
87                                            will use this time instead.
88                                            This is in milliseconds. */
89 #define EXPIRY_GUARD_PCT        0.20    /* Percentage of expires timeout to use when 
90                                            below EXPIRY_GUARD_LIMIT */
91
92 static int max_expiry = DEFAULT_MAX_EXPIRY;
93 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
94
95 #ifndef MAX
96 #define MAX(a,b) ((a) > (b) ? (a) : (b))
97 #endif
98
99 #define CALLERID_UNKNOWN        "Unknown"
100
101
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
111 #define DEBUG_READ      0                       /* Recieved data        */
112 #define DEBUG_SEND      1                       /* Transmit data        */
113
114 static char *desc = "Session Initiation Protocol (SIP)";
115 static char *channeltype = "SIP";
116 static char *tdesc = "Session Initiation Protocol (SIP)";
117 static char *config = "sip.conf";
118 static char *notify_config = "sip_notify.conf";
119
120 #define DEFAULT_SIP_PORT        5060    /* From RFC 2543 */
121 #define SIP_MAX_PACKET          4096    /* Also from RFC 2543, should sub headers tho */
122
123 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
124
125 static char default_useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT;
126
127 #define DEFAULT_CONTEXT "default"
128 static char default_context[AST_MAX_EXTENSION] = DEFAULT_CONTEXT;
129
130 static char default_language[MAX_LANGUAGE] = "";
131
132 #define DEFAULT_CALLERID "asterisk"
133 static char default_callerid[AST_MAX_EXTENSION] = DEFAULT_CALLERID;
134
135 static char default_fromdomain[AST_MAX_EXTENSION] = "";
136
137 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
138 static char default_notifymime[AST_MAX_EXTENSION] = DEFAULT_NOTIFYMIME;
139
140 static struct ast_flags global_flags = {0};             /* global SIP_ flags */
141
142 static int srvlookup = 0;               /* SRV Lookup on or off. Default is off, RFC behavior is on */
143
144 static int pedanticsipchecking = 0;     /* Extra checking ?  Default off */
145
146 static int autocreatepeer = 0;          /* Auto creation of peers at registration? Default off. */
147
148 static int relaxdtmf = 0;
149
150 static int global_rtptimeout = 0;
151
152 static int global_rtpholdtimeout = 0;
153
154 static int global_rtpkeepalive = 0;
155
156 static int global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
157
158 /* Object counters */
159 static int suserobjs = 0;
160 static int ruserobjs = 0;
161 static int speerobjs = 0;
162 static int rpeerobjs = 0;
163 static int apeerobjs = 0;
164 static int regobjs = 0;
165
166 static int global_allowguest = 0;    /* allow unathuncated peers to connect? */
167
168 #define DEFAULT_MWITIME 10
169 static int global_mwitime = DEFAULT_MWITIME;    /* Time between MWI checks for peers */
170
171 static int usecnt =0;
172 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
173
174
175 /* Protect the interface list (of sip_pvt's) */
176 AST_MUTEX_DEFINE_STATIC(iflock);
177
178 /* Protect the monitoring thread, so only one process can kill or start it, and not
179    when it's doing something critical. */
180 AST_MUTEX_DEFINE_STATIC(netlock);
181
182 AST_MUTEX_DEFINE_STATIC(monlock);
183
184 /* This is the thread for the monitor which checks for input on the channels
185    which are not currently in use.  */
186 static pthread_t monitor_thread = AST_PTHREADT_NULL;
187
188 static int restart_monitor(void);
189
190 /* Codecs that we support by default: */
191 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
192 static int noncodeccapability = AST_RTP_DTMF;
193
194 static char ourhost[256];
195 static struct in_addr __ourip;
196 static struct sockaddr_in outboundproxyip;
197 static int ourport;
198
199 static int sipdebug = 0;
200 static struct sockaddr_in debugaddr;
201
202 static int tos = 0;
203
204 static int videosupport = 0;
205
206 static int compactheaders = 0;                                          /* send compact sip headers */
207
208 static int recordhistory = 0;                           /* Record SIP history. Off by default */
209
210 static char global_musicclass[MAX_LANGUAGE] = "";       /* Global music on hold class */
211 static char global_realm[AST_MAX_EXTENSION] = "asterisk";       /* Default realm */
212 static char regcontext[AST_MAX_EXTENSION] = "";         /* Context for auto-extensions */
213
214 /* Expire slowly */
215 #define DEFAULT_EXPIRY 900
216 static int expiry = DEFAULT_EXPIRY;
217
218 static struct sched_context *sched;
219 static struct io_context *io;
220 /* The private structures of the  sip channels are linked for
221    selecting outgoing channels */
222    
223 #define SIP_MAX_HEADERS         64
224 #define SIP_MAX_LINES           64
225
226 #define DEC_IN_USE      0
227 #define INC_IN_USE      1
228 #define DEC_OUT_USE     2
229 #define INC_OUT_USE     3
230
231 static struct ast_codec_pref prefs;
232
233
234 /* sip_request: The data grabbed from the UDP socket */
235 struct sip_request {
236         char *rlPart1;          /* SIP Method Name or "SIP/2.0" protocol version */
237         char *rlPart2;          /* The Request URI or Response Status */
238         int len;                /* Length */
239         int headers;            /* # of SIP Headers */
240         char *header[SIP_MAX_HEADERS];
241         int lines;                                              /* SDP Content */
242         char *line[SIP_MAX_LINES];
243         char data[SIP_MAX_PACKET];
244 };
245
246 struct sip_pkt;
247
248 struct sip_route {
249         struct sip_route *next;
250         char hop[0];
251 };
252
253 struct sip_history {
254         char event[80];
255         struct sip_history *next;
256 };
257
258 #define SIP_ALREADYGONE         (1 << 0)        /* Whether or not we've already been destroyed by our peer */
259 #define SIP_NEEDDESTROY         (1 << 1)        /* if we need to be destroyed */
260 #define SIP_NOVIDEO             (1 << 2)        /* Didn't get video in invite, don't offer */
261 #define SIP_RINGING             (1 << 3)        /* Have sent 180 ringing */
262 #define SIP_PROGRESS_SENT               (1 << 4)        /* Have sent 183 message progress */
263 #define SIP_NEEDREINVITE        (1 << 5)        /* Do we need to send another reinvite? */
264 #define SIP_PENDINGBYE          (1 << 6)        /* Need to send bye after we ack? */
265 #define SIP_GOTREFER            (1 << 7)        /* Got a refer? */
266 #define SIP_PROMISCREDIR        (1 << 8)        /* Promiscuous redirection */
267 #define SIP_TRUSTRPID           (1 << 9)        /* Trust RPID headers? */
268 #define SIP_USEREQPHONE         (1 << 10)       /* Add user=phone to numeric URI. Default off */
269 #define SIP_REALTIME            (1 << 11)       /* Flag for realtime users */
270 #define SIP_USECLIENTCODE       (1 << 12)       /* Trust X-ClientCode info message */
271 #define SIP_OUTGOING            (1 << 13)       /* Is this an outgoing call? */
272 #define SIP_SELFDESTRUCT        (1 << 14)       
273 #define SIP_DYNAMIC             (1 << 15)       /* Is this a dynamic peer? */
274 /* --- Choices for DTMF support in SIP channel */
275 #define SIP_DTMF                (3 << 16)       /* three settings, uses two bits */
276 #define SIP_DTMF_RFC2833        (0 << 16)       /* RTP DTMF */
277 #define SIP_DTMF_INBAND         (1 << 16)       /* Inband audio, only for ULAW/ALAW */
278 #define SIP_DTMF_INFO           (2 << 16)       /* SIP Info messages */
279 /* NAT settings */
280 #define SIP_NAT                 (3 << 18)       /* four settings, uses two bits */
281 #define SIP_NAT_NEVER           (0 << 18)       /* No nat support */
282 #define SIP_NAT_RFC3581         (1 << 18)
283 #define SIP_NAT_ROUTE           (2 << 18)
284 #define SIP_NAT_ALWAYS          (3 << 18)
285 /* re-INVITE related settings */
286 #define SIP_REINVITE            (3 << 20)       /* two bits used */
287 #define SIP_CAN_REINVITE        (1 << 20)       /* allow peers to be reinvited to send media directly to us */
288 #define SIP_REINVITE_UPDATE     (2 << 20)       /* use UPDATE (RFC3311) when reinviting this peer */
289 /* "insecure" settings */
290 #define SIP_INSECURE            (3 << 22)       /* three settings, uses two bits */
291 #define SIP_SECURE              (0 << 22)
292 #define SIP_INSECURE_NORMAL     (1 << 22)
293 #define SIP_INSECURE_VERY       (2 << 22)
294 /* Sending PROGRESS in-band settings */
295 #define SIP_PROG_INBAND         (3 << 24)       /* three settings, uses two bits */
296 #define SIP_PROG_INBAND_NEVER   (0 << 24)
297 #define SIP_PROG_INBAND_NO      (1 << 24)
298 #define SIP_PROG_INBAND_YES     (2 << 24)
299 /* Open Settlement Protocol authentication */
300 #define SIP_OSPAUTH             (3 << 26)       /* three settings, uses two bits */
301 #define SIP_OSPAUTH_NO          (0 << 26)
302 #define SIP_OSPAUTH_YES         (1 << 26)
303 #define SIP_OSPAUTH_EXCLUSIVE   (2 << 26)
304
305 /* sip_pvt: PVT structures are used for each SIP conversation, ie. a call  */
306 static struct sip_pvt {
307         ast_mutex_t lock;                       /* Channel private lock */
308         char callid[80];                        /* Global CallID */
309         char randdata[80];                      /* Random data */
310         struct ast_codec_pref prefs; /* codec prefs */
311         unsigned int ocseq;                     /* Current outgoing seqno */
312         unsigned int icseq;                     /* Current incoming seqno */
313         unsigned int callgroup;                 /* Call group */
314         unsigned int pickupgroup;               /* Pickup group */
315         int lastinvite;                         /* Last Cseq of invite */
316         unsigned int flags;                     /* SIP_ flags */        
317         int capability;                         /* Special capability (codec) */
318         int jointcapability;                    /* Supported capability at both ends (codecs ) */
319         int peercapability;                     /* Supported peer capability */
320         int prefcodec;                          /* Preferred codec (outbound only) */
321         int noncodeccapability;
322         int callingpres;                        /* Calling presentation */
323         int authtries;                          /* Times we've tried to authenticate */
324         int expiry;                             /* How long we take to expire */
325         int branch;                             /* One random number */
326         int tag;                                /* Another random number */
327         int sessionid;                          /* SDP Session ID */
328         int sessionversion;                     /* SDP Session Version */
329         struct sockaddr_in sa;                  /* Our peer */
330         struct sockaddr_in redirip;             /* Where our RTP should be going if not to us */
331         struct sockaddr_in vredirip;            /* Where our Video RTP should be going if not to us */
332         int redircodecs;                        /* Redirect codecs */
333         struct sockaddr_in recv;                /* Received as */
334         struct in_addr ourip;                   /* Our IP */
335         struct ast_channel *owner;              /* Who owns us */
336         char exten[AST_MAX_EXTENSION];          /* Extension where to start */
337         char refer_to[AST_MAX_EXTENSION];       /* Place to store REFER-TO extension */
338         char referred_by[AST_MAX_EXTENSION];    /* Place to store REFERRED-BY extension */
339         char refer_contact[AST_MAX_EXTENSION];  /* Place to store Contact info from a REFER extension */
340         struct sip_pvt *refer_call;             /* Call we are referring */
341         struct sip_route *route;                /* Head of linked list of routing steps (fm Record-Route) */
342         int route_persistant;                   /* Is this the "real" route? */
343         char from[256];                         /* The From: header */
344         char useragent[256];                    /* User agent in SIP request */
345         char context[AST_MAX_EXTENSION];        /* Context for this call */
346         char fromdomain[AST_MAX_EXTENSION];     /* Domain to show in the from field */
347         char fromuser[AST_MAX_EXTENSION];       /* Domain to show in the user field */
348         char tohost[AST_MAX_EXTENSION];         /* Host we should put in the "to" field */
349         char language[MAX_LANGUAGE];            /* Default language for this call */
350         char musicclass[MAX_LANGUAGE];          /* Music on Hold class */
351         char rdnis[256];                        /* Referring DNIS */
352         char theirtag[256];                     /* Their tag */
353         char username[256];
354         char peername[256];
355         char authname[256];                     /* Who we use for authentication */
356         char uri[256];                          /* Original requested URI */
357         char okcontacturi[256];                 /* URI from the 200 OK on INVITE */
358         char peersecret[256];                   /* Password */
359         char peermd5secret[256];
360         char cid_num[256];                      /* Caller*ID */
361         char cid_name[256];                     /* Caller*ID */
362         char via[256];                          /* Via: header */
363         char fullcontact[128];                  /* The Contact: that the UA registers with us */
364         char accountcode[20];                   /* Account code */
365         char our_contact[256];                  /* Our contact header */
366         char realm[256];                        /* Authorization realm */
367         char nonce[256];                        /* Authorization nonce */
368         char opaque[256];                       /* Opaque nonsense */
369         char qop[80];                           /* Quality of Protection, since SIP wasn't complicated enough yet. */
370         char domain[256];                       /* Authorization domain */
371         char lastmsg[256];                      /* Last Message sent/received */
372         int amaflags;                           /* AMA Flags */
373         int pendinginvite;                      /* Any pending invite */
374 #ifdef OSP_SUPPORT
375         int osphandle;                          /* OSP Handle for call */
376         time_t ospstart;                        /* OSP Start time */
377 #endif
378         struct sip_request initreq;             /* Initial request */
379         
380         int maxtime;                            /* Max time for first response */
381         int initid;                             /* Auto-congest ID if appropriate */
382         int autokillid;                         /* Auto-kill ID */
383         time_t lastrtprx;                       /* Last RTP received */
384         time_t lastrtptx;                       /* Last RTP sent */
385         int rtptimeout;                         /* RTP timeout time */
386         int rtpholdtimeout;                     /* RTP timeout when on hold */
387         int rtpkeepalive;                       /* Send RTP packets for keepalive */
388
389         int subscribed;                         /* Is this call a subscription?  */
390         int stateid;
391         int dialogver;
392         
393         struct ast_dsp *vad;
394         
395         struct sip_peer *peerpoke;              /* If this calls is to poke a peer, which one */
396         struct sip_registry *registry;          /* If this is a REGISTER call, to which registry */
397         struct ast_rtp *rtp;                    /* RTP Session */
398         struct ast_rtp *vrtp;                   /* Video RTP session */
399         struct sip_pkt *packets;                /* Packets scheduled for re-transmission */
400         struct sip_history *history;            /* History of this SIP dialog */
401         struct ast_variable *vars;
402         struct sip_pvt *next;                   /* Next call in chain */
403 } *iflist = NULL;
404
405 #define FLAG_RESPONSE (1 << 0)
406 #define FLAG_FATAL (1 << 1)
407
408 /* sip packet - read in sipsock_read, transmitted in send_request */
409 struct sip_pkt {
410         struct sip_pkt *next;                           /* Next packet */
411         int retrans;                                    /* Retransmission number */
412         int seqno;                                      /* Sequence number */
413         unsigned int flags;                             /* non-zero if this is a response packet (e.g. 200 OK) */
414         struct sip_pvt *owner;                          /* Owner call */
415         int retransid;                                  /* Retransmission ID */
416         int packetlen;                                  /* Length of packet */
417         char data[0];
418 };      
419
420 /* Structure for SIP user data. User's place calls to us */
421 struct sip_user {
422         /* Users who can access various contexts */
423         ASTOBJ_COMPONENTS(struct sip_user);
424         char secret[80];                /* Password */
425         char md5secret[80];             /* Password in md5 */
426         char context[80];               /* Default context for incoming calls */
427         char cid_num[80];               /* Caller ID num */
428         char cid_name[80];              /* Caller ID name */
429         char accountcode[20];           /* Account code */
430         char language[MAX_LANGUAGE];    /* Default language for this user */
431         char musicclass[MAX_LANGUAGE];  /* Music on Hold class */
432         char useragent[256];            /* User agent in SIP request */
433         struct ast_codec_pref prefs; /* codec prefs */
434         unsigned int callgroup;         /* Call group */
435         unsigned int pickupgroup;       /* Pickup Group */
436         unsigned int flags;             /* SIP_ flags */        
437         int amaflags;                   /* AMA flags for billing */
438         int callingpres;                /* Calling id presentation */
439         int capability;                 /* Codec capability */
440         int inUse;
441         int incominglimit;
442         int outUse;
443         int outgoinglimit;
444         struct ast_ha *ha;              /* ACL setting */
445         struct ast_variable *vars;
446 };
447
448 /* Structure for SIP peer data, we place calls to peers if registred  or fixed IP address (host) */
449 struct sip_peer {
450         ASTOBJ_COMPONENTS(struct sip_peer);
451         char secret[80];                /* Password */
452         char md5secret[80];             /* Password in MD5 */
453         char context[80];               /* Default context for incoming calls */
454         char username[80];              /* Temporary username until registration */
455         char tohost[80];                /* If not dynamic, IP address */
456         char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
457         char fromuser[80];              /* From: user when calling this peer */
458         char fromdomain[80];            /* From: domain when calling this peer */
459         char fullcontact[128];          /* Contact registred with us (not in sip.conf) */
460         char cid_num[80];               /* Caller ID num */
461         char cid_name[80];              /* Caller ID name */
462         char mailbox[AST_MAX_EXTENSION]; /* Mailbox setting for MWI checks */
463         char language[MAX_LANGUAGE];    /* Default language for prompts */
464         char musicclass[MAX_LANGUAGE];  /* Music on Hold class */
465         char useragent[256];            /* User agent in SIP request (saved from registration) */
466         struct ast_codec_pref prefs; /* codec prefs */
467         int lastmsgssent;
468         time_t  lastmsgcheck;           /* Last time we checked for MWI */
469         unsigned int flags;             /* SIP_ flags */        
470         int expire;                     /* Registration expiration */
471         int expiry;
472         int capability;                 /* Codec capability */
473         int rtptimeout;
474         int rtpholdtimeout;
475         int rtpkeepalive;                       /* Send RTP packets for keepalive */
476         unsigned int callgroup;         /* Call group */
477         unsigned int pickupgroup;       /* Pickup group */
478         struct sockaddr_in addr;        /* IP address of peer */
479         struct in_addr mask;
480
481         /* Qualification */
482         struct sip_pvt *call;           /* Call pointer */
483         int pokeexpire;                 /* When to expire poke (qualify= checking) */
484         int lastms;                     /* How long last response took (in ms), or -1 for no response */
485         int maxms;                      /* Max ms we will accept for the host to be up, 0 to not monitor */
486         struct timeval ps;              /* Ping send time */
487         
488         struct sockaddr_in defaddr;     /* Default IP address, used until registration */
489         struct ast_ha *ha;              /* Access control list */
490         int lastmsg;
491 };
492
493 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
494 static int sip_reloading = 0;
495
496 /* States for outbound registrations (with register= lines in sip.conf */
497 #define REG_STATE_UNREGISTERED          0
498 #define REG_STATE_REGSENT               1
499 #define REG_STATE_AUTHSENT              2
500 #define REG_STATE_REGISTERED            3
501 #define REG_STATE_REJECTED              4
502 #define REG_STATE_TIMEOUT               5
503 #define REG_STATE_NOAUTH                6
504
505
506 /* sip_registry: Registrations with other SIP proxies */
507 struct sip_registry {
508         ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
509         int portno;                     /* Optional port override */
510         char username[80];              /* Who we are registering as */
511         char authuser[80];              /* Who we *authenticate* as */
512         char hostname[80];              /* Domain or host we register to */
513         char secret[80];                /* Password or key name in []'s */      
514         char md5secret[80];
515         char contact[80];               /* Contact extension */
516         char random[80];
517         int expire;                     /* Sched ID of expiration */
518         int timeout;                    /* sched id of sip_reg_timeout */
519         int refresh;                    /* How often to refresh */
520         struct sip_pvt *call;           /* create a sip_pvt structure for each outbound "registration call" in progress */
521         int regstate;                   /* Registration state (see above) */
522         int callid_valid;               /* 0 means we haven't chosen callid for this registry yet. */
523         char callid[80];                /* Global CallID for this registry */
524         unsigned int ocseq;             /* Sequence number we got to for REGISTERs for this registry */
525         struct sockaddr_in us;          /* Who the server thinks we are */
526         
527                                         /* Saved headers */
528         char realm[256];                /* Authorization realm */
529         char nonce[256];                /* Authorization nonce */
530         char domain[256];               /* Authorization domain */
531         char opaque[256];               /* Opaque nonsense */
532         char qop[80];                   /* Quality of Protection. */
533  
534         char lastmsg[256];              /* Last Message sent/received */
535 };
536
537 /*--- The user list: Users and friends ---*/
538 static struct ast_user_list {
539         ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
540 } userl;
541
542 /*--- The peer list: Peers and Friends ---*/
543 static struct ast_peer_list {
544         ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
545 } peerl;
546
547 /*--- The register list: Other SIP proxys we register with and call ---*/
548 static struct ast_register_list {
549         ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
550         int recheck;
551 } regl;
552
553
554 static int __sip_do_register(struct sip_registry *r);
555
556 static int sipsock  = -1;
557
558
559 static struct sockaddr_in bindaddr;
560 static struct sockaddr_in externip;
561 static char externhost[256] = "";
562 static time_t externexpire = 0;
563 static int externrefresh = 10;
564 static struct ast_ha *localaddr;
565
566 /* The list of manual NOTIFY types we know how to send */
567 struct ast_config *notify_types;
568
569 static struct ast_frame  *sip_read(struct ast_channel *ast);
570 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
571 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
572 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable, char *header);
573 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
574 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
575 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 addsipheaders, int init);
576 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
577 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
578 static int transmit_message_with_text(struct sip_pvt *p, char *text);
579 static int transmit_refer(struct sip_pvt *p, char *dest);
580 static struct sip_peer *temp_peer(char *name);
581 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
582 static void free_old_route(struct sip_route *route);
583 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
584 static int update_user_counter(struct sip_pvt *fup, int event);
585 static void prune_peers(void);
586 static int sip_do_reload(void);
587
588
589 /*--- sip_debug_test_addr: See if we pass debug IP filter */
590 static inline int sip_debug_test_addr(struct sockaddr_in *addr) 
591 {
592         if (sipdebug == 0)
593                 return 0;
594         if (debugaddr.sin_addr.s_addr) {
595                 if (((ntohs(debugaddr.sin_port) != 0)
596                         && (debugaddr.sin_port != addr->sin_port))
597                         || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
598                         return 0;
599         }
600         return 1;
601 }
602
603 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
604 {
605         if (sipdebug == 0)
606                 return 0;
607         return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
608 }
609
610
611 /*--- __sip_xmit: Transmit SIP message ---*/
612 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
613 {
614         int res;
615         char iabuf[INET_ADDRSTRLEN];
616         if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
617             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
618         else
619             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
620         if (res != len) {
621                 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), res, strerror(errno));
622         }
623         return res;
624 }
625
626 static void sip_destroy(struct sip_pvt *p);
627
628 /*--- build_via: Build a Via header for a request ---*/
629 static void build_via(struct sip_pvt *p, char *buf, int len)
630 {
631         char iabuf[INET_ADDRSTRLEN];
632
633         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
634         if (ast_test_flag(p, SIP_NAT) != SIP_NAT_NEVER)
635                 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
636         else /* Work around buggy UNIDEN UIP200 firmware */
637                 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
638 }
639
640 /*--- ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/
641 /* Only used for outbound registrations */
642 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
643 {
644         /*
645          * Using the localaddr structure built up with localnet statements
646          * apply it to their address to see if we need to substitute our
647          * externip or can get away with our internal bindaddr
648          */
649         struct sockaddr_in theirs;
650         theirs.sin_addr = *them;
651         if (localaddr && externip.sin_addr.s_addr &&
652            ast_apply_ha(localaddr, &theirs)) {
653                 char iabuf[INET_ADDRSTRLEN];
654                 if (externexpire && (time(NULL) >= externexpire)) {
655                         struct ast_hostent ahp;
656                         struct hostent *hp;
657                         time(&externexpire);
658                         externexpire += externrefresh;
659                         if ((hp = ast_gethostbyname(externhost, &ahp))) {
660                                 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
661                         } else
662                                 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
663                 }
664                 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
665                 ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
666                 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
667         }
668         else if (bindaddr.sin_addr.s_addr)
669                 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
670         else
671                 return ast_ouraddrfor(them, us);
672         return 0;
673 }
674
675 static int append_history(struct sip_pvt *p, char *event, char *data)
676 {
677         struct sip_history *hist, *prev;
678         char *c;
679         if (!recordhistory)
680                 return 0;
681         hist = malloc(sizeof(struct sip_history));
682         if (hist) {
683                 memset(hist, 0, sizeof(struct sip_history));
684                 snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
685                 /* Trim up nicely */
686                 c = hist->event;
687                 while(*c) {
688                         if ((*c == '\r') || (*c == '\n')) {
689                                 *c = '\0';
690                                 break;
691                         }
692                         c++;
693                 }
694                 /* Enqueue into history */
695                 prev = p->history;
696                 if (prev) {
697                         while(prev->next)
698                                 prev = prev->next;
699                         prev->next = hist;
700                 } else {
701                         p->history = hist;
702                 }
703         }
704         return 0;
705 }
706
707 /*--- retrans_pkt: Retransmit SIP message if no answer ---*/
708 static int retrans_pkt(void *data)
709 {
710         struct sip_pkt *pkt=data, *prev, *cur;
711         int res = 0;
712         char iabuf[INET_ADDRSTRLEN];
713         ast_mutex_lock(&pkt->owner->lock);
714         if (pkt->retrans < MAX_RETRANS) {
715                 pkt->retrans++;
716                 if (sip_debug_test_pvt(pkt->owner)) {
717                         if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE)
718                                 ast_verbose("Retransmitting #%d (NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port));
719                         else
720                                 ast_verbose("Retransmitting #%d (no NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port));
721                 }
722                 append_history(pkt->owner, "ReTx", pkt->data);
723                 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
724                 res = 1;
725         } else {
726                 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
727                 append_history(pkt->owner, "MaxRetries", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
728                 pkt->retransid = -1;
729                 if (ast_test_flag(pkt, FLAG_FATAL)) {
730                         while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
731                                 ast_mutex_unlock(&pkt->owner->lock);
732                                 usleep(1);
733                                 ast_mutex_lock(&pkt->owner->lock);
734                         }
735                         if (pkt->owner->owner) {
736                                 ast_set_flag(pkt->owner, SIP_ALREADYGONE);
737                                 ast_queue_hangup(pkt->owner->owner);
738                                 ast_mutex_unlock(&pkt->owner->owner->lock);
739                         } else {
740                                 /* If no owner, destroy now */
741                                 ast_set_flag(pkt->owner, SIP_NEEDDESTROY);      
742                         }
743                 }
744                 /* In any case, go ahead and remove the packet */
745                 prev = NULL;
746                 cur = pkt->owner->packets;
747                 while(cur) {
748                         if (cur == pkt)
749                                 break;
750                         prev = cur;
751                         cur = cur->next;
752                 }
753                 if (cur) {
754                         if (prev)
755                                 prev->next = cur->next;
756                         else
757                                 pkt->owner->packets = cur->next;
758                         ast_mutex_unlock(&pkt->owner->lock);
759                         free(cur);
760                         pkt = NULL;
761                 } else
762                         ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
763         }
764         if (pkt)
765                 ast_mutex_unlock(&pkt->owner->lock);
766         return res;
767 }
768
769 /*--- __sip_reliable_xmit: transmit packet with retransmits ---*/
770 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal)
771 {
772         struct sip_pkt *pkt;
773         pkt = malloc(sizeof(struct sip_pkt) + len + 1);
774         if (!pkt)
775                 return -1;
776         memset(pkt, 0, sizeof(struct sip_pkt));
777         memcpy(pkt->data, data, len);
778         pkt->packetlen = len;
779         pkt->next = p->packets;
780         pkt->owner = p;
781         pkt->seqno = seqno;
782         pkt->flags = resp;
783         pkt->data[len] = '\0';
784         if (fatal)
785                 ast_set_flag(pkt, FLAG_FATAL);
786         /* Schedule retransmission */
787         pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
788         pkt->next = p->packets;
789         p->packets = pkt;
790         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
791         if (!strncasecmp(pkt->data, "INVITE", 6)) {
792                 /* Note this is a pending invite */
793                 p->pendinginvite = seqno;
794         }
795         return 0;
796 }
797
798 /*--- __sip_autodestruct: Kill a call (called by scheduler) ---*/
799 static int __sip_autodestruct(void *data)
800 {
801         struct sip_pvt *p = data;
802         p->autokillid = -1;
803         ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
804         append_history(p, "AutoDestroy", "");
805         if (p->owner) {
806                 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
807                 ast_queue_hangup(p->owner);
808         } else {
809                 sip_destroy(p);
810         }
811         return 0;
812 }
813
814 /*--- sip_scheddestroy: Schedule destruction of SIP call ---*/
815 static int sip_scheddestroy(struct sip_pvt *p, int ms)
816 {
817         char tmp[80];
818         if (sip_debug_test_pvt(p))
819                 ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
820         if (recordhistory) {
821                 snprintf(tmp, sizeof(tmp), "%d ms", ms);
822                 append_history(p, "SchedDestroy", tmp);
823         }
824         if (p->autokillid > -1)
825                 ast_sched_del(sched, p->autokillid);
826         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
827         return 0;
828 }
829
830 /*--- sip_cancel_destroy: Cancel destruction of SIP call ---*/
831 static int sip_cancel_destroy(struct sip_pvt *p)
832 {
833         if (p->autokillid > -1)
834                 ast_sched_del(sched, p->autokillid);
835         append_history(p, "CancelDestroy", "");
836         p->autokillid = -1;
837         return 0;
838 }
839
840 /*--- __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/
841 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, const char *msg)
842 {
843         struct sip_pkt *cur, *prev = NULL;
844         int res = -1;
845         int resetinvite = 0;
846         /* Just in case... */
847         if (!msg) msg = "___NEVER___";
848         cur = p->packets;
849         while(cur) {
850                 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
851                         ((ast_test_flag(cur, FLAG_RESPONSE)) || 
852                          (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
853                         if (!resp && (seqno == p->pendinginvite)) {
854                                 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
855                                 p->pendinginvite = 0;
856                                 resetinvite = 1;
857                         }
858                         /* this is our baby */
859                         if (prev)
860                                 prev->next = cur->next;
861                         else
862                                 p->packets = cur->next;
863                         if (cur->retransid > -1)
864                                 ast_sched_del(sched, cur->retransid);
865                         free(cur);
866                         res = 0;
867                         break;
868                 }
869                 prev = cur;
870                 cur = cur->next;
871         }
872         ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
873         return res;
874 }
875
876 /* Pretend to ack all packets */
877 static int __sip_pretend_ack(struct sip_pvt *p)
878 {
879         while(p->packets) {
880                 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), p->packets->data);
881         }
882         return 0;
883 }
884
885 /*--- __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/
886 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, const char *msg)
887 {
888         struct sip_pkt *cur;
889         int res = -1;
890         cur = p->packets;
891         while(cur) {
892                 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
893                         ((ast_test_flag(cur, FLAG_RESPONSE)) || 
894                          (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
895                         /* this is our baby */
896                         if (cur->retransid > -1)
897                                 ast_sched_del(sched, cur->retransid);
898                         cur->retransid = -1;
899                         res = 0;
900                         break;
901                 }
902                 cur = cur->next;
903         }
904         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");
905         return res;
906 }
907
908 static void parse(struct sip_request *req);
909 static char *get_header(struct sip_request *req, char *name);
910 static void copy_request(struct sip_request *dst,struct sip_request *src);
911
912 static void parse_copy(struct sip_request *dst, struct sip_request *src)
913 {
914         memset(dst, 0, sizeof(*dst));
915         memcpy(dst->data, src->data, sizeof(dst->data));
916         dst->len = src->len;
917         parse(dst);
918 }
919 /*--- send_response: Transmit response on SIP request---*/
920 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
921 {
922         int res;
923         char iabuf[INET_ADDRSTRLEN];
924         struct sip_request tmp;
925         char tmpmsg[80];
926         if (sip_debug_test_pvt(p)) {
927                 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
928                         ast_verbose("%sTransmitting (NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
929                 else
930                         ast_verbose("%sTransmitting (no NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port));
931         }
932         if (reliable) {
933                 if (recordhistory) {
934                         parse_copy(&tmp, req);
935                         snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
936                         append_history(p, "TxRespRel", tmpmsg);
937                 }
938                 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1));
939         } else {
940                 if (recordhistory) {
941                         parse_copy(&tmp, req);
942                         snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
943                         append_history(p, "TxResp", tmpmsg);
944                 }
945                 res = __sip_xmit(p, req->data, req->len);
946         }
947         if (res > 0)
948                 res = 0;
949         return res;
950 }
951
952 /*--- send_request: Send SIP Request to the other part of the dialogue ---*/
953 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
954 {
955         int res;
956         char iabuf[INET_ADDRSTRLEN];
957         struct sip_request tmp;
958         char tmpmsg[80];
959         if (sip_debug_test_pvt(p)) {
960                 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
961                         ast_verbose("%sTransmitting:\n%s (NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
962                 else
963                         ast_verbose("%sTransmitting:\n%s (no NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port));
964         }
965         if (reliable) {
966                 if (recordhistory) {
967                         parse_copy(&tmp, req);
968                         snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
969                         append_history(p, "TxReqRel", tmpmsg);
970                 }
971                 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1));
972         } else {
973                 if (recordhistory) {
974                         parse_copy(&tmp, req);
975                         snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
976                         append_history(p, "TxReq", tmpmsg);
977                 }
978                 res = __sip_xmit(p, req->data, req->len);
979         }
980         return res;
981 }
982
983 /*--- url_decode: Decode SIP URL  ---*/
984 static void url_decode(char *s) 
985 {
986         char *o = s;
987         unsigned int tmp;
988         while(*s) {
989                 switch(*s) {
990                 case '%':
991                         if (strlen(s) > 2) {
992                                 if (sscanf(s + 1, "%2x", &tmp) == 1) {
993                                         *o = tmp;
994                                         s += 2; /* Will be incremented once more when we break out */
995                                         break;
996                                 }
997                         }
998                         /* Fall through if something wasn't right with the formatting */
999                 default:
1000                         *o = *s;
1001                 }
1002                 s++;
1003                 o++;
1004         }
1005         *o = '\0';
1006 }
1007
1008 /*--- ditch_braces: Pick out text in braces from character string  ---*/
1009 static char *ditch_braces(char *tmp)
1010 {
1011         char *c = tmp;
1012         char *n;
1013         char *q;
1014         if ((q = strchr(tmp, '"')) ) {
1015                 c = q + 1;
1016                 if ((q = strchr(c, '"')) )
1017                         c = q + 1;
1018                 else {
1019                         ast_log(LOG_WARNING, "No closing quote in '%s'\n", tmp);
1020                         c = tmp;
1021                 }
1022         }
1023         if ((n = strchr(c, '<')) ) {
1024                 c = n + 1;
1025                 while(*c && *c != '>') c++;
1026                 if (*c != '>') {
1027                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
1028                 } else {
1029                         *c = '\0';
1030                 }
1031                 return n+1;
1032         }
1033         return c;
1034 }
1035
1036 /*--- sip_sendtext: Send SIP MESSAGE text within a call ---*/
1037 /*      Called from PBX core text message functions */
1038 static int sip_sendtext(struct ast_channel *ast, char *text)
1039 {
1040         struct sip_pvt *p = ast->pvt->pvt;
1041         int debug=sip_debug_test_pvt(p);
1042
1043         if (debug)
1044                 ast_verbose("Sending text %s on %s\n", text, ast->name);
1045         if (!p)
1046                 return -1;
1047         if (!text || ast_strlen_zero(text))
1048                 return 0;
1049         if (debug)
1050                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1051         transmit_message_with_text(p, text);
1052         return 0;       
1053 }
1054
1055 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, int expirey)
1056 {
1057         char port[10];
1058         char ipaddr[20];
1059         char regseconds[20];
1060         time_t nowtime;
1061         
1062         time(&nowtime);
1063         nowtime += expirey;
1064         snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
1065         ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1066         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1067         ast_update_realtime("sipfriends", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
1068 }
1069
1070 static void register_peer_exten(struct sip_peer *peer, int onoff)
1071 {
1072         unsigned char multi[256]="";
1073         char *stringp, *ext;
1074         if (!ast_strlen_zero(regcontext)) {
1075                 strncpy(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi) - 1);
1076                 stringp = multi;
1077                 while((ext = strsep(&stringp, "&"))) {
1078                         if (onoff)
1079                                 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL, "Noop", strdup(peer->name), free, channeltype);
1080                         else
1081                                 ast_context_remove_extension(regcontext, ext, 1, NULL);
1082                 }
1083         }
1084 }
1085
1086 static void sip_destroy_peer(struct sip_peer *peer)
1087 {
1088         /* Delete it, it needs to disappear */
1089         if (peer->call)
1090                 sip_destroy(peer->call);
1091         if (peer->expire > -1)
1092                 ast_sched_del(sched, peer->expire);
1093         if (peer->pokeexpire > -1)
1094                 ast_sched_del(sched, peer->pokeexpire);
1095         register_peer_exten(peer, 0);
1096         ast_free_ha(peer->ha);
1097         if (ast_test_flag(peer, SIP_SELFDESTRUCT))
1098                 apeerobjs--;
1099         else if (ast_test_flag(peer, SIP_REALTIME))
1100                 rpeerobjs--;
1101         else
1102                 speerobjs--;
1103         free(peer);
1104 }
1105
1106 /*--- update_peer: Update peer data in database (if used) ---*/
1107 static void update_peer(struct sip_peer *p, int expiry)
1108 {
1109         if (ast_test_flag(p, SIP_REALTIME))
1110                 realtime_update_peer(p->name, &p->addr, p->username, expiry);
1111 }
1112
1113 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
1114
1115 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1116 {
1117         struct ast_variable *var, *tmp=NULL;
1118         char iabuf[80];
1119         struct sip_peer *peer=NULL;
1120         time_t nowtime, regseconds;
1121         int dynamic=0;
1122         
1123         if (sin)
1124                 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
1125         if (peername) 
1126                 var = ast_load_realtime("sipfriends", "name", peername, NULL);
1127         else
1128                 var = ast_load_realtime("sipfriends", "ipaddr", iabuf, NULL);
1129         if (var) {
1130                 /* Make sure it's not a user only... */
1131                 peer = build_peer(peername, var, 1);
1132                 if (peer) {
1133                         /* Add some finishing touches, addresses, etc */
1134                         ast_set_flag(peer, SIP_REALTIME);
1135                         tmp = var;
1136                         while(tmp) {
1137                                 if (!strcasecmp(tmp->name, "type")) {
1138                                         if (strcasecmp(tmp->value, "friend") &&
1139                                                 strcasecmp(tmp->value, "peer")) {
1140                                                 /* Whoops, we weren't supposed to exist! */
1141                                                 sip_destroy_peer(peer);
1142                                                 peer = NULL;
1143                                                 break;
1144                                         } 
1145                                 } else if (!strcasecmp(tmp->name, "regseconds")) {
1146                                         if (sscanf(tmp->value, "%li", &regseconds) != 1)
1147                                                 regseconds = 0;
1148                                 } else if (!strcasecmp(tmp->name, "ipaddr")) {
1149                                         inet_aton(tmp->value, &(peer->addr.sin_addr));
1150                                 } else if (!strcasecmp(tmp->name, "port")) {
1151                                         peer->addr.sin_port = htons(atoi(tmp->value));
1152                                 } else if (!strcasecmp(tmp->name, "host")) {
1153                                         if (!strcasecmp(tmp->value, "dynamic"))
1154                                                 dynamic = 1;
1155                                 }
1156                                 tmp = tmp->next;
1157                         }
1158                         if (peer && dynamic) {
1159                                 time(&nowtime);
1160                                 if ((nowtime - regseconds) > 0) {
1161                                         memset(&peer->addr, 0, sizeof(peer->addr));
1162                                         if (option_debug)
1163                                                 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
1164                                 }
1165                         }
1166                 }
1167                 ast_destroy_realtime(var);
1168         }
1169         if (peer) {
1170                 /* Destroy, so when our caller unrefs, it will disappear */
1171                 ASTOBJ_DESTROY(peer, sip_destroy_peer);
1172         }
1173         return peer;
1174 }
1175
1176 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
1177 {
1178         /* We know name is the first field, so we can cast */
1179         struct sip_peer *p = (struct sip_peer *)name;
1180         return  !(!inaddrcmp(&p->addr, sin) || 
1181                                         (ast_test_flag(p, SIP_INSECURE) &&
1182                                         (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
1183 }
1184
1185 /*--- find_peer: Locate peer by name or ip address */
1186 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin)
1187 {
1188         struct sip_peer *p = NULL;
1189
1190         if (peer)
1191                 p = ASTOBJ_CONTAINER_FIND(&peerl,peer);
1192         else
1193                 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl,sin,name,sip_addr_hashfunc,1,sip_addrcmp);
1194
1195         if (!p) {
1196                 p = realtime_peer(peer, sin);
1197         }
1198
1199         return(p);
1200 }
1201
1202 static void sip_destroy_user(struct sip_user *user)
1203 {
1204         ast_free_ha(user->ha);
1205         if(user->vars) {
1206                 ast_destroy_realtime(user->vars);
1207                 user->vars = NULL;
1208         }
1209         if (ast_test_flag(user, SIP_REALTIME))
1210                 ruserobjs--;
1211         else
1212                 suserobjs--;
1213         free(user);
1214 }
1215
1216 static struct sip_user *build_user(const char *name, struct ast_variable *v);
1217 static struct sip_user *realtime_user(const char *username)
1218 {
1219         struct ast_variable *var;
1220         struct ast_variable *tmp;
1221         struct sip_user *user=NULL;
1222         var = ast_load_realtime("sipfriends", "name", username, NULL);
1223         if (var) {
1224                 /* Make sure it's not a user only... */
1225                 user = build_user(username, var);
1226                 if (user) {
1227                         /* Move counter from s to r... */
1228                         suserobjs--;
1229                         ruserobjs++;
1230                         /* Add some finishing touches, addresses, etc */
1231                         ast_set_flag(user, SIP_REALTIME);       
1232                         tmp = var;
1233                         while(tmp) {
1234                                 if (!strcasecmp(tmp->name, "type")) {
1235                                         if (strcasecmp(tmp->value, "friend") &&
1236                                                 strcasecmp(tmp->value, "user")) {
1237                                                 /* Whoops, we weren't supposed to exist! */
1238                                                 sip_destroy_user(user);
1239                                                 user = NULL;
1240                                                 break;
1241                                         } 
1242                                 }
1243                                 tmp = tmp->next;
1244                         }
1245                 }
1246                 ast_destroy_realtime(var);
1247         }
1248         if (user) {
1249                 /* Reference and destroy, so when our caller unrefs, we disappear */
1250                 ASTOBJ_REF(user);
1251                 ASTOBJ_DESTROY(user, sip_destroy_user);
1252         }
1253         return user;
1254 }
1255
1256 /*--- find_user: Locate user by name */
1257 static struct sip_user *find_user(const char *name)
1258 {
1259         struct sip_user *u = NULL;
1260         u = ASTOBJ_CONTAINER_FIND(&userl,name);
1261         if (!u) {
1262                 u = realtime_user(name);
1263         }
1264         return(u);
1265 }
1266
1267 /*--- create_addr: create address structure from peer definition ---*/
1268 /*      Or, if peer not found, find it in the global DNS */
1269 /*      returns TRUE on failure, FALSE on success */
1270 static int create_addr(struct sip_pvt *r, char *opeer)
1271 {
1272         struct hostent *hp;
1273         struct ast_hostent ahp;
1274         struct sip_peer *p;
1275         int found=0;
1276         char *port;
1277         char *callhost;
1278         int portno;
1279         char host[256], *hostn;
1280         char peer[256]="";
1281
1282         strncpy(peer, opeer, sizeof(peer) - 1);
1283         port = strchr(peer, ':');
1284         if (port) {
1285                 *port = '\0';
1286                 port++;
1287         }
1288         r->sa.sin_family = AF_INET;
1289         p = find_peer(peer, NULL);
1290
1291         if (p) {
1292                         found++;
1293                         ast_copy_flags(r, p, SIP_PROMISCREDIR | SIP_USEREQPHONE | SIP_DTMF | SIP_NAT | SIP_REINVITE | SIP_INSECURE);
1294                         r->capability = p->capability;
1295                         if (r->rtp) {
1296                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1297                                 ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1298                         }
1299                         if (r->vrtp) {
1300                                 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1301                                 ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1302                         }
1303                         strncpy(r->peername, p->username, sizeof(r->peername)-1);
1304                         strncpy(r->authname, p->username, sizeof(r->authname)-1);
1305                         strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
1306                         strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
1307                         strncpy(r->username, p->username, sizeof(r->username)-1);
1308                         strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
1309                         strncpy(r->fullcontact, p->fullcontact, sizeof(r->fullcontact)-1);
1310                         if (!r->initreq.headers && !ast_strlen_zero(p->fromdomain)) {
1311                                 if ((callhost = strchr(r->callid, '@'))) {
1312                                         strncpy(callhost + 1, p->fromdomain, sizeof(r->callid) - (callhost - r->callid) - 2);
1313                                 }
1314                         }
1315                         if (ast_strlen_zero(r->tohost)) {
1316                                 if (p->addr.sin_addr.s_addr)
1317                                         ast_inet_ntoa(r->tohost, sizeof(r->tohost), p->addr.sin_addr);
1318                                 else
1319                                         ast_inet_ntoa(r->tohost, sizeof(r->tohost), p->defaddr.sin_addr);
1320                         }
1321                         if (!ast_strlen_zero(p->fromdomain))
1322                                 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
1323                         if (!ast_strlen_zero(p->fromuser))
1324                                 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
1325                         r->maxtime = p->maxms;
1326                         r->callgroup = p->callgroup;
1327                         r->pickupgroup = p->pickupgroup;
1328                         if (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833)
1329                                 r->noncodeccapability |= AST_RTP_DTMF;
1330                         else
1331                                 r->noncodeccapability &= ~AST_RTP_DTMF;
1332                         strncpy(r->context, p->context,sizeof(r->context)-1);
1333                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1334                                 (!p->maxms || ((p->lastms >= 0)  && (p->lastms <= p->maxms)))) {
1335                                 if (p->addr.sin_addr.s_addr) {
1336                                         r->sa.sin_addr = p->addr.sin_addr;
1337                                         r->sa.sin_port = p->addr.sin_port;
1338                                 } else {
1339                                         r->sa.sin_addr = p->defaddr.sin_addr;
1340                                         r->sa.sin_port = p->defaddr.sin_port;
1341                                 }
1342                                 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1343                         } else {
1344                                 ASTOBJ_UNREF(p,sip_destroy_peer);
1345                         }
1346         }
1347         if (!p && !found) {
1348                 hostn = peer;
1349                 if (port)
1350                         portno = atoi(port);
1351                 else
1352                         portno = DEFAULT_SIP_PORT;
1353                 if (srvlookup) {
1354                         char service[256];
1355                         int tportno;
1356                         int ret;
1357                         snprintf(service, sizeof(service), "_sip._udp.%s", peer);
1358                         ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
1359                         if (ret > 0) {
1360                                 hostn = host;
1361                                 portno = tportno;
1362                         }
1363                 }
1364                 hp = ast_gethostbyname(hostn, &ahp);
1365                 if (hp) {
1366                         strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
1367                         memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
1368                         r->sa.sin_port = htons(portno);
1369                         memcpy(&r->recv, &r->sa, sizeof(r->recv));
1370                         return 0;
1371                 } else {
1372                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1373                         return -1;
1374                 }
1375         } else if (!p)
1376                 return -1;
1377         else {
1378                 ASTOBJ_UNREF(p,sip_destroy_peer);
1379                 return 0;
1380         }
1381 }
1382
1383 /*--- auto_congest: Scheduled congestion on a call ---*/
1384 static int auto_congest(void *nothing)
1385 {
1386         struct sip_pvt *p = nothing;
1387         ast_mutex_lock(&p->lock);
1388         p->initid = -1;
1389         if (p->owner) {
1390                 if (!ast_mutex_trylock(&p->owner->lock)) {
1391                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1392                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1393                         ast_mutex_unlock(&p->owner->lock);
1394                 }
1395         }
1396         ast_mutex_unlock(&p->lock);
1397         return 0;
1398 }
1399
1400
1401
1402
1403 /*--- sip_call: Initiate SIP call from PBX ---*/
1404 /*      used from the dial() application      */
1405 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
1406 {
1407         int res;
1408         struct sip_pvt *p;
1409         char *vxml_url = NULL;
1410         char *distinctive_ring = NULL;
1411         char *osptoken = NULL;
1412 #ifdef OSP_SUPPORT
1413         char *osphandle = NULL;
1414 #endif  
1415         struct varshead *headp;
1416         struct ast_var_t *current;
1417         int addsipheaders = 0;
1418         
1419         p = ast->pvt->pvt;
1420         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1421                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
1422                 return -1;
1423         }
1424         /* Check whether there is vxml_url, distinctive ring variables */
1425
1426         headp=&ast->varshead;
1427         AST_LIST_TRAVERSE(headp,current,entries) {
1428                 /* Check whether there is a VXML_URL variable */
1429                 if (!vxml_url && !strcasecmp(ast_var_name(current),"VXML_URL")) {
1430                         vxml_url = ast_var_value(current);
1431                 } else if (!distinctive_ring && !strcasecmp(ast_var_name(current),"ALERT_INFO")) {
1432                         /* Check whether there is a ALERT_INFO variable */
1433                         distinctive_ring = ast_var_value(current);
1434                 } else if (!addsipheaders && !strncasecmp(ast_var_name(current),"SIPADDHEADER",strlen("SIPADDHEADER"))) {
1435                         /* Check whether there is a variable with a name starting with SIPADDHEADER */
1436                         addsipheaders = 1;
1437                 }
1438
1439                 
1440 #ifdef OSP_SUPPORT
1441                   else if (!osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
1442                         osptoken = ast_var_value(current);
1443                 } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
1444                         osphandle = ast_var_value(current);
1445                 }
1446 #endif
1447         }
1448         
1449         res = 0;
1450         ast_set_flag(p, SIP_OUTGOING);
1451 #ifdef OSP_SUPPORT
1452         if (!osptoken || !osphandle || (sscanf(osphandle, "%i", &p->osphandle) != 1)) {
1453                 /* Force Disable OSP support */
1454                 ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", osptoken, osphandle);
1455                 osptoken = NULL;
1456                 osphandle = NULL;
1457                 p->osphandle = -1;
1458         }
1459 #endif
1460         ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
1461         res = update_user_counter(p,INC_OUT_USE);
1462         if ( res != -1 ) {
1463                 p->callingpres = ast->cid.cid_pres;
1464                 p->jointcapability = p->capability;
1465                 transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, osptoken, addsipheaders, 1);
1466                 if (p->maxtime) {
1467                         /* Initialize auto-congest time */
1468                         p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
1469                 }
1470         }
1471         return res;
1472 }
1473
1474 static void sip_registry_destroy(struct sip_registry *reg)
1475 {
1476         /* Really delete */
1477         if (reg->call) {
1478                 /* Clear registry before destroying to ensure
1479                    we don't get reentered trying to grab the registry lock */
1480                 reg->call->registry = NULL;
1481                 sip_destroy(reg->call);
1482         }
1483         if (reg->expire > -1)
1484                 ast_sched_del(sched, reg->expire);
1485         if (reg->timeout > -1)
1486                 ast_sched_del(sched, reg->timeout);
1487         regobjs--;
1488         free(reg);
1489         
1490 }
1491
1492 /*---  __sip_destroy: Execute destrucion of call structure, release memory---*/
1493 static void __sip_destroy(struct sip_pvt *p, int lockowner)
1494 {
1495         struct sip_pvt *cur, *prev = NULL;
1496         struct sip_pkt *cp;
1497         struct sip_history *hist;
1498
1499         if (sip_debug_test_pvt(p))
1500                 ast_verbose("Destroying call '%s'\n", p->callid);
1501         if (p->stateid > -1)
1502                 ast_extension_state_del(p->stateid, NULL);
1503         if (p->initid > -1)
1504                 ast_sched_del(sched, p->initid);
1505         if (p->autokillid > -1)
1506                 ast_sched_del(sched, p->autokillid);
1507
1508         if (p->rtp) {
1509                 ast_rtp_destroy(p->rtp);
1510         }
1511         if (p->vrtp) {
1512                 ast_rtp_destroy(p->vrtp);
1513         }
1514         if (p->route) {
1515                 free_old_route(p->route);
1516                 p->route = NULL;
1517         }
1518         if (p->registry) {
1519                 if (p->registry->call == p)
1520                         p->registry->call = NULL;
1521                 ASTOBJ_UNREF(p->registry,sip_registry_destroy);
1522         }
1523         /* Unlink us from the owner if we have one */
1524         if (p->owner) {
1525                 if (lockowner)
1526                         ast_mutex_lock(&p->owner->lock);
1527                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
1528                 p->owner->pvt->pvt = NULL;
1529                 if (lockowner)
1530                         ast_mutex_unlock(&p->owner->lock);
1531         }
1532         /* Clear history */
1533         while(p->history) {
1534                 hist = p->history;
1535                 p->history = p->history->next;
1536                 free(hist);
1537         }
1538         cur = iflist;
1539         while(cur) {
1540                 if (cur == p) {
1541                         if (prev)
1542                                 prev->next = cur->next;
1543                         else
1544                                 iflist = cur->next;
1545                         break;
1546                 }
1547                 prev = cur;
1548                 cur = cur->next;
1549         }
1550         if (!cur) {
1551                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
1552         } else {
1553                 if (p->initid > -1)
1554                         ast_sched_del(sched, p->initid);
1555                 while((cp = p->packets)) {
1556                         p->packets = p->packets->next;
1557                         if (cp->retransid > -1)
1558                                 ast_sched_del(sched, cp->retransid);
1559                         free(cp);
1560                 }
1561                 ast_mutex_destroy(&p->lock);
1562                 if(p->vars) {
1563                         ast_destroy_realtime(p->vars);
1564                         p->vars = NULL;
1565                 }
1566                 free(p);
1567         }
1568 }
1569
1570 /*--- update_user_counter: Handle incominglimit and outgoinglimit for SIP users ---*/
1571 /* Note: This is going to be replaced by app_groupcount */
1572 static int update_user_counter(struct sip_pvt *fup, int event)
1573 {
1574         char name[256] = "";
1575         struct sip_user *u;
1576         strncpy(name, fup->username, sizeof(name) - 1);
1577         u = find_user(name);
1578         if (!u) {
1579                 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
1580                 return 0;
1581         }
1582         switch(event) {
1583                 /* incoming and outgoing affects the inUse counter */
1584                 case DEC_OUT_USE:
1585                 case DEC_IN_USE:
1586                         if ( u->inUse > 0 ) {
1587                                 u->inUse--;
1588                         } else {
1589                                 u->inUse = 0;
1590                         }
1591                         break;
1592                 case INC_IN_USE:
1593                 case INC_OUT_USE:
1594                         if (u->incominglimit > 0 ) {
1595                                 if (u->inUse >= u->incominglimit) {
1596                                         ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
1597                                         /* inc inUse as well */
1598                                         if ( event == INC_OUT_USE ) {
1599                                                 u->inUse++;
1600                                         }
1601                                         ASTOBJ_UNREF(u,sip_destroy_user);
1602                                         return -1; 
1603                                 }
1604                         }
1605                         u->inUse++;
1606                         ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
1607                         break;
1608                 /* we don't use these anymore
1609                 case DEC_OUT_USE:
1610                         if ( u->outUse > 0 ) {
1611                                 u->outUse--;
1612                         } else {
1613                                 u->outUse = 0;
1614                         }
1615                         break;
1616                 case INC_OUT_USE:
1617                         if ( u->outgoinglimit > 0 ) {
1618                                 if ( u->outUse >= u->outgoinglimit ) {
1619                                         ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
1620                                         ast_mutex_unlock(&userl.lock);
1621                                         if (u->temponly) {
1622                                                 destroy_user(u);
1623                                         }
1624                                         return -1;
1625                                 }
1626                         }
1627                         u->outUse++;
1628                         break;
1629                 */
1630                 default:
1631                         ast_log(LOG_ERROR, "update_user_counter(%s,%d) called with no event!\n",u->name,event);
1632         }
1633         ASTOBJ_UNREF(u,sip_destroy_user);
1634         return 0;
1635 }
1636
1637 /*--- sip_destroy: Destroy SIP call structure ---*/
1638 static void sip_destroy(struct sip_pvt *p)
1639 {
1640         ast_mutex_lock(&iflock);
1641         __sip_destroy(p, 1);
1642         ast_mutex_unlock(&iflock);
1643 }
1644
1645
1646 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
1647
1648 static int hangup_sip2cause(int cause)
1649 {
1650 /* Possible values from causes.h
1651         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
1652         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
1653 */
1654
1655         switch(cause) {
1656                 case 404:       /* Not found */
1657                         return AST_CAUSE_UNALLOCATED;
1658                 case 483:       /* Too many hops */
1659                         return AST_CAUSE_FAILURE;
1660                 case 486:
1661                         return AST_CAUSE_BUSY;
1662                 default:
1663                         return AST_CAUSE_NORMAL;
1664         }
1665         /* Never reached */
1666         return 0;
1667 }
1668
1669 static char *hangup_cause2sip(int cause)
1670 {
1671         switch(cause)
1672         {
1673                 case AST_CAUSE_FAILURE:
1674                         return "500 Server internal failure";
1675                 case AST_CAUSE_CONGESTION:
1676                         return "503 Service Unavailable";
1677                 case AST_CAUSE_BUSY:
1678                         return "486 Busy";
1679                 default:
1680                         return NULL;
1681         }
1682         /* Never reached */
1683         return 0;
1684 }
1685
1686 /*--- sip_hangup: Hangup SIP call */
1687 static int sip_hangup(struct ast_channel *ast)
1688 {
1689         struct sip_pvt *p = ast->pvt->pvt;
1690         int needcancel = 0;
1691         struct ast_flags locflags = {0};
1692         if (option_debug)
1693                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1694         if (!ast->pvt->pvt) {
1695                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1696                 return 0;
1697         }
1698         ast_mutex_lock(&p->lock);
1699 #ifdef OSP_SUPPORT
1700         if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
1701                 ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
1702         }
1703 #endif  
1704         if (ast_test_flag(p, SIP_OUTGOING)) {
1705                 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement outUse counter\n", p->username);
1706                 update_user_counter(p, DEC_OUT_USE);
1707         } else {
1708                 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement inUse counter\n", p->username);
1709                 update_user_counter(p, DEC_IN_USE);
1710         }
1711         /* Determine how to disconnect */
1712         if (p->owner != ast) {
1713                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
1714                 ast_mutex_unlock(&p->lock);
1715                 return 0;
1716         }
1717         if (!ast || (ast->_state != AST_STATE_UP))
1718                 needcancel = 1;
1719         /* Disconnect */
1720         p = ast->pvt->pvt;
1721         if (p->vad) {
1722             ast_dsp_free(p->vad);
1723         }
1724         p->owner = NULL;
1725         ast->pvt->pvt = NULL;
1726
1727         ast_mutex_lock(&usecnt_lock);
1728         usecnt--;
1729         ast_mutex_unlock(&usecnt_lock);
1730         ast_update_use_count();
1731
1732         ast_set_flag(&locflags, SIP_NEEDDESTROY);       
1733         /* Start the process if it's not already started */
1734         if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
1735                 if (needcancel) {
1736                         if (ast_test_flag(p, SIP_OUTGOING)) {
1737                                 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1, 0);
1738                                 /* Actually don't destroy us yet, wait for the 487 on our original 
1739                                    INVITE, but do set an autodestruct just in case we never get it. */
1740                                 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
1741                                 sip_scheddestroy(p, 15000);
1742                                 if ( p->initid != -1 ) {
1743                                         /* channel still up - reverse dec of inUse counter
1744                                            only if the channel is not auto-congested */
1745                                         if (ast_test_flag(p, SIP_OUTGOING)) {
1746                                                 update_user_counter(p, INC_OUT_USE);
1747                                         }
1748                                         else {
1749                                                 update_user_counter(p, INC_IN_USE);
1750                                         }
1751                                 }
1752                         } else {
1753                                 char *res;
1754                                 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
1755                                         transmit_response_reliable(p, res, &p->initreq, 1);
1756                                 } else 
1757                                         transmit_response_reliable(p, "403 Forbidden", &p->initreq, 1);
1758                         }
1759                 } else {
1760                         if (!p->pendinginvite) {
1761                                 /* Send a hangup */
1762                                 transmit_request_with_auth(p, "BYE", 0, 1, 1);
1763                         } else {
1764                                 /* Note we will need a BYE when this all settles out
1765                                    but we can't send one while we have "INVITE" outstanding. */
1766                                 ast_set_flag(p, SIP_PENDINGBYE);        
1767                                 ast_clear_flag(p, SIP_NEEDREINVITE);    
1768                         }
1769                 }
1770         }
1771         ast_copy_flags(p, (&locflags), SIP_NEEDDESTROY);        
1772         ast_mutex_unlock(&p->lock);
1773         return 0;
1774 }
1775
1776 /*--- sip_answer: Answer SIP call , send 200 OK on Invite */
1777 static int sip_answer(struct ast_channel *ast)
1778 {
1779         int res = 0,fmt;
1780         char *codec;
1781         struct sip_pvt *p = ast->pvt->pvt;
1782
1783         ast_mutex_lock(&p->lock);
1784         if (ast->_state != AST_STATE_UP) {
1785 #ifdef OSP_SUPPORT      
1786                 time(&p->ospstart);
1787 #endif
1788         
1789                 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1790                 if (codec) {
1791                         fmt=ast_getformatbyname(codec);
1792                         if (fmt) {
1793                                 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1794                                 if (p->jointcapability & fmt) {
1795                                         p->jointcapability &= fmt;
1796                                         p->capability &= fmt;
1797                                 } else
1798                                         ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
1799                         } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
1800                 }
1801
1802                 ast_setstate(ast, AST_STATE_UP);
1803                 if (option_debug)
1804                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1805                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1806         }
1807         ast_mutex_unlock(&p->lock);
1808         return res;
1809 }
1810
1811 /*--- sip_write: Send response, support audio media ---*/
1812 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1813 {
1814         struct sip_pvt *p = ast->pvt->pvt;
1815         int res = 0;
1816         if (frame->frametype == AST_FRAME_VOICE) {
1817                 if (!(frame->subclass & ast->nativeformats)) {
1818                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1819                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1820                         return 0;
1821                 }
1822                 if (p) {
1823                         ast_mutex_lock(&p->lock);
1824                         if (p->rtp) {
1825                                 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
1826                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1827                                         ast_set_flag(p, SIP_PROGRESS_SENT);     
1828                                 }
1829                                 time(&p->lastrtptx);
1830                                 res =  ast_rtp_write(p->rtp, frame);
1831                         }
1832                         ast_mutex_unlock(&p->lock);
1833                 }
1834         } else if (frame->frametype == AST_FRAME_VIDEO) {
1835                 if (p) {
1836                         ast_mutex_lock(&p->lock);
1837                         if (p->vrtp) {
1838                                 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
1839                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1840                                         ast_set_flag(p, SIP_PROGRESS_SENT);     
1841                                 }
1842                                 time(&p->lastrtptx);
1843                                 res =  ast_rtp_write(p->vrtp, frame);
1844                         }
1845                         ast_mutex_unlock(&p->lock);
1846                 }
1847         } else if (frame->frametype == AST_FRAME_IMAGE) {
1848                 return 0;
1849         } else {
1850                 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1851                 return 0;
1852         }
1853
1854         return res;
1855 }
1856
1857 /*--- sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
1858         Basically update any ->owner links ----*/
1859 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1860 {
1861         struct sip_pvt *p = newchan->pvt->pvt;
1862         ast_mutex_lock(&p->lock);
1863         if (p->owner != oldchan) {
1864                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1865                 ast_mutex_unlock(&p->lock);
1866                 return -1;
1867         }
1868         p->owner = newchan;
1869         ast_mutex_unlock(&p->lock);
1870         return 0;
1871 }
1872
1873 /*--- sip_senddigit: Send DTMF character on SIP channel */
1874 /*    within one call, we're able to transmit in many methods simultaneously */
1875 static int sip_senddigit(struct ast_channel *ast, char digit)
1876 {
1877         struct sip_pvt *p = ast->pvt->pvt;
1878         int res = 0;
1879         ast_mutex_lock(&p->lock);
1880         switch (ast_test_flag(p, SIP_DTMF)) {
1881         case SIP_DTMF_INFO:
1882                 transmit_info_with_digit(p, digit);
1883                 break;
1884         case SIP_DTMF_RFC2833:
1885                 if (p->rtp)
1886                         ast_rtp_senddigit(p->rtp, digit);
1887                 break;
1888         case SIP_DTMF_INBAND:
1889                 res = -1;
1890                 break;
1891         }
1892         ast_mutex_unlock(&p->lock);
1893         return res;
1894 }
1895
1896
1897 /*--- sip_transfer: Transfer SIP call */
1898 static int sip_transfer(struct ast_channel *ast, char *dest)
1899 {
1900         struct sip_pvt *p = ast->pvt->pvt;
1901         int res;
1902         ast_mutex_lock(&p->lock);
1903         res = transmit_refer(p, dest);
1904         ast_mutex_unlock(&p->lock);
1905         return res;
1906 }
1907
1908 /*--- sip_indicate: Play indication to user */
1909 /* With SIP a lot of indications is sent as messages, letting the device play
1910    the indication - busy signal, congestion etc */
1911 static int sip_indicate(struct ast_channel *ast, int condition)
1912 {
1913         struct sip_pvt *p = ast->pvt->pvt;
1914         int res = 0;
1915
1916         ast_mutex_lock(&p->lock);
1917         switch(condition) {
1918         case AST_CONTROL_RINGING:
1919                 if (ast->_state == AST_STATE_RING) {
1920                         if (!ast_test_flag(p, SIP_PROGRESS_SENT) ||
1921                             (ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
1922                                 /* Send 180 ringing if out-of-band seems reasonable */
1923                                 transmit_response(p, "180 Ringing", &p->initreq);
1924                                 ast_set_flag(p, SIP_RINGING);
1925                                 if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
1926                                         break;
1927                         } else {
1928                                 /* Well, if it's not reasonable, just send in-band */
1929                         }
1930                 }
1931                 res = -1;
1932                 break;
1933         case AST_CONTROL_BUSY:
1934                 if (ast->_state != AST_STATE_UP) {
1935                         transmit_response(p, "486 Busy Here", &p->initreq);
1936                         ast_set_flag(p, SIP_ALREADYGONE);       
1937                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1938                         break;
1939                 }
1940                 res = -1;
1941                 break;
1942         case AST_CONTROL_CONGESTION:
1943                 if (ast->_state != AST_STATE_UP) {
1944                         transmit_response(p, "503 Service Unavailable", &p->initreq);
1945                         ast_set_flag(p, SIP_ALREADYGONE);       
1946                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1947                         break;
1948                 }
1949                 res = -1;
1950                 break;
1951         case AST_CONTROL_PROGRESS:
1952         case AST_CONTROL_PROCEEDING:
1953                 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
1954                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1955                         ast_set_flag(p, SIP_PROGRESS_SENT);     
1956                         break;
1957                 }
1958                 res = -1;
1959                 break;
1960         case -1:
1961                 res = -1;
1962                 break;
1963         default:
1964                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1965                 res = -1;
1966                 break;
1967         }
1968         ast_mutex_unlock(&p->lock);
1969         return res;
1970 }
1971
1972
1973
1974 /*--- sip_new: Initiate a call in the SIP channel */
1975 /*      called from sip_request_call (calls from the pbx ) */
1976 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1977 {
1978         struct ast_channel *tmp;
1979         struct ast_variable *v = NULL;
1980         int fmt;
1981         
1982         ast_mutex_unlock(&i->lock);
1983         /* Don't hold a sip pvt lock while we allocate a channel */
1984         tmp = ast_channel_alloc(1);
1985         ast_mutex_lock(&i->lock);
1986         if (tmp) {
1987                 /* Select our native format based on codec preference until we receive
1988                    something from another device to the contrary. */
1989                 ast_mutex_lock(&i->lock);
1990                 if (i->jointcapability)
1991                         tmp->nativeformats = ast_codec_choose(&i->prefs, i->jointcapability, 1);
1992                 else if (i->capability)
1993                         tmp->nativeformats = ast_codec_choose(&i->prefs, i->capability, 1);
1994                 else
1995                         tmp->nativeformats = ast_codec_choose(&i->prefs, global_capability, 1);
1996                 ast_mutex_unlock(&i->lock);
1997                 fmt = ast_best_codec(tmp->nativeformats);
1998                 if (title)
1999                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
2000                 else
2001                         if (strchr(i->fromdomain,':'))
2002                         {
2003                                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
2004                         }
2005                         else
2006                         {
2007                                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
2008                         }
2009                 tmp->type = channeltype;
2010                 if (ast_test_flag(i, SIP_DTMF) ==  SIP_DTMF_INBAND) {
2011                     i->vad = ast_dsp_new();
2012                     ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
2013                     if (relaxdtmf)
2014                         ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
2015                 }
2016                 tmp->fds[0] = ast_rtp_fd(i->rtp);
2017                 tmp->fds[1] = ast_rtcp_fd(i->rtp);
2018                 if (i->vrtp) {
2019                         tmp->fds[2] = ast_rtp_fd(i->vrtp);
2020                         tmp->fds[3] = ast_rtcp_fd(i->vrtp);
2021                 }
2022                 if (state == AST_STATE_RING)
2023                         tmp->rings = 1;
2024                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2025                 tmp->writeformat = fmt;
2026                 tmp->pvt->rawwriteformat = fmt;
2027                 tmp->readformat = fmt;
2028                 tmp->pvt->rawreadformat = fmt;
2029                 tmp->pvt->pvt = i;
2030                 tmp->pvt->send_text = sip_sendtext;
2031                 tmp->pvt->call = sip_call;
2032                 tmp->pvt->hangup = sip_hangup;
2033                 tmp->pvt->answer = sip_answer;
2034                 tmp->pvt->read = sip_read;
2035                 tmp->pvt->write = sip_write;
2036                 tmp->pvt->write_video = sip_write;
2037                 tmp->pvt->indicate = sip_indicate;
2038                 tmp->pvt->transfer = sip_transfer;
2039                 tmp->pvt->fixup = sip_fixup;
2040                 tmp->pvt->send_digit = sip_senddigit;
2041
2042                 tmp->pvt->bridge = ast_rtp_bridge;
2043
2044                 tmp->callgroup = i->callgroup;
2045                 tmp->pickupgroup = i->pickupgroup;
2046                 tmp->cid.cid_pres = i->callingpres;
2047                 if (!ast_strlen_zero(i->accountcode))
2048                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2049                 if (i->amaflags)
2050                         tmp->amaflags = i->amaflags;
2051                 if (!ast_strlen_zero(i->language))
2052                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2053                 if (!ast_strlen_zero(i->musicclass))
2054                         strncpy(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass)-1);
2055                 i->owner = tmp;
2056                 ast_mutex_lock(&usecnt_lock);
2057                 usecnt++;
2058                 ast_mutex_unlock(&usecnt_lock);
2059                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2060                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2061                 if (!ast_strlen_zero(i->cid_num)) 
2062                         tmp->cid.cid_num = strdup(i->cid_num);
2063                 if (!ast_strlen_zero(i->cid_name))
2064                         tmp->cid.cid_name = strdup(i->cid_name);
2065                 if (!ast_strlen_zero(i->rdnis))
2066                         tmp->cid.cid_rdnis = strdup(i->rdnis);
2067                 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
2068                         tmp->cid.cid_dnid = strdup(i->exten);
2069                 tmp->priority = 1;
2070                 if (!ast_strlen_zero(i->uri)) {
2071                         pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
2072                 }
2073                 if (!ast_strlen_zero(i->domain)) {
2074                         pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
2075                 }
2076                 if (!ast_strlen_zero(i->useragent)) {
2077                         pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
2078                 }
2079                 if (!ast_strlen_zero(i->callid)) {
2080                         pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
2081                 }
2082                 ast_setstate(tmp, state);
2083                 if (state != AST_STATE_DOWN) {
2084                         if (ast_pbx_start(tmp)) {
2085                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2086                                 ast_hangup(tmp);
2087                                 tmp = NULL;
2088                         }
2089                 }
2090                 for (v = i->vars ; v ; v = v->next)
2091                         pbx_builtin_setvar_helper(tmp,v->name,v->value);
2092                                 
2093         } else
2094                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2095         return tmp;
2096 }
2097
2098 static struct cfalias {
2099         char *fullname;
2100         char *shortname;
2101 } aliases[] = {
2102         { "Content-Type", "c" },
2103         { "Content-Encoding", "e" },
2104         { "From", "f" },
2105         { "Call-ID", "i" },
2106         { "Contact", "m" },
2107         { "Content-Length", "l" },
2108         { "Subject", "s" },
2109         { "To", "t" },
2110         { "Supported", "k" },
2111         { "Refer-To", "r" },
2112         { "Allow-Events", "u" },
2113         { "Event", "o" },
2114         { "Via", "v" },
2115 };
2116
2117 /*--- get_sdp_by_line: Reads one line of SIP message body */
2118 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
2119   if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
2120     char* r = line + nameLen + 1;
2121     while (*r && (*r < 33)) ++r;
2122     return r;
2123   }
2124
2125   return "";
2126 }
2127
2128 /*--- get_sdp: Gets all kind of SIP message bodies, including SDP,
2129    but the name wrongly applies _only_ sdp */
2130 static char *get_sdp(struct sip_request *req, char *name) {
2131   int x;
2132   int len = strlen(name);
2133   char *r;
2134
2135   for (x=0; x<req->lines; x++) {
2136     r = get_sdp_by_line(req->line[x], name, len);
2137     if (r[0] != '\0') return r;
2138   }
2139   return "";
2140 }
2141
2142
2143 static void sdpLineNum_iterator_init(int* iterator) {
2144   *iterator = 0;
2145 }
2146
2147 static char* get_sdp_iterate(int* iterator,
2148                              struct sip_request *req, char *name) {
2149   int len = strlen(name);
2150   char *r;
2151   while (*iterator < req->lines) {
2152     r = get_sdp_by_line(req->line[(*iterator)++], name, len);
2153     if (r[0] != '\0') return r;
2154   }
2155   return "";
2156 }
2157
2158 static char *__get_header(struct sip_request *req, char *name, int *start)
2159 {
2160         int x;
2161         int len = strlen(name);
2162         char *r;
2163         if (pedanticsipchecking) {
2164                 /* Technically you can place arbitrary whitespace both before and after the ':' in
2165                    a header, although RFC3261 clearly says you shouldn't before, and place just
2166                    one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
2167                    a good idea to say you can do it, and if you can do it, why in the hell would 
2168                    you say you shouldn't.  */
2169                 for (x=*start;x<req->headers;x++) {
2170                         if (!strncasecmp(req->header[x], name, len)) {
2171                                 r = req->header[x] + len;
2172                                 while(*r && (*r < 33))
2173                                         r++;
2174                                 if (*r == ':') {
2175                                         r++ ;
2176                                         while(*r && (*r < 33))
2177                                                 r++;
2178                                         *start = x+1;
2179                                         return r;
2180                                 }
2181                         }
2182                 }
2183         } else {
2184                 /* We probably shouldn't even bother counting whitespace afterwards but
2185                    I guess for backwards compatibility we will */
2186                 for (x=*start;x<req->headers;x++) {
2187                         if (!strncasecmp(req->header[x], name, len) && 
2188                                         (req->header[x][len] == ':')) {
2189                                                 r = req->header[x] + len + 1;
2190                                                 while(*r && (*r < 33))
2191                                                                 r++;
2192                                                 *start = x+1;
2193                                                 return r;
2194                         }
2195                 }
2196         }
2197         /* Try aliases */
2198         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
2199                 if (!strcasecmp(aliases[x].fullname, name))
2200                         return __get_header(req, aliases[x].shortname, start);
2201
2202         /* Don't return NULL, so get_header is always a valid pointer */
2203         return "";
2204 }
2205
2206 /*--- get_header: Get header from SIP request ---*/
2207 static char *get_header(struct sip_request *req, char *name)
2208 {
2209         int start = 0;
2210         return __get_header(req, name, &start);
2211 }
2212
2213 /*--- sip_rtp_read: Read RTP from network ---*/
2214 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
2215 {
2216         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
2217         struct ast_frame *f;
2218         static struct ast_frame null_frame = { AST_FRAME_NULL, };
2219         switch(ast->fdno) {
2220         case 0:
2221                 f = ast_rtp_read(p->rtp);       /* RTP Audio */
2222                 break;
2223         case 1:
2224                 f = ast_rtcp_read(p->rtp);      /* RTCP Control Channel */
2225                 break;
2226         case 2:
2227                 f = ast_rtp_read(p->vrtp);      /* RTP Video */
2228                 break;
2229         case 3:
2230                 f = ast_rtcp_read(p->vrtp);     /* RTCP Control Channel for video */
2231                 break;
2232         default:
2233                 f = &null_frame;
2234         }
2235         /* Don't send RFC2833 if we're not supposed to */
2236         if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833))
2237                 return &null_frame;
2238         if (p->owner) {
2239                 /* We already hold the channel lock */
2240                 if (f->frametype == AST_FRAME_VOICE) {
2241                         if (f->subclass != p->owner->nativeformats) {
2242                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
2243                                 p->owner->nativeformats = f->subclass;
2244                                 ast_set_read_format(p->owner, p->owner->readformat);
2245                                 ast_set_write_format(p->owner, p->owner->writeformat);
2246                         }
2247             if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
2248                    f = ast_dsp_process(p->owner,p->vad,f);
2249                    if (f && (f->frametype == AST_FRAME_DTMF)) 
2250                         ast_log(LOG_DEBUG, "Detected DTMF '%c'\n", f->subclass);
2251             }
2252                 }
2253         }
2254         return f;
2255 }
2256
2257 /*--- sip_read: Read SIP RTP from channel */
2258 static struct ast_frame *sip_read(struct ast_channel *ast)
2259 {
2260         struct ast_frame *fr;
2261         struct sip_pvt *p = ast->pvt->pvt;
2262         ast_mutex_lock(&p->lock);
2263         fr = sip_rtp_read(ast, p);
2264         time(&p->lastrtprx);
2265         ast_mutex_unlock(&p->lock);
2266         return fr;
2267 }
2268
2269 /*--- build_callid: Build SIP CALLID header ---*/
2270 static void build_callid(char *callid, int len, struct in_addr ourip, char *fromdomain)
2271 {
2272         int res;
2273         int val;
2274         int x;
2275         char iabuf[INET_ADDRSTRLEN];
2276         for (x=0;x<4;x++) {
2277                 val = rand();
2278                 res = snprintf(callid, len, "%08x", val);
2279                 len -= res;
2280                 callid += res;
2281         }
2282         if (!ast_strlen_zero(fromdomain))
2283                 snprintf(callid, len, "@%s", fromdomain);
2284         else
2285         /* It's not important that we really use our right IP here... */
2286                 snprintf(callid, len, "@%s", ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));
2287 }
2288
2289 /*--- sip_alloc: Allocate SIP_PVT structure and set defaults ---*/
2290 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobal_nat)
2291 {
2292         struct sip_pvt *p;
2293
2294         p = malloc(sizeof(struct sip_pvt));
2295         if (!p)
2296                 return NULL;
2297         /* Keep track of stuff */
2298         memset(p, 0, sizeof(struct sip_pvt));
2299         ast_mutex_init(&p->lock);
2300
2301         p->initid = -1;
2302         p->autokillid = -1;
2303         p->stateid = -1;
2304         p->prefs = prefs;
2305 #ifdef OSP_SUPPORT
2306         p->osphandle = -1;
2307 #endif  
2308         if (sin) {
2309                 memcpy(&p->sa, sin, sizeof(p->sa));
2310                 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
2311                         memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2312         } else {
2313                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2314         }
2315         p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2316         if (videosupport)
2317                 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2318         p->branch = rand();     
2319         p->tag = rand();
2320         
2321         /* Start with 101 instead of 1 */
2322         p->ocseq = 101;
2323         if (!p->rtp) {
2324                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
2325                 ast_mutex_destroy(&p->lock);
2326                 if(p->vars) {
2327                         ast_destroy_realtime(p->vars);
2328                         p->vars = NULL;
2329                 }
2330                 free(p);
2331                 return NULL;
2332         }
2333         ast_rtp_settos(p->rtp, tos);
2334         if (p->vrtp)
2335                 ast_rtp_settos(p->vrtp, tos);
2336         if (useglobal_nat && sin) {
2337                 /* Setup NAT structure according to global settings if we have an address */
2338                 ast_copy_flags(p, &global_flags, SIP_NAT);
2339                 memcpy(&p->recv, sin, sizeof(p->recv));
2340                 ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
2341                 if (p->vrtp)
2342                         ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
2343         }
2344
2345         strncpy(p->fromdomain, default_fromdomain, sizeof(p->fromdomain) - 1);
2346         build_via(p, p->via, sizeof(p->via));
2347         if (!callid)
2348                 build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
2349         else
2350                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
2351         ast_copy_flags(p, (&global_flags), SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_DTMF | SIP_REINVITE | SIP_PROG_INBAND | SIP_OSPAUTH);
2352         /* Assign default music on hold class */
2353         strncpy(p->musicclass, global_musicclass, sizeof(p->musicclass) - 1);
2354         p->rtptimeout = global_rtptimeout;
2355         p->rtpholdtimeout = global_rtpholdtimeout;
2356         p->rtpkeepalive = global_rtpkeepalive;
2357         p->capability = global_capability;
2358         if (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833)
2359                 p->noncodeccapability |= AST_RTP_DTMF;
2360         strncpy(p->context, default_context, sizeof(p->context) - 1);
2361         /* Add to list */
2362         ast_mutex_lock(&iflock);
2363         p->next = iflist;
2364         iflist = p;
2365         ast_mutex_unlock(&iflock);
2366         if (option_debug)
2367                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
2368         return p;
2369 }
2370
2371 /*--- find_call: Connect incoming SIP message to current call or create new call structure */
2372 /*               Called by handle_request ,sipsock_read */
2373 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
2374 {
2375         struct sip_pvt *p;
2376         char *callid;
2377         char tmp[256] = "";
2378         char iabuf[INET_ADDRSTRLEN];
2379         char *cmd;
2380         char *tag = "", *c;
2381
2382         callid = get_header(req, "Call-ID");
2383
2384         if (pedanticsipchecking) {
2385                 /* In principle Call-ID's uniquely identify a call, however some vendors
2386                    (i.e. Pingtel) send multiple calls with the same Call-ID and different
2387                    tags in order to simplify billing.  The RFC does state that we have to
2388                    compare tags in addition to the call-id, but this generate substantially
2389                    more overhead which is totally unnecessary for the vast majority of sane
2390                    SIP implementations, and thus Asterisk does not enable this behavior
2391                    by default. Short version: You'll need this option to support conferencing
2392                    on the pingtel */
2393                 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
2394                 cmd = tmp;
2395                 c = strchr(tmp, ' ');
2396                 if (c)
2397                         *c = '\0';
2398                 if (!strcasecmp(cmd, "SIP/2.0"))
2399                         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2400                 else
2401                         strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
2402                 tag = strstr(tmp, "tag=");
2403                 if (tag) {
2404                         tag += 4;
2405                         c = strchr(tag, ';');
2406                         if (c)
2407                                 *c = '\0';
2408                 }
2409                         
2410         }
2411                 
2412         if (ast_strlen_zero(callid)) {
2413                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
2414                 return NULL;
2415         }
2416         ast_mutex_lock(&iflock);
2417         p = iflist;
2418         while(p) {
2419                 if (!strcmp(p->callid, callid) && 
2420                         (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) {
2421                         /* Found the call */
2422                         ast_mutex_lock(&p->lock);
2423                         ast_mutex_unlock(&iflock);
2424                         return p;
2425                 }
2426                 p = p->next;
2427         }
2428         ast_mutex_unlock(&iflock);
2429         p = sip_alloc(callid, sin, 1);
2430         if (p)
2431                 ast_mutex_lock(&p->lock);
2432         return p;
2433 }
2434
2435 /*--- sip_register: Parse register=> line in sip.conf and add to registry */
2436 static int sip_register(char *value, int lineno)
2437 {
2438         struct sip_registry *reg;
2439         char copy[256] = "";
2440         char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
2441         char *porta=NULL;
2442         char *contact=NULL;
2443         char *stringp=NULL;
2444         
2445         if (!value)
2446                 return -1;
2447         strncpy(copy, value, sizeof(copy)-1);
2448         stringp=copy;
2449         username = stringp;
2450         hostname = strrchr(stringp, '@');
2451         if (hostname) {
2452                 *hostname = '\0';
2453                 hostname++;
2454         }
2455         if (!username || ast_strlen_zero(username) || !hostname || ast_strlen_zero(hostname)) {
2456                 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
2457                 return -1;
2458         }
2459         stringp=username;
2460         username = strsep(&stringp, ":");
2461         if (username) {
2462                 secret = strsep(&stringp, ":");
2463                 if (secret) 
2464                         authuser = strsep(&stringp, ":");
2465         }
2466         stringp = hostname;
2467         hostname = strsep(&stringp, "/");
2468         if (hostname) 
2469                 contact = strsep(&stringp, "/");
2470         if (!contact || ast_strlen_zero(contact))
2471                 contact = "s";
2472         stringp=hostname;
2473         hostname = strsep(&stringp, ":");
2474         porta = strsep(&stringp, ":");
2475         
2476         if (porta && !atoi(porta)) {
2477                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
2478                 return -1;
2479         }
2480         reg = malloc(sizeof(struct sip_registry));
2481         if (reg) {
2482                 memset(reg, 0, sizeof(struct sip_registry));
2483                 regobjs++;
2484                 ASTOBJ_INIT(reg);
2485                 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
2486                 if (username)
2487                         strncpy(reg->username, username, sizeof(reg->username)-1);
2488                 if (hostname)
2489                         strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
2490                 if (authuser)
2491                         strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
2492                 if (secret)
2493                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
2494                 reg->expire = -1;
2495                 reg->timeout =  -1;
2496                 reg->refresh = default_expiry;
2497                 reg->portno = porta ? atoi(porta) : 0;
2498                 reg->callid_valid = 0;
2499                 reg->ocseq = 101;
2500                 ASTOBJ_CONTAINER_LINK(&regl, reg);
2501                 ASTOBJ_UNREF(reg,sip_registry_destroy);
2502         } else {
2503                 ast_log(LOG_ERROR, "Out of memory\n");
2504                 return -1;
2505         }
2506         return 0;
2507 }
2508
2509 /*--- lws2sws: Parse multiline SIP headers into one header */
2510 /* This is enabled if pedanticsipchecking is enabled */
2511 static int lws2sws(char *msgbuf, int len) 
2512
2513         int h = 0, t = 0; 
2514         int lws = 0; 
2515
2516         for (; h < len;) { 
2517                 /* Eliminate all CRs */ 
2518                 if (msgbuf[h] == '\r') { 
2519                         h++; 
2520                         continue; 
2521                 } 
2522                 /* Check for end-of-line */ 
2523                 if (msgbuf[h] == '\n') { 
2524                         /* Check for end-of-message */ 
2525                         if (h + 1 == len) 
2526                                 break; 
2527                         /* Check for a continuation line */ 
2528                         if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
2529                                 /* Merge continuation line */ 
2530                                 h++; 
2531                                 continue; 
2532                         } 
2533                         /* Propagate LF and start new line */ 
2534                         msgbuf[t++] = msgbuf[h++]; 
2535                         lws = 0;
2536                         continue; 
2537                 } 
2538                 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
2539                         if (lws) { 
2540                                 h++; 
2541                                 continue; 
2542                         } 
2543                         msgbuf[t++] = msgbuf[h++]; 
2544                         lws = 1; 
2545                         continue; 
2546                 } 
2547                 msgbuf[t++] = msgbuf[h++]; 
2548                 if (lws) 
2549                         lws = 0; 
2550         } 
2551         msgbuf[t] = '\0'; 
2552         return t; 
2553 }
2554
2555 /*--- parse: Parse a SIP message ----*/
2556 static void parse(struct sip_request *req)
2557 {
2558         /* Divide fields by NULL's */
2559         char *c;
2560         int f = 0;
2561         c = req->data;
2562
2563         /* First header starts immediately */
2564         req->header[f] = c;
2565         while(*c) {
2566                 if (*c == '\n') {
2567                         /* We've got a new header */
2568                         *c = 0;
2569
2570 #if 0
2571                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
2572 #endif                  
2573                         if (ast_strlen_zero(req->header[f])) {
2574                                 /* Line by itself means we're now in content */
2575                                 c++;
2576                                 break;
2577                         }
2578                         if (f >= SIP_MAX_HEADERS - 1) {
2579                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
2580                         } else
2581                                 f++;
2582                         req->header[f] = c + 1;
2583                 } else if (*c == '\r') {
2584                         /* Ignore but eliminate \r's */
2585                         *c = 0;
2586                 }
2587                 c++;
2588         }
2589         /* Check for last header */
2590         if (!ast_strlen_zero(req->header[f])) 
2591                 f++;
2592         req->headers = f;
2593         /* Now we process any mime content */
2594         f = 0;
2595         req->line[f] = c;
2596         while(*c) {
2597                 if (*c == '\n') {
2598                         /* We've got a new line */
2599                         *c = 0;
2600 #if 0
2601                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
2602 #endif                  
2603                         if (f >= SIP_MAX_LINES - 1) {
2604                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
2605                         } else
2606                                 f++;
2607                         req->line[f] = c + 1;
2608                 } else if (*c == '\r') {
2609                         /* Ignore and eliminate \r's */
2610                         *c = 0;
2611                 }
2612                 c++;
2613         }
2614         /* Check for last line */
2615         if (!ast_strlen_zero(req->line[f])) 
2616                 f++;
2617         req->lines = f;
2618         if (*c) 
2619                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
2620 }
2621
2622 /*--- process_sdp: Process SIP SDP ---*/
2623 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
2624 {
2625         char *m;
2626         char *c;
2627         char *a;
2628         char host[258];
2629         char iabuf[INET_ADDRSTRLEN];
2630         int len = -1;
2631         int portno=0;
2632         int vportno=0;
2633         int peercapability, peernoncodeccapability;
2634         int vpeercapability=0, vpeernoncodeccapability=0;
2635         struct sockaddr_in sin;
2636         char *codecs;
2637         struct hostent *hp;
2638         struct ast_hostent ahp;
2639         int codec;
2640         int destiterator = 0;
2641         int iterator;
2642         int sendonly = 0;
2643         int x,y;
2644         int debug=sip_debug_test_pvt(p);
2645
2646         /* Update our last rtprx when we receive an SDP, too */
2647         time(&p->lastrtprx);
2648         time(&p->lastrtptx);
2649
2650         /* Get codec and RTP info from SDP */
2651         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
2652                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
2653                 return -1;
2654         }
2655         m = get_sdp(req, "m");
2656         sdpLineNum_iterator_init(&destiterator);
2657         c = get_sdp_iterate(&destiterator, req, "c");
2658         if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
2659                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
2660                 return -1;
2661         }
2662         if (sscanf(c, "IN IP4 %256s", host) != 1) {
2663                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
2664                 return -1;
2665         }
2666         /* XXX This could block for a long time, and block the main thread! XXX */
2667         hp = ast_gethostbyname(host, &ahp);
2668         if (!hp) {
2669                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
2670                 return -1;
2671         }
2672         sdpLineNum_iterator_init(&iterator);
2673         ast_set_flag(p, SIP_NOVIDEO);   
2674         while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
2675                 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1) ||
2676                     (sscanf(m, "audio %d/%d RTP/AVP %n", &x, &y, &len) == 2)) {
2677                         portno = x;
2678                         /* Scan through the RTP payload types specified in a "m=" line: */
2679                         ast_rtp_pt_clear(p->rtp);
2680                         codecs = m + len;
2681                         while(!ast_strlen_zero(codecs)) {
2682                                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2683                                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2684                                         return -1;
2685                                 }
2686                                 if (debug)
2687                                         ast_verbose("Found RTP audio format %d\n", codec);
2688                                 ast_rtp_set_m_type(p->rtp, codec);
2689                                 codecs += len;
2690                                 /* Skip over any whitespace */
2691                                 while(*codecs && (*codecs < 33)) codecs++;
2692                         }
2693                 }
2694                 if (p->vrtp)
2695                         ast_rtp_pt_clear(p->vrtp);  /* Must be cleared in case no m=video line exists */
2696
2697                 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
2698                         ast_clear_flag(p, SIP_NOVIDEO); 
2699                         vportno = x;
2700                         /* Scan through the RTP payload types specified in a "m=" line: */
2701                         codecs = m + len;
2702                         while(!ast_strlen_zero(codecs)) {
2703                                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2704                                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2705                                         return -1;
2706                                 }
2707                                 if (debug)
2708                                         ast_verbose("Found video format %s\n", ast_getformatname(codec));
2709                                 ast_rtp_set_m_type(p->vrtp, codec);
2710                                 codecs += len;
2711                                 /* Skip over any whitespace */
2712                                 while(*codecs && (*codecs < 33)) codecs++;
2713                         }
2714                 }
2715         }
2716         /* Check for Media-description-level-address for audio */
2717         if (pedanticsipchecking) {
2718                 c = get_sdp_iterate(&destiterator, req, "c");
2719                 if (!ast_strlen_zero(c)) {
2720                         if (sscanf(c, "IN IP4 %256s", host) != 1) {
2721                                 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
2722                         } else {
2723                                 /* XXX This could block for a long time, and block the main thread! XXX */
2724                                 hp = ast_gethostbyname(host, &ahp);
2725                                 if (!hp) {
2726                                         ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
2727                                 }
2728                         }
2729                 }
2730         }
2731         /* RTP addresses and ports for audio and video */
2732         sin.sin_family = AF_INET;
2733         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
2734
2735         /* Setup audio port number */
2736         sin.sin_port = htons(portno);
2737         if (p->rtp && sin.sin_port) {
2738                 ast_rtp_set_peer(p->rtp, &sin);
2739                 if (debug) {
2740                         ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
2741                         ast_log(LOG_DEBUG,"Peer audio RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
2742                 }
2743         }
2744         /* Check for Media-description-level-address for video */
2745         if (pedanticsipchecking) {
2746                 c = get_sdp_iterate(&destiterator, req, "c");
2747                 if (!ast_strlen_zero(c)) {
2748                         if (sscanf(c, "IN IP4 %256s", host) != 1) {
2749                                 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
2750                         } else {
2751                                 /* XXX This could block for a long time, and block the main thread! XXX */
2752                                 hp = ast_gethostbyname(host, &ahp);
2753                                 if (!hp) {
2754                                         ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
2755                                 }
2756                         }
2757                 }
2758         }
2759         /* Setup video port number */
2760         sin.sin_port = htons(vportno);
2761         if (p->vrtp && sin.sin_port) {
2762                 ast_rtp_set_peer(p->vrtp, &sin);
2763                 if (debug) {
2764                         ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
2765                         ast_log(LOG_DEBUG,"Peer video RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
2766                 }
2767         }
2768
2769         /* Next, scan through each "a=rtpmap:" line, noting each
2770          * specified RTP payload type (with corresponding MIME subtype):
2771          */
2772         sdpLineNum_iterator_init(&iterator);
2773         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
2774       char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
2775           if (!strcasecmp(a, "sendonly")) {
2776                 sendonly=1;
2777                 continue;
2778           }
2779           if (!strcasecmp(a, "sendrecv")) {
2780                 sendonly=0;
2781           }
2782           if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
2783           if (debug)
2784                 ast_verbose("Found description format %s\n", mimeSubtype);
2785           /* Note: should really look at the 'freq' and '#chans' params too */
2786           ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
2787           if (p->vrtp)
2788                   ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
2789         }
2790
2791         /* Now gather all of the codecs that were asked for: */
2792         ast_rtp_get_current_formats(p->rtp,
2793                                 &peercapability, &peernoncodeccapability);
2794         if (p->vrtp)
2795                 ast_rtp_get_current_formats(p->vrtp,
2796                                 &vpeercapability, &vpeernoncodeccapability);
2797         p->jointcapability = p->capability & (peercapability | vpeercapability);
2798         p->peercapability = (peercapability | vpeercapability);
2799         p->noncodeccapability = noncodeccapability & peernoncodeccapability;
2800         
2801         if (debug) {
2802                 /* shame on whoever coded this.... */
2803                 const unsigned slen=512;
2804                 char s1[slen], s2[slen], s3[slen], s4[slen];
2805
2806                 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
2807                         ast_getformatname_multiple(s1, slen, p->capability),
2808                         ast_getformatname_multiple(s2, slen, peercapability),
2809                         ast_getformatname_multiple(s3, slen, vpeercapability),
2810                         ast_getformatname_multiple(s4, slen, p->jointcapability));
2811
2812                 ast_verbose("Non-codec capabilities: us - %s, peer - %s, combined - %s\n",
2813                         ast_getformatname_multiple(s1, slen, noncodeccapability),
2814                         ast_getformatname_multiple(s2, slen, peernoncodeccapability),
2815                         ast_getformatname_multiple(s3, slen, p->noncodeccapability));
2816         }
2817         if (!p->jointcapability) {
2818                 ast_log(LOG_WARNING, "No compatible codecs!\n");
2819                 return -1;
2820         }
2821         if (p->owner) {
2822                 if (!(p->owner->nativeformats & p->jointcapability)) {
2823                         const unsigned slen=512;
2824                         char s1[slen], s2[slen];
2825                         ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %s and not %s\n", 
2826                                         ast_getformatname_multiple(s1, slen, p->jointcapability),
2827                                         ast_getformatname_multiple(s2, slen, p->owner->nativeformats));
2828                         p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1);
2829                         ast_set_read_format(p->owner, p->owner->readformat);
2830                         ast_set_write_format(p->owner, p->owner->writeformat);
2831                 }
2832                 if (ast_bridged_channel(p->owner)) {
2833                         /* Turn on/off music on hold if we are holding/unholding */
2834                         if (sin.sin_addr.s_addr && !sendonly) {
2835                                 ast_moh_stop(ast_bridged_channel(p->owner));
2836                         } else {
2837                                 ast_moh_start(ast_bridged_channel(p->owner), NULL);
2838                                 if (sendonly)
2839                                         ast_rtp_stop(p->rtp);
2840                         }
2841                 }
2842         }
2843         return 0;
2844         
2845 }
2846
2847 /*--- add_header: Add header to SIP message */
2848 static int add_header(struct sip_request *req, char *var, char *value)
2849 {
2850         int x = 0;
2851         char *shortname = "";
2852         if (req->len >= sizeof(req->data) - 4) {
2853                 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
2854                 return -1;
2855         }
2856         if (req->lines) {
2857                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2858                 return -1;
2859         }
2860
2861         req->header[req->headers] = req->data + req->len;
2862         if (compactheaders) {
2863                 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
2864                         if (!strcasecmp(aliases[x].fullname, var))
2865                                 shortname = aliases[x].shortname;
2866         }
2867         if(!ast_strlen_zero(shortname)) {
2868                 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", shortname, value);
2869         } else {
2870                 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
2871         }
2872         req->len += strlen(req->header[req->headers]);
2873         if (req->headers < SIP_MAX_HEADERS)
2874                 req->headers++;
2875         else {
2876                 ast_log(LOG_WARNING, "Out of header space\n");
2877                 return -1;
2878         }
2879         return 0;       
2880 }
2881
2882 /*--- add_blank_header: Add blank header to SIP message */
2883 static int add_blank_header(struct sip_request *req)
2884 {
2885         if (req->len >= sizeof(req->data) - 4) {
2886                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2887                 return -1;
2888         }
2889         if (req->lines) {
2890                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2891                 return -1;
2892         }
2893         req->header[req->headers] = req->data + req->len;
2894         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
2895         req->len += strlen(req->header[req->headers]);
2896         if (req->headers < SIP_MAX_HEADERS)
2897                 req->headers++;
2898         else {
2899                 ast_log(LOG_WARNING, "Out of header space\n");
2900                 return -1;
2901         }
2902         return 0;       
2903 }
2904
2905 /*--- add_line: Add content (not header) to SIP message */
2906 static int add_line(struct sip_request *req, char *line)
2907 {
2908         if (req->len >= sizeof(req->data) - 4) {
2909                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2910                 return -1;
2911         }
2912         if (!req->lines) {
2913                 /* Add extra empty return */
2914                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2915                 req->len += strlen(req->data + req->len);
2916         }
2917         req->line[req->lines] = req->data + req->len;
2918         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
2919         req->len += strlen(req->line[req->lines]);
2920         if (req->lines < SIP_MAX_LINES)
2921                 req->lines++;
2922         else {
2923                 ast_log(LOG_WARNING, "Out of line space\n");
2924                 return -1;
2925         }
2926         return 0;       
2927 }
2928
2929 /*--- copy_header: Copy one header field from one request to another */
2930 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
2931 {
2932         char *tmp;
2933         tmp = get_header(orig, field);
2934         if (!ast_strlen_zero(tmp)) {
2935                 /* Add what we're responding to */
2936                 return add_header(req, field, tmp);
2937         }
2938         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2939         return -1;
2940 }
2941
2942 /*--- copy_all_header: Copy all headers from one request to another ---*/
2943 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
2944 {
2945         char *tmp;
2946         int start = 0;
2947         int copied = 0;
2948         for (;;) {
2949                 tmp = __get_header(orig, field, &start);
2950                 if (!ast_strlen_zero(tmp)) {
2951                         /* Add what we're responding to */
2952                         add_header(req, field, tmp);
2953                         copied++;
2954                 } else
2955                         break;
2956         }
2957         return copied ? 0 : -1;
2958 }
2959
2960 /*--- copy_via_headers: Copy SIP VIA Headers from one request to another ---*/
2961 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
2962 {
2963         char tmp[256]="", *oh, *end;
2964         int start = 0;
2965         int copied = 0;
2966         char new[256];
2967         char iabuf[INET_ADDRSTRLEN];
2968         for (;;) {
2969                 oh = __get_header(orig, field, &start);
2970                 if (!ast_strlen_zero(oh)) {
2971                         /* Strip ;rport */
2972                         strncpy(tmp, oh, sizeof(tmp) - 1);
2973                         oh = strstr(tmp, ";rport");
2974                         if (oh) {
2975                                 end = strchr(oh + 1, ';');
2976                                 if (end)
2977                                         memmove(oh, end, strlen(end) + 1);
2978                                 else
2979                                         *oh = '\0';
2980                         }
2981                         if (!copied && (ast_test_flag(p, SIP_NAT) == SIP_NAT_ALWAYS)) {
2982                                 /* Whoo hoo!  Now we can indicate port address translation too!  Just
2983                                    another RFC (RFC3581). I'll leave the original comments in for
2984                                    posterity.  */
2985                                 snprintf(new, sizeof(new), "%s;received=%s;rport=%d", tmp, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
2986                                 add_header(req, field, new);
2987                         } else {
2988                                 /* Add what we're responding to */
2989                                 add_header(req, field, tmp);
2990                         }
2991                         copied++;
2992                 } else
2993                         break;