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