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