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