minor logic simplification in get_sip_pvt_byid_locked()
[asterisk/asterisk.git] / channels / chan_sip.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  * \brief Implementation of Session Initiation Protocol
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * See Also:
26  * \arg \ref AstCREDITS
27  *
28  * Implementation of RFC 3261 - without S/MIME, TCP and TLS support
29  * Configuration file \link Config_sip sip.conf \endlink
30  *
31  *
32  * \todo SIP over TCP
33  * \todo SIP over TLS
34  * \todo Better support of forking
35  * \todo VIA branch tag transaction checking
36  * \todo Transaction support
37  *
38  * \ingroup channel_drivers
39  *
40  * \par Overview of the handling of SIP sessions
41  * The SIP channel handles several types of SIP sessions, or dialogs,
42  * not all of them being "telephone calls".
43  * - Incoming calls that will be sent to the PBX core
44  * - Outgoing calls, generated by the PBX
45  * - SIP subscriptions and notifications of states and voicemail messages
46  * - SIP registrations, both inbound and outbound
47  * - SIP peer management (peerpoke, OPTIONS)
48  * - SIP text messages
49  *
50  * In the SIP channel, there's a list of active SIP dialogs, which includes
51  * all of these when they are active. "sip show channels" in the CLI will
52  * show most of these, excluding subscriptions which are shown by
53  * "sip show subscriptions"
54  *
55  * \par incoming packets
56  * Incoming packets are received in the monitoring thread, then handled by
57  * sipsock_read(). This function parses the packet and matches an existing
58  * dialog or starts a new SIP dialog.
59  * 
60  * sipsock_read sends the packet to handle_request(), that parses a bit more.
61  * if it's a response to an outbound request, it's sent to handle_response().
62  * If it is a request, handle_request sends it to one of a list of functions
63  * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
64  * sipsock_read locks the ast_channel if it exists (an active call) and
65  * unlocks it after we have processed the SIP message.
66  *
67  * A new INVITE is sent to handle_request_invite(), that will end up
68  * starting a new channel in the PBX, the new channel after that executing
69  * in a separate channel thread. This is an incoming "call".
70  * When the call is answered, either by a bridged channel or the PBX itself
71  * the sip_answer() function is called.
72  *
73  * The actual media - Video or Audio - is mostly handled by the RTP subsystem
74  * in rtp.c 
75  * 
76  * \par Outbound calls
77  * Outbound calls are set up by the PBX through the sip_request_call()
78  * function. After that, they are activated by sip_call().
79  * 
80  * \par Hanging up
81  * The PBX issues a hangup on both incoming and outgoing calls through
82  * the sip_hangup() function
83  *
84  */
85
86
87 #include <stdio.h>
88 #include <ctype.h>
89 #include <string.h>
90 #include <unistd.h>
91 #include <sys/socket.h>
92 #include <sys/ioctl.h>
93 #include <net/if.h>
94 #include <errno.h>
95 #include <stdlib.h>
96 #include <fcntl.h>
97 #include <netdb.h>
98 #include <signal.h>
99 #include <sys/signal.h>
100 #include <netinet/in.h>
101 #include <netinet/in_systm.h>
102 #include <arpa/inet.h>
103 #include <netinet/ip.h>
104 #include <regex.h>
105
106 #include "asterisk.h"
107
108 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
109
110 #include "asterisk/lock.h"
111 #include "asterisk/channel.h"
112 #include "asterisk/config.h"
113 #include "asterisk/logger.h"
114 #include "asterisk/module.h"
115 #include "asterisk/pbx.h"
116 #include "asterisk/options.h"
117 #include "asterisk/lock.h"
118 #include "asterisk/sched.h"
119 #include "asterisk/io.h"
120 #include "asterisk/rtp.h"
121 #include "asterisk/acl.h"
122 #include "asterisk/manager.h"
123 #include "asterisk/callerid.h"
124 #include "asterisk/cli.h"
125 #include "asterisk/app.h"
126 #include "asterisk/musiconhold.h"
127 #include "asterisk/dsp.h"
128 #include "asterisk/features.h"
129 #include "asterisk/acl.h"
130 #include "asterisk/srv.h"
131 #include "asterisk/astdb.h"
132 #include "asterisk/causes.h"
133 #include "asterisk/utils.h"
134 #include "asterisk/file.h"
135 #include "asterisk/astobj.h"
136 #include "asterisk/dnsmgr.h"
137 #include "asterisk/devicestate.h"
138 #include "asterisk/linkedlists.h"
139 #include "asterisk/stringfields.h"
140 #include "asterisk/monitor.h"
141 #include "asterisk/localtime.h"
142
143 #ifndef FALSE
144 #define FALSE   0
145 #endif
146
147 #ifndef TRUE
148 #define TRUE 1
149 #endif
150
151 #define VIDEO_CODEC_MASK        0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
152 #ifndef IPTOS_MINCOST
153 #define IPTOS_MINCOST           0x02
154 #endif
155
156 /* #define VOCAL_DATA_HACK */
157
158 #define DEFAULT_DEFAULT_EXPIRY  120
159 #define DEFAULT_MIN_EXPIRY      60
160 #define DEFAULT_MAX_EXPIRY      3600
161 #define DEFAULT_REGISTRATION_TIMEOUT    20
162 #define DEFAULT_MAX_FORWARDS    "70"
163
164 /* guard limit must be larger than guard secs */
165 /* guard min must be < 1000, and should be >= 250 */
166 #define EXPIRY_GUARD_SECS       15              /*!< How long before expiry do we reregister */
167 #define EXPIRY_GUARD_LIMIT      30              /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
168                                                   EXPIRY_GUARD_SECS */
169 #define EXPIRY_GUARD_MIN        500             /*!< This is the minimum guard time applied. If 
170                                                   GUARD_PCT turns out to be lower than this, it 
171                                                    will use this time instead.
172                                                    This is in milliseconds. */
173 #define EXPIRY_GUARD_PCT        0.20            /*!< Percentage of expires timeout to use when 
174                                                    below EXPIRY_GUARD_LIMIT */
175 #define DEFAULT_EXPIRY 900                      /*!< Expire slowly */
176
177 static int min_expiry = DEFAULT_MIN_EXPIRY;     /*!< Minimum accepted registration time */
178 static int max_expiry = DEFAULT_MAX_EXPIRY;     /*!< Maximum accepted registration time */
179 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
180 static int expiry = DEFAULT_EXPIRY;
181
182 #ifndef MAX
183 #define MAX(a,b) ((a) > (b) ? (a) : (b))
184 #endif
185
186 #define CALLERID_UNKNOWN        "Unknown"
187
188 #define DEFAULT_MAXMS           2000            /*!< Qualification: Must be faster than 2 seconds by default */
189 #define DEFAULT_FREQ_OK         60 * 1000       /*!< Qualification: How often to check for the host to be up */
190 #define DEFAULT_FREQ_NOTOK      10 * 1000       /*!< Qualification: How often to check, if the host is down... */
191
192 #define DEFAULT_RETRANS         1000            /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
193 #define MAX_RETRANS             6               /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
194 #define SIP_TRANS_TIMEOUT       32000           /*!< SIP request timeout (rfc 3261) 64*T1 
195                                                 \todo Use known T1 for timeout (peerpoke)
196                                                 */
197 #define MAX_AUTHTRIES           3               /*!< Try authentication three times, then fail */
198
199 #define SIP_MAX_HEADERS         64                      /*!< Max amount of SIP headers to read */
200 #define SIP_MAX_LINES           64                      /*!< Max amount of lines in SIP attachment (like SDP) */
201 #define SIP_MAX_PACKET          4096    /*!< Also from RFC 3261 (2543), should sub headers tho */
202
203 #define INITIAL_CSEQ            101     /*!< our initial sip sequence number */
204
205 static const char tdesc[] = "Session Initiation Protocol (SIP)";
206 static const char config[] = "sip.conf";
207 static const char notify_config[] = "sip_notify.conf";
208 static int usecnt = 0;
209
210
211 #define RTP     1
212 #define NO_RTP  0
213
214 /*! \brief Authorization scheme for call transfers 
215 \note Not a bitfield flag, since there are plans for other modes,
216         like "only allow transfers for authenticated devices" */
217 enum transfermodes {
218         TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
219         TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
220 };
221
222
223 /* Do _NOT_ make any changes to this enum, or the array following it;
224    if you think you are doing the right thing, you are probably
225    not doing the right thing. If you think there are changes
226    needed, get someone else to review them first _before_
227    submitting a patch. If these two lists do not match properly
228    bad things will happen.
229 */
230
231 enum xmittype {
232         XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
233                                                         If it fails, it's critical and will cause a teardown of the session */
234         XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
235         XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
236 };
237
238 enum subscriptiontype { 
239         NONE = 0,
240         TIMEOUT,
241         XPIDF_XML,
242         DIALOG_INFO_XML,
243         CPIM_PIDF_XML,
244         PIDF_XML,
245         MWI_NOTIFICATION
246 };
247
248 static const struct cfsubscription_types {
249         enum subscriptiontype type;
250         const char * const event;
251         const char * const mediatype;
252         const char * const text;
253 } subscription_types[] = {
254         { NONE,            "-",        "unknown",                    "unknown" },
255         /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
256         { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
257         { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
258         { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
259         { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
260         { MWI_NOTIFICATION,     "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
261 };
262
263 enum sipmethod {
264         SIP_UNKNOWN,
265         SIP_RESPONSE,
266         SIP_REGISTER,
267         SIP_OPTIONS,
268         SIP_NOTIFY,
269         SIP_INVITE,
270         SIP_ACK,
271         SIP_PRACK,
272         SIP_BYE,
273         SIP_REFER,
274         SIP_SUBSCRIBE,
275         SIP_MESSAGE,
276         SIP_UPDATE,
277         SIP_INFO,
278         SIP_CANCEL,
279         SIP_PUBLISH,
280 } sip_method_list;
281
282 enum sip_auth_type {
283         PROXY_AUTH,
284         WWW_AUTH,
285 };
286
287 /* States for outbound registrations (with register= lines in sip.conf */
288 enum sipregistrystate {
289         REG_STATE_UNREGISTERED = 0,     /*!< We are not registred */
290         REG_STATE_REGSENT,      /*!< Registration request sent */
291         REG_STATE_AUTHSENT,     /*!< We have tried to authenticate */
292         REG_STATE_REGISTERED,   /*!< Registred and done */
293         REG_STATE_REJECTED,     /*!< Registration rejected */
294         REG_STATE_TIMEOUT,      /*!< Registration timed out */
295         REG_STATE_NOAUTH,       /*!< We have no accepted credentials */
296         REG_STATE_FAILED,       /*!< Registration failed after several tries */
297 };
298
299
300 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
301 static const struct  cfsip_methods { 
302         enum sipmethod id;
303         int need_rtp;           /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
304         char * const text;
305 } sip_methods[] = {
306         { SIP_UNKNOWN,   RTP,    "-UNKNOWN-" },
307         { SIP_RESPONSE,  NO_RTP, "SIP/2.0" },
308         { SIP_REGISTER,  NO_RTP, "REGISTER" },
309         { SIP_OPTIONS,   NO_RTP, "OPTIONS" },
310         { SIP_NOTIFY,    NO_RTP, "NOTIFY" },
311         { SIP_INVITE,    RTP,    "INVITE" },
312         { SIP_ACK,       NO_RTP, "ACK" },
313         { SIP_PRACK,     NO_RTP, "PRACK" },
314         { SIP_BYE,       NO_RTP, "BYE" },
315         { SIP_REFER,     NO_RTP, "REFER" },
316         { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
317         { SIP_MESSAGE,   NO_RTP, "MESSAGE" },
318         { SIP_UPDATE,    NO_RTP, "UPDATE" },
319         { SIP_INFO,      NO_RTP, "INFO" },
320         { SIP_CANCEL,    NO_RTP, "CANCEL" },
321         { SIP_PUBLISH,   NO_RTP, "PUBLISH" }
322 };
323
324 /*!  Define SIP option tags, used in Require: and Supported: headers 
325         We need to be aware of these properties in the phones to use 
326         the replace: header. We should not do that without knowing
327         that the other end supports it... 
328         This is nothing we can configure, we learn by the dialog
329         Supported: header on the REGISTER (peer) or the INVITE
330         (other devices)
331         We are not using many of these today, but will in the future.
332         This is documented in RFC 3261
333 */
334 #define SUPPORTED               1
335 #define NOT_SUPPORTED           0
336
337 #define SIP_OPT_REPLACES        (1 << 0)
338 #define SIP_OPT_100REL          (1 << 1)
339 #define SIP_OPT_TIMER           (1 << 2)
340 #define SIP_OPT_EARLY_SESSION   (1 << 3)
341 #define SIP_OPT_JOIN            (1 << 4)
342 #define SIP_OPT_PATH            (1 << 5)
343 #define SIP_OPT_PREF            (1 << 6)
344 #define SIP_OPT_PRECONDITION    (1 << 7)
345 #define SIP_OPT_PRIVACY         (1 << 8)
346 #define SIP_OPT_SDP_ANAT        (1 << 9)
347 #define SIP_OPT_SEC_AGREE       (1 << 10)
348 #define SIP_OPT_EVENTLIST       (1 << 11)
349 #define SIP_OPT_GRUU            (1 << 12)
350 #define SIP_OPT_TARGET_DIALOG   (1 << 13)
351
352 /*! \brief List of well-known SIP options. If we get this in a require,
353    we should check the list and answer accordingly. */
354 static const struct cfsip_options {
355         int id;                 /*!< Bitmap ID */
356         int supported;          /*!< Supported by Asterisk ? */
357         char * const text;      /*!< Text id, as in standard */
358 } sip_options[] = {     /* XXX used in 3 places */
359         /* Replaces: header for transfer */
360         { SIP_OPT_REPLACES,     SUPPORTED,      "replaces" },   
361         /* One version of Polycom firmware has the wrong label */
362         { SIP_OPT_REPLACES,     SUPPORTED,      "replace" },    
363         /* RFC3262: PRACK 100% reliability */
364         { SIP_OPT_100REL,       NOT_SUPPORTED,  "100rel" },     
365         /* SIP Session Timers */
366         { SIP_OPT_TIMER,        NOT_SUPPORTED,  "timer" },
367         /* RFC3959: SIP Early session support */
368         { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
369         /* SIP Join header support */
370         { SIP_OPT_JOIN,         NOT_SUPPORTED,  "join" },
371         /* RFC3327: Path support */
372         { SIP_OPT_PATH,         NOT_SUPPORTED,  "path" },
373         /* RFC3840: Callee preferences */
374         { SIP_OPT_PREF,         NOT_SUPPORTED,  "pref" },
375         /* RFC3312: Precondition support */
376         { SIP_OPT_PRECONDITION, NOT_SUPPORTED,  "precondition" },
377         /* RFC3323: Privacy with proxies*/
378         { SIP_OPT_PRIVACY,      NOT_SUPPORTED,  "privacy" },
379         /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
380         { SIP_OPT_SDP_ANAT,     NOT_SUPPORTED,  "sdp-anat" },
381         /* RFC3329: Security agreement mechanism */
382         { SIP_OPT_SEC_AGREE,    NOT_SUPPORTED,  "sec_agree" },
383         /* SIMPLE events:  draft-ietf-simple-event-list-07.txt */
384         { SIP_OPT_EVENTLIST,    NOT_SUPPORTED,  "eventlist" },
385         /* GRUU: Globally Routable User Agent URI's */
386         { SIP_OPT_GRUU,         NOT_SUPPORTED,  "gruu" },
387         /* Target-dialog: draft-ietf-sip-target-dialog-00.txt */
388         { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,  "target-dialog" },
389 };
390
391
392 /*! \brief SIP Methods we support */
393 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
394
395 /*! \brief SIP Extensions we support */
396 #define SUPPORTED_EXTENSIONS "replaces" 
397
398
399 /* Default values, set and reset in reload_config before reading configuration */
400 /* These are default values in the source. There are other recommended values in the
401    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
402    yet encouraging new behaviour on new installations 
403  */
404 #define DEFAULT_SIP_PORT        5060    /*!< From RFC 3261 (former 2543) */
405 #define DEFAULT_CONTEXT         "default"
406 #define DEFAULT_MUSICCLASS      "default"
407 #define DEFAULT_VMEXTEN         "asterisk"
408 #define DEFAULT_CALLERID        "asterisk"
409 #define DEFAULT_NOTIFYMIME      "application/simple-message-summary"
410 #define DEFAULT_MWITIME         10
411 #define DEFAULT_ALLOWGUEST      TRUE
412 #define DEFAULT_SRVLOOKUP       FALSE           /*!< Recommended setting is ON */
413 #define DEFAULT_COMPACTHEADERS  FALSE
414 #define DEFAULT_TOS_SIP         0               /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
415 #define DEFAULT_TOS_AUDIO       0               /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
416 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
417 #define DEFAULT_ALLOW_EXT_DOM   TRUE
418 #define DEFAULT_REALM           "asterisk"
419 #define DEFAULT_NOTIFYRINGING   TRUE
420 #define DEFAULT_PEDANTIC        FALSE
421 #define DEFAULT_AUTOCREATEPEER  FALSE
422 #define DEFAULT_QUALIFY         FALSE
423 #define DEFAULT_T1MIN           100             /*!< 100 MS for minimal roundtrip time */
424 #define DEFAULT_MAX_CALL_BITRATE (384)          /*!< Max bitrate for video */
425 #ifndef DEFAULT_USERAGENT
426 #define DEFAULT_USERAGENT "Asterisk PBX"        /*!< Default Useragent: header unless re-defined in sip.conf */
427 #endif
428
429
430 /* Default setttings are used as a channel setting and as a default when
431    configuring devices */
432 static char default_context[AST_MAX_CONTEXT];
433 static char default_subscribecontext[AST_MAX_CONTEXT];
434 static char default_language[MAX_LANGUAGE];
435 static char default_callerid[AST_MAX_EXTENSION];
436 static char default_fromdomain[AST_MAX_EXTENSION];
437 static char default_notifymime[AST_MAX_EXTENSION];
438 static int default_qualify;             /*!< Default Qualify= setting */
439 static char default_vmexten[AST_MAX_EXTENSION];
440 static char default_musicclass[MAX_MUSICCLASS];         /*!< Global music on hold class */
441 static int default_maxcallbitrate;      /*!< Maximum bitrate for call */
442 static struct ast_codec_pref default_prefs;             /*!< Default codec prefs */
443
444 /* Global settings only apply to the channel */
445 static int global_rtautoclear;
446 static int global_notifyringing;        /*!< Send notifications on ringing */
447 static int srvlookup;                   /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
448 static int pedanticsipchecking;         /*!< Extra checking ?  Default off */
449 static int autocreatepeer;              /*!< Auto creation of peers at registration? Default off. */
450 static int global_relaxdtmf;                    /*!< Relax DTMF */
451 static int global_rtptimeout;           /*!< Time out call if no RTP */
452 static int global_rtpholdtimeout;
453 static int global_rtpkeepalive;         /*!< Send RTP keepalives */
454 static int global_reg_timeout;  
455 static int global_regattempts_max;      /*!< Registration attempts before giving up */
456 static int global_allowguest;           /*!< allow unauthenticated users/peers to connect? */
457 static int global_allowsubscribe;       /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
458                                             the global setting is in globals_flags[1] */
459 static int global_mwitime;              /*!< Time between MWI checks for peers */
460 static int global_tos_sip;              /*!< IP type of service for SIP packets */
461 static int global_tos_audio;            /*!< IP type of service for audio RTP packets */
462 static int global_tos_video;            /*!< IP type of service for video RTP packets */
463 static int compactheaders;              /*!< send compact sip headers */
464 static int recordhistory;               /*!< Record SIP history. Off by default */
465 static int dumphistory;                 /*!< Dump history to verbose before destroying SIP dialog */
466 static char global_realm[MAXHOSTNAMELEN];               /*!< Default realm */
467 static char global_regcontext[AST_MAX_CONTEXT];         /*!< Context for auto-extensions */
468 static char global_useragent[AST_MAX_EXTENSION];        /*!< Useragent for the SIP channel */
469 static int allow_external_domains;      /*!< Accept calls to external SIP domains? */
470 static int global_callevents;           /*!< Whether we send manager events or not */
471 static int global_t1min;                /*!< T1 roundtrip time minimum */
472 enum transfermodes global_allowtransfer;        /*! SIP Refer restriction scheme */
473
474 /*! \brief Codecs that we support by default: */
475 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
476 static int noncodeccapability = AST_RTP_DTMF;
477
478 /* Object counters */
479 static int suserobjs = 0;               /*!< Static users */
480 static int ruserobjs = 0;               /*!< Realtime users */
481 static int speerobjs = 0;               /*!< Statis peers */
482 static int rpeerobjs = 0;               /*!< Realtime peers */
483 static int apeerobjs = 0;               /*!< Autocreated peer objects */
484 static int regobjs = 0;                 /*!< Registry objects */
485
486 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
487
488 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
489
490 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
491 AST_MUTEX_DEFINE_STATIC(iflock);
492
493 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
494    when it's doing something critical. */
495 AST_MUTEX_DEFINE_STATIC(netlock);
496
497 AST_MUTEX_DEFINE_STATIC(monlock);
498
499 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
500
501 /*! \brief This is the thread for the monitor which checks for input on the channels
502    which are not currently in use.  */
503 static pthread_t monitor_thread = AST_PTHREADT_NULL;
504
505 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
506 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
507
508 static struct sched_context *sched;     /*!< The scheduling context */
509 static struct io_context *io;           /*!< The IO context */
510
511 #define DEC_CALL_LIMIT  0
512 #define INC_CALL_LIMIT  1
513
514
515 /*! \brief sip_request: The data grabbed from the UDP socket */
516 struct sip_request {
517         char *rlPart1;          /*!< SIP Method Name or "SIP/2.0" protocol version */
518         char *rlPart2;          /*!< The Request URI or Response Status */
519         int len;                /*!< Length */
520         int headers;            /*!< # of SIP Headers */
521         int method;             /*!< Method of this request */
522         int lines;              /*!< Body Content */
523         unsigned int flags;     /*!< SIP_PKT Flags for this packet */
524         char *header[SIP_MAX_HEADERS];
525         char *line[SIP_MAX_LINES];
526         char data[SIP_MAX_PACKET];
527         unsigned int sdp_start; /*!< the line number where the SDP begins */
528         unsigned int sdp_end;   /*!< the line number where the SDP ends */
529 };
530
531 /*
532  * A sip packet is stored into the data[] buffer, with the header followed
533  * by an empty line and the body of the message.
534  * On outgoing packets, data is accumulated in data[] with len reflecting
535  * the next available byte, headers and lines count the number of lines
536  * in both parts. There are no '\0' in data[0..len-1].
537  *
538  * On received packet, the input read from the socket is copied into data[],
539  * len is set and the string is NUL-terminated. Then a parser fills up
540  * the other fields -header[] and line[] to point to the lines of the
541  * message, rlPart1 and rlPart2 parse the first lnie as below:
542  *
543  * Requests have in the first line      METHOD URI SIP/2.0
544  *      rlPart1 = method; rlPart2 = uri;
545  * Responses have in the first line     SIP/2.0 code description
546  *      rlPart1 = SIP/2.0; rlPart2 = code + description;
547  *
548  */
549
550 /*! \brief structure used in transfers */
551 struct sip_dual {
552         struct ast_channel *chan1;      /*!< First channel involved */
553         struct ast_channel *chan2;      /*!< Second channel involved */
554         struct sip_request req;         /*!< Request that caused the transfer (REFER) */
555         int seqno;                      /*!< Sequence number */
556 };
557
558 struct sip_pkt;
559
560 /*! \brief Parameters to the transmit_invite function */
561 struct sip_invite_param {
562         const char *distinctive_ring;   /*!< Distinctive ring header */
563         int addsipheaders;              /*!< Add extra SIP headers */
564         const char *uri_options;        /*!< URI options to add to the URI */
565         const char *vxml_url;           /*!< VXML url for Cisco phones */
566         char *auth;                     /*!< Authentication */
567         char *authheader;               /*!< Auth header */
568         enum sip_auth_type auth_type;   /*!< Authentication type */
569         const char *replaces;           /*!< Replaces header for call transfers */
570         int transfer;                   /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
571 };
572
573 /*! \brief Structure to save routing information for a SIP session */
574 struct sip_route {
575         struct sip_route *next;
576         char hop[0];
577 };
578
579 /*! \brief Modes for SIP domain handling in the PBX */
580 enum domain_mode {
581         SIP_DOMAIN_AUTO,                /*!< This domain is auto-configured */
582         SIP_DOMAIN_CONFIG,              /*!< This domain is from configuration */
583 };
584
585 struct domain {
586         char domain[MAXHOSTNAMELEN];            /*!< SIP domain we are responsible for */
587         char context[AST_MAX_EXTENSION];        /*!< Incoming context for this domain */
588         enum domain_mode mode;                  /*!< How did we find this domain? */
589         AST_LIST_ENTRY(domain) list;            /*!< List mechanics */
590 };
591
592 static AST_LIST_HEAD_STATIC(domain_list, domain);       /*!< The SIP domain list */
593
594
595 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
596 struct sip_history {
597         AST_LIST_ENTRY(sip_history) list;
598         char event[0];  /* actually more, depending on needs */
599 };
600
601 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
602
603 /*! \brief sip_auth: Creadentials for authentication to other SIP services */
604 struct sip_auth {
605         char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
606         char username[256];             /*!< Username */
607         char secret[256];               /*!< Secret */
608         char md5secret[256];            /*!< MD5Secret */
609         struct sip_auth *next;          /*!< Next auth structure in list */
610 };
611
612 /*--- Various flags for the flags field in the pvt structure */
613 #define SIP_ALREADYGONE         (1 << 0)        /*!< Whether or not we've already been destroyed by our peer */
614 #define SIP_NEEDDESTROY         (1 << 1)        /*!< if we need to be destroyed by the monitor thread */
615 #define SIP_NOVIDEO             (1 << 2)        /*!< Didn't get video in invite, don't offer */
616 #define SIP_RINGING             (1 << 3)        /*!< Have sent 180 ringing */
617 #define SIP_PROGRESS_SENT       (1 << 4)        /*!< Have sent 183 message progress */
618 #define SIP_NEEDREINVITE        (1 << 5)        /*!< Do we need to send another reinvite? */
619 #define SIP_PENDINGBYE          (1 << 6)        /*!< Need to send bye after we ack? */
620 #define SIP_GOTREFER            (1 << 7)        /*!< Got a refer? */
621 #define SIP_PROMISCREDIR        (1 << 8)        /*!< Promiscuous redirection */
622 #define SIP_TRUSTRPID           (1 << 9)        /*!< Trust RPID headers? */
623 #define SIP_USEREQPHONE         (1 << 10)       /*!< Add user=phone to numeric URI. Default off */
624 #define SIP_REALTIME            (1 << 11)       /*!< Flag for realtime users */
625 #define SIP_USECLIENTCODE       (1 << 12)       /*!< Trust X-ClientCode info message */
626 #define SIP_OUTGOING            (1 << 13)       /*!< Is this an outgoing call? */
627 #define SIP_FREEBIT             (1 << 14)       /*!< Free for session-related use */
628 #define SIP_FREEBIT3            (1 << 15)       /*!< Free for session-related use */
629 #define SIP_DTMF                (3 << 16)       /*!< DTMF Support: four settings, uses two bits */
630 #define SIP_DTMF_RFC2833        (0 << 16)       /*!< DTMF Support: RTP DTMF - "rfc2833" */
631 #define SIP_DTMF_INBAND         (1 << 16)       /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
632 #define SIP_DTMF_INFO           (2 << 16)       /*!< DTMF Support: SIP Info messages - "info" */
633 #define SIP_DTMF_AUTO           (3 << 16)       /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
634 /* NAT settings */
635 #define SIP_NAT                 (3 << 18)       /*!< four settings, uses two bits */
636 #define SIP_NAT_NEVER           (0 << 18)       /*!< No nat support */
637 #define SIP_NAT_RFC3581         (1 << 18)       /*!< NAT RFC3581 */
638 #define SIP_NAT_ROUTE           (2 << 18)       /*!< NAT Only ROUTE */
639 #define SIP_NAT_ALWAYS          (3 << 18)       /*!< NAT Both ROUTE and RFC3581 */
640 /* re-INVITE related settings */
641 #define SIP_REINVITE            (7 << 20)       /*!< three bits used */
642 #define SIP_CAN_REINVITE        (1 << 20)       /*!< allow peers to be reinvited to send media directly p2p */
643 #define SIP_CAN_REINVITE_NAT    (2 << 20)       /*!< allow media reinvite when new peer is behind NAT */
644 #define SIP_REINVITE_UPDATE     (4 << 20)       /*!< use UPDATE (RFC3311) when reinviting this peer */
645 /* "insecure" settings */
646 #define SIP_INSECURE_PORT       (1 << 23)       /*!< don't require matching port for incoming requests */
647 #define SIP_INSECURE_INVITE     (1 << 24)       /*!< don't require authentication for incoming INVITEs */
648 /* Sending PROGRESS in-band settings */
649 #define SIP_PROG_INBAND         (3 << 25)       /*!< three settings, uses two bits */
650 #define SIP_PROG_INBAND_NEVER   (0 << 25)
651 #define SIP_PROG_INBAND_NO      (1 << 25)
652 #define SIP_PROG_INBAND_YES     (2 << 25)
653 #define SIP_CALL_ONHOLD         (1 << 27)       /*!< Call states */
654 #define SIP_CALL_LIMIT          (1 << 28)       /*!< Call limit enforced for this call */
655 #define SIP_SENDRPID            (1 << 29)       /*!< Remote Party-ID Support */
656 #define SIP_INC_COUNT           (1 << 30)       /*!< Did this connection increment the counter of in-use calls? */
657
658 #define SIP_FLAGS_TO_COPY \
659         (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
660          SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | \
661          SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
662
663 /* a new page of flags for peers */
664 #define SIP_PAGE2_RTCACHEFRIENDS        (1 << 0)
665 #define SIP_PAGE2_RTUPDATE              (1 << 1)
666 #define SIP_PAGE2_RTAUTOCLEAR           (1 << 2)
667 #define SIP_PAGE2_IGNOREREGEXPIRE       (1 << 3)
668 #define SIP_PAGE2_RT_FROMCONTACT        (1 << 4)
669 #define SIP_PAGE2_DEBUG                 (3 << 5)
670 #define SIP_PAGE2_DEBUG_CONFIG          (1 << 5)
671 #define SIP_PAGE2_DEBUG_CONSOLE         (1 << 6)
672 #define SIP_PAGE2_DYNAMIC               (1 << 7)        /*!< Dynamic Peers register with Asterisk */
673 #define SIP_PAGE2_SELFDESTRUCT          (1 << 8)        /*!< Automatic peers need to destruct themselves */
674 #define SIP_PAGE2_VIDEOSUPPORT          (1 << 9)
675 #define SIP_PAGE2_ALLOWSUBSCRIBE        (1 << 10)       /*!< Allow subscriptions from this peer? */
676 #define SIP_PAGE2_ALLOWOVERLAP          (1 << 11)       /*!< Allow overlap dialing ? */
677 #define SIP_PAGE2_SUBSCRIBEMWIONLY      (1 << 12)       /*!< Only issue MWI notification if subscribed to */
678
679
680 #define SIP_PAGE2_FLAGS_TO_COPY \
681         (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT)
682
683 /* SIP packet flags */
684 #define SIP_PKT_DEBUG           (1 << 0)        /*!< Debug this packet */
685 #define SIP_PKT_WITH_TOTAG      (1 << 1)        /*!< This packet has a to-tag */
686 #define SIP_PKT_IGNORE          (1 << 2)        /*!< This is a re-transmit, ignore it */
687 #define SIP_PKT_IGNORE_RESP     (1 << 3)        /*!< Resp ignore - ??? */
688 #define SIP_PKT_IGNORE_REQ      (1 << 4)        /*!< Req ignore - ??? */
689
690 #define sipdebug                ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
691 #define sipdebug_config         ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
692 #define sipdebug_console        ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
693
694 /*! \brief Parameters to know status of transfer */
695 enum referstatus {
696         REFER_IDLE,             /*!< No REFER is in progress */
697         REFER_SENT,             /*!< Sent REFER to transferee */
698         REFER_RECEIVED,         /*!< Received REFER from transferer */
699         REFER_CONFIRMED,        /*!< Refer confirmed with a 100 TRYING */
700         REFER_ACCEPTED,         /*!< Accepted by transferee */
701         REFER_RINGING,          /*!< Target Ringing */
702         REFER_200OK,            /*!< Answered by transfer target */
703         REFER_FAILED,           /*!< REFER declined - go on */
704         REFER_NOAUTH            /*!< We had no auth for REFER */
705 };
706
707 static const struct c_referstatusstring {
708         enum referstatus status;
709         char *text;
710 } referstatusstrings[] = {
711         { REFER_IDLE,           "<none>" },
712         { REFER_SENT,           "Request sent" },
713         { REFER_RECEIVED,       "Request received" },
714         { REFER_ACCEPTED,       "Accepted" },
715         { REFER_RINGING,        "Target ringing" },
716         { REFER_200OK,          "Done" },
717         { REFER_FAILED,         "Failed" },
718         { REFER_NOAUTH,         "Failed - auth failure" }
719 } ;
720
721 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed  */
722 /* OEJ: Should be moved to string fields */
723 struct sip_refer {
724         char refer_to[AST_MAX_EXTENSION];               /*!< Place to store REFER-TO extension */
725         char refer_to_domain[AST_MAX_EXTENSION];        /*!< Place to store REFER-TO domain */
726         char refer_to_urioption[AST_MAX_EXTENSION];     /*!< Place to store REFER-TO uri options */
727         char refer_to_context[AST_MAX_EXTENSION];       /*!< Place to store REFER-TO context */
728         char referred_by[AST_MAX_EXTENSION];            /*!< Place to store REFERRED-BY extension */
729         char referred_by_name[AST_MAX_EXTENSION];       /*!< Place to store REFERRED-BY extension */
730         char refer_contact[AST_MAX_EXTENSION];          /*!< Place to store Contact info from a REFER extension */
731         char replaces_callid[BUFSIZ];                   /*!< Replace info */
732         char replaces_callid_totag[BUFSIZ/2];           /*!< Replace info */
733         char replaces_callid_fromtag[BUFSIZ/2];         /*!< Replace info */
734         struct sip_pvt *refer_call;                     /*!< Call we are referring */
735         int attendedtransfer;                           /*!< Attended or blind transfer? */
736         int localtransfer;                              /*!< Transfer to local domain? */
737         enum referstatus status;                        /*!< REFER status */
738 };
739
740 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe  */
741 static struct sip_pvt {
742         ast_mutex_t lock;                       /*!< Dialog private lock */
743         int method;                             /*!< SIP method that opened this dialog */
744         AST_DECLARE_STRING_FIELDS(
745                 AST_STRING_FIELD(callid);       /*!< Global CallID */
746                 AST_STRING_FIELD(randdata);     /*!< Random data */
747                 AST_STRING_FIELD(accountcode);  /*!< Account code */
748                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
749                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
750                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
751                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
752                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
753                 AST_STRING_FIELD(refer_to);     /*!< Place to store REFER-TO extension */
754                 AST_STRING_FIELD(referred_by);  /*!< Place to store REFERRED-BY extension */
755                 AST_STRING_FIELD(refer_contact);/*!< Place to store Contact info from a REFER extension */
756                 AST_STRING_FIELD(from);         /*!< The From: header */
757                 AST_STRING_FIELD(useragent);    /*!< User agent in SIP request */
758                 AST_STRING_FIELD(exten);        /*!< Extension where to start */
759                 AST_STRING_FIELD(context);      /*!< Context for this call */
760                 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
761                 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
762                 AST_STRING_FIELD(fromdomain);   /*!< Domain to show in the from field */
763                 AST_STRING_FIELD(fromuser);     /*!< User to show in the user field */
764                 AST_STRING_FIELD(fromname);     /*!< Name to show in the user field */
765                 AST_STRING_FIELD(tohost);       /*!< Host we should put in the "to" field */
766                 AST_STRING_FIELD(language);     /*!< Default language for this call */
767                 AST_STRING_FIELD(musicclass);   /*!< Music on Hold class */
768                 AST_STRING_FIELD(rdnis);        /*!< Referring DNIS */
769                 AST_STRING_FIELD(theirtag);     /*!< Their tag */
770                 AST_STRING_FIELD(username);     /*!< [user] name */
771                 AST_STRING_FIELD(peername);     /*!< [peer] name, not set if [user] */
772                 AST_STRING_FIELD(authname);     /*!< Who we use for authentication */
773                 AST_STRING_FIELD(uri);          /*!< Original requested URI */
774                 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
775                 AST_STRING_FIELD(peersecret);   /*!< Password */
776                 AST_STRING_FIELD(peermd5secret);
777                 AST_STRING_FIELD(cid_num);      /*!< Caller*ID */
778                 AST_STRING_FIELD(cid_name);     /*!< Caller*ID */
779                 AST_STRING_FIELD(via);          /*!< Via: header */
780                 AST_STRING_FIELD(fullcontact);  /*!< The Contact: that the UA registers with us */
781                 AST_STRING_FIELD(our_contact);  /*!< Our contact header */
782                 AST_STRING_FIELD(rpid);         /*!< Our RPID header */
783                 AST_STRING_FIELD(rpid_from);    /*!< Our RPID From header */
784         );
785         struct ast_codec_pref prefs;            /*!< codec prefs */
786         unsigned int ocseq;                     /*!< Current outgoing seqno */
787         unsigned int icseq;                     /*!< Current incoming seqno */
788         ast_group_t callgroup;                  /*!< Call group */
789         ast_group_t pickupgroup;                /*!< Pickup group */
790         int lastinvite;                         /*!< Last Cseq of invite */
791         struct ast_flags flags[2];              /*!< SIP_ flags */
792         int timer_t1;                           /*!< SIP timer T1, ms rtt */
793         unsigned int sipoptions;                /*!< Supported SIP sipoptions on the other end */
794         int capability;                         /*!< Special capability (codec) */
795         int jointcapability;                    /*!< Supported capability at both ends (codecs ) */
796         int peercapability;                     /*!< Supported peer capability */
797         int prefcodec;                          /*!< Preferred codec (outbound only) */
798         int noncodeccapability;
799         int maxcallbitrate;                     /*!< Maximum Call Bitrate for Video Calls */    
800         int callingpres;                        /*!< Calling presentation */
801         int authtries;                          /*!< Times we've tried to authenticate */
802         int expiry;                             /*!< How long we take to expire */
803         long branch;                            /*!< One random number */
804         char tag[11];                           /*!< Another random number */
805         int sessionid;                          /*!< SDP Session ID */
806         int sessionversion;                     /*!< SDP Session Version */
807         struct sockaddr_in sa;                  /*!< Our peer */
808         struct sockaddr_in redirip;             /*!< Where our RTP should be going if not to us */
809         struct sockaddr_in vredirip;            /*!< Where our Video RTP should be going if not to us */
810         int redircodecs;                        /*!< Redirect codecs */
811         struct sockaddr_in recv;                /*!< Received as */
812         struct in_addr ourip;                   /*!< Our IP */
813         struct ast_channel *owner;              /*!< Who owns us */
814         struct sip_pvt *refer_call;             /*!< Call we are referring */
815         struct sip_route *route;                /*!< Head of linked list of routing steps (fm Record-Route) */
816         int route_persistant;                   /*!< Is this the "real" route? */
817         struct sip_auth *peerauth;              /*!< Realm authentication */
818         int noncecount;                         /*!< Nonce-count */
819         char lastmsg[256];                      /*!< Last Message sent/received */
820         int amaflags;                           /*!< AMA Flags */
821         int pendinginvite;                      /*!< Any pending invite */
822         struct sip_request initreq;             /*!< Initial request that opened the SIP dialog */
823         
824         int maxtime;                            /*!< Max time for first response */
825         int initid;                             /*!< Auto-congest ID if appropriate */
826         int autokillid;                         /*!< Auto-kill ID */
827         time_t lastrtprx;                       /*!< Last RTP received */
828         time_t lastrtptx;                       /*!< Last RTP sent */
829         int rtptimeout;                         /*!< RTP timeout time */
830         int rtpholdtimeout;                     /*!< RTP timeout when on hold */
831         int rtpkeepalive;                       /*!< Send RTP packets for keepalive */
832         enum transfermodes allowtransfer;       /*! SIP Refer restriction scheme */
833         enum subscriptiontype subscribed;       /*!< SUBSCRIBE: Is this dialog a subscription?  */
834         int stateid;                            /*!< SUBSCRIBE: ID for devicestate subscriptions */
835         int laststate;                          /*!< SUBSCRIBE: Last known extension state */
836         int dialogver;                          /*!< SUBSCRIBE: Version for subscription dialog-info */
837         
838         struct sip_refer *refer;                /*!< REFER: SIP transfer data structure */
839         struct ast_dsp *vad;                    /*!< Voice Activation Detection dsp */
840         
841         struct sip_peer *relatedpeer;           /*!< If this dialog is related to a peer, which one 
842                                                         Used in peerpoke, mwi subscriptions */
843         struct sip_registry *registry;          /*!< If this is a REGISTER dialog, to which registry */
844         struct ast_rtp *rtp;                    /*!< RTP Session */
845         struct ast_rtp *vrtp;                   /*!< Video RTP session */
846         struct sip_pkt *packets;                /*!< Packets scheduled for re-transmission */
847         struct sip_history_head *history;       /*!< History of this SIP dialog */
848         struct ast_variable *chanvars;          /*!< Channel variables to set for inbound call */
849         struct sip_pvt *next;                   /*!< Next dialog in chain */
850         struct sip_invite_param *options;       /*!< Options for INVITE */
851 } *iflist = NULL;
852
853 #define FLAG_RESPONSE (1 << 0)
854 #define FLAG_FATAL (1 << 1)
855
856 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
857 struct sip_pkt {
858         struct sip_pkt *next;                   /*!< Next packet in linked list */
859         int retrans;                            /*!< Retransmission number */
860         int method;                             /*!< SIP method for this packet */
861         int seqno;                              /*!< Sequence number */
862         unsigned int flags;                     /*!< non-zero if this is a response packet (e.g. 200 OK) */
863         struct sip_pvt *owner;                  /*!< Owner AST call */
864         int retransid;                          /*!< Retransmission ID */
865         int timer_a;                            /*!< SIP timer A, retransmission timer */
866         int timer_t1;                           /*!< SIP Timer T1, estimated RTT or 500 ms */
867         int packetlen;                          /*!< Length of packet */
868         char data[0];
869 };      
870
871 /*! \brief Structure for SIP user data. User's place calls to us */
872 struct sip_user {
873         /* Users who can access various contexts */
874         ASTOBJ_COMPONENTS(struct sip_user);
875         char secret[80];                /*!< Password */
876         char md5secret[80];             /*!< Password in md5 */
877         char context[AST_MAX_CONTEXT];  /*!< Default context for incoming calls */
878         char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
879         char cid_num[80];               /*!< Caller ID num */
880         char cid_name[80];              /*!< Caller ID name */
881         char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
882         char language[MAX_LANGUAGE];    /*!< Default language for this user */
883         char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
884         char useragent[256];            /*!< User agent in SIP request */
885         struct ast_codec_pref prefs;    /*!< codec prefs */
886         ast_group_t callgroup;          /*!< Call group */
887         ast_group_t pickupgroup;        /*!< Pickup Group */
888         unsigned int sipoptions;        /*!< Supported SIP options */
889         struct ast_flags flags[2];      /*!< SIP_ flags */
890         int amaflags;                   /*!< AMA flags for billing */
891         int callingpres;                /*!< Calling id presentation */
892         int capability;                 /*!< Codec capability */
893         int inUse;                      /*!< Number of calls in use */
894         int call_limit;                 /*!< Limit of concurrent calls */
895         enum transfermodes allowtransfer;       /*! SIP Refer restriction scheme */
896         struct ast_ha *ha;              /*!< ACL setting */
897         struct ast_variable *chanvars;  /*!< Variables to set for channel created by user */
898         int maxcallbitrate;             /*!< Maximum Bitrate for a video call */
899 };
900
901 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) */
902 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
903 struct sip_peer {
904         ASTOBJ_COMPONENTS(struct sip_peer);     /*!< name, refcount, objflags,  object pointers */
905                                         /*!< peer->name is the unique name of this object */
906         char secret[80];                /*!< Password */
907         char md5secret[80];             /*!< Password in MD5 */
908         struct sip_auth *auth;          /*!< Realm authentication list */
909         char context[AST_MAX_CONTEXT];  /*!< Default context for incoming calls */
910         char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
911         char username[80];              /*!< Temporary username until registration */ 
912         char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
913         int amaflags;                   /*!< AMA Flags (for billing) */
914         char tohost[MAXHOSTNAMELEN];    /*!< If not dynamic, IP address */
915         char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
916         char fromuser[80];              /*!< From: user when calling this peer */
917         char fromdomain[MAXHOSTNAMELEN];        /*!< From: domain when calling this peer */
918         char fullcontact[256];          /*!< Contact registered with us (not in sip.conf) */
919         char cid_num[80];               /*!< Caller ID num */
920         char cid_name[80];              /*!< Caller ID name */
921         int callingpres;                /*!< Calling id presentation */
922         int inUse;                      /*!< Number of calls in use */
923         int call_limit;                 /*!< Limit of concurrent calls */
924         enum transfermodes allowtransfer;       /*! SIP Refer restriction scheme */
925         char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
926         char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
927         char language[MAX_LANGUAGE];    /*!<  Default language for prompts */
928         char musicclass[MAX_MUSICCLASS];/*!<  Music on Hold class */
929         char useragent[256];            /*!<  User agent in SIP request (saved from registration) */
930         struct ast_codec_pref prefs;    /*!<  codec prefs */
931         int lastmsgssent;
932         time_t  lastmsgcheck;           /*!<  Last time we checked for MWI */
933         unsigned int sipoptions;        /*!<  Supported SIP options */
934         struct ast_flags flags[2];      /*!<  SIP_ flags */
935         int expire;                     /*!<  When to expire this peer registration */
936         int capability;                 /*!<  Codec capability */
937         int rtptimeout;                 /*!<  RTP timeout */
938         int rtpholdtimeout;             /*!<  RTP Hold Timeout */
939         int rtpkeepalive;               /*!<  Send RTP packets for keepalive */
940         ast_group_t callgroup;          /*!<  Call group */
941         ast_group_t pickupgroup;        /*!<  Pickup group */
942         struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
943         struct sockaddr_in addr;        /*!<  IP address of peer */
944         int maxcallbitrate;             /*!< Maximum Bitrate for a video call */
945         
946         /* Qualification */
947         struct sip_pvt *call;           /*!<  Call pointer */
948         int pokeexpire;                 /*!<  When to expire poke (qualify= checking) */
949         int lastms;                     /*!<  How long last response took (in ms), or -1 for no response */
950         int maxms;                      /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
951         struct timeval ps;              /*!<  Ping send time */
952         
953         struct sockaddr_in defaddr;     /*!<  Default IP address, used until registration */
954         struct ast_ha *ha;              /*!<  Access control list */
955         struct ast_variable *chanvars;  /*!<  Variables to set for channel created by user */
956         struct sip_pvt *mwipvt;         /*!<  Subscription for MWI */
957         int lastmsg;
958 };
959
960
961
962 /*! \brief Registrations with other SIP proxies */
963 struct sip_registry {
964         ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
965         AST_DECLARE_STRING_FIELDS(
966                 AST_STRING_FIELD(callid);       /*!< Global Call-ID */
967                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
968                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
969                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
970                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
971                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
972                 AST_STRING_FIELD(username);     /*!< Who we are registering as */
973                 AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
974                 AST_STRING_FIELD(hostname);     /*!< Domain or host we register to */
975                 AST_STRING_FIELD(secret);       /*!< Password in clear text */  
976                 AST_STRING_FIELD(md5secret);    /*!< Password in md5 */
977                 AST_STRING_FIELD(contact);      /*!< Contact extension */
978                 AST_STRING_FIELD(random);
979         );
980         int portno;                     /*!<  Optional port override */
981         int expire;                     /*!< Sched ID of expiration */
982         int regattempts;                /*!< Number of attempts (since the last success) */
983         int timeout;                    /*!< sched id of sip_reg_timeout */
984         int refresh;                    /*!< How often to refresh */
985         struct sip_pvt *call;           /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
986         enum sipregistrystate regstate; /*!< Registration state (see above) */
987         time_t regtime;         /*!< Last succesful registration time */
988         int callid_valid;               /*!< 0 means we haven't chosen callid for this registry yet. */
989         unsigned int ocseq;             /*!< Sequence number we got to for REGISTERs for this registry */
990         struct sockaddr_in us;          /*!< Who the server thinks we are */
991         int noncecount;                 /*!< Nonce-count */
992         char lastmsg[256];              /*!< Last Message sent/received */
993 };
994
995 /* --- Linked lists of various objects --------*/
996
997 /*! \brief  The user list: Users and friends */
998 static struct ast_user_list {
999         ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1000 } userl;
1001
1002 /*! \brief  The peer list: Peers and Friends */
1003 static struct ast_peer_list {
1004         ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1005 } peerl;
1006
1007 /*! \brief  The register list: Other SIP proxys we register with and place calls to */
1008 static struct ast_register_list {
1009         ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1010         int recheck;
1011 } regl;
1012
1013 /*! \todo Move the sip_auth list to AST_LIST */
1014 static struct sip_auth *authl = NULL;           /*!< Authentication list for realm authentication */
1015
1016
1017 /* --- Sockets and networking --------------*/
1018 static int sipsock  = -1;                       /*!< Main socket for SIP network communication */
1019 static struct sockaddr_in bindaddr = { 0, };    /*!< The address we bind to */
1020 static struct sockaddr_in externip;             /*!< External IP address if we are behind NAT */
1021 static char externhost[MAXHOSTNAMELEN];         /*!< External host name (possibly with dynamic DNS and DHCP */
1022 static time_t externexpire = 0;                 /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1023 static int externrefresh = 10;
1024 static struct ast_ha *localaddr;                /*!< List of local networks, on the same side of NAT as this Asterisk */
1025 static struct in_addr __ourip;
1026 static struct sockaddr_in outboundproxyip;
1027 static int ourport;
1028 static struct sockaddr_in debugaddr;
1029
1030 static struct ast_config *notify_types;         /*!< The list of manual NOTIFY types we know how to send */
1031
1032 /*---------------------------- Forward declarations of functions in chan_sip.c */
1033 /*! \note Sorted up from start to build_rpid.... Will continue categorization in order to
1034         split up chan_sip.c into several files  */
1035
1036 /*--- PBX interface functions */
1037 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1038 static int sip_devicestate(void *data);
1039 static int sip_sendtext(struct ast_channel *ast, const char *text);
1040 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1041 static int sip_hangup(struct ast_channel *ast);
1042 static int sip_answer(struct ast_channel *ast);
1043 static struct ast_frame *sip_read(struct ast_channel *ast);
1044 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1045 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1046 static int sip_transfer(struct ast_channel *ast, const char *dest);
1047 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1048 static int sip_senddigit(struct ast_channel *ast, char digit);
1049
1050 /*--- Transmitting responses and requests */
1051 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1052 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1053 static int __transmit_response(struct sip_pvt *p, const char *msg, struct sip_request *req, enum xmittype reliable);
1054 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
1055 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, struct sip_request *req);
1056 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req);
1057 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, enum xmittype reliable);
1058 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, struct sip_request *req, const char *unsupported);
1059 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
1060 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req, enum xmittype reliable);
1061 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1062 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1063 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init);
1064 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
1065 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
1066 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1067 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1068 static int transmit_refer(struct sip_pvt *p, const char *dest);
1069 static int transmit_state_notify(struct sip_pvt *p, int state, int full);
1070 static int transmit_register(struct sip_registry *r, int sipmethod, char *auth, char *authheader);
1071 static int retrans_pkt(void *data);
1072 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1073 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1074 static void copy_request(struct sip_request *dst, struct sip_request *src);
1075
1076 /*--- Dialog management */
1077 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1078                                  int useglobal_nat, const int intended_method);
1079 static int __sip_autodestruct(void *data);
1080 static int sip_scheddestroy(struct sip_pvt *p, int ms);
1081 static int sip_cancel_destroy(struct sip_pvt *p);
1082 static void sip_destroy(struct sip_pvt *p);
1083 static void __sip_destroy(struct sip_pvt *p, int lockowner);
1084 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod, int reset);
1085 static int __sip_pretend_ack(struct sip_pvt *p);
1086 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1087 static int auto_congest(void *nothing);
1088 static int update_call_counter(struct sip_pvt *fup, int event);
1089 static int hangup_sip2cause(int cause);
1090 static const char *hangup_cause2sip(int cause);
1091 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1092 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1093
1094 /*--- Codec handling / SDP */
1095 static void try_suggested_sip_codec(struct sip_pvt *p);
1096 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1097 static const char *get_sdp(struct sip_request *req, const char *name);
1098 static int find_sdp(struct sip_request *req);
1099 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1100 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1101                              char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1102                              int debug);
1103 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1104                                 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1105                                 int debug);
1106 static int add_sdp(struct sip_request *resp, struct sip_pvt *p);
1107
1108 /*--- Authentication stuff */
1109 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
1110 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1111 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1112 static int clear_realm_authentication(struct sip_auth *authlist);       /* Clear realm authentication list (at reload) */
1113 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);   /* Add realm authentication in list */
1114 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);        /* Find authentication for a specific realm */
1115 static int check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1116                 const char *secret, const char *md5secret, int sipmethod,
1117                 char *uri, enum xmittype reliable, int ignore);
1118
1119 /*--- Domain handling */
1120 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1121
1122 static void free_old_route(struct sip_route *route);
1123
1124 /*--- Misc functions */
1125 static int sip_do_reload(enum channelreloadreason reason);
1126 static int expire_register(void *data);
1127 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1128 static int restart_monitor(void);
1129 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1130 static void sip_destroy(struct sip_pvt *p);
1131 static int sip_scheddestroy(struct sip_pvt *p, int ms);
1132 static int sip_addrcmp(char *name, struct sockaddr_in *sin);    /* Support for peer matching */
1133
1134 /*--- CLI and manager command helpers */
1135 static const char *sip_nat_mode(const struct sip_pvt *p);
1136
1137 /*--- Debugging */
1138 static void sip_dump_history(struct sip_pvt *dialog);   /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1139 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1140 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1141 static int append_history_full(struct sip_pvt *p, const char *fmt, ...);
1142
1143 /*--- Device object handling */
1144 static struct sip_peer *temp_peer(const char *name);
1145 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
1146 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1147 static int update_call_counter(struct sip_pvt *fup, int event);
1148 static void sip_destroy_peer(struct sip_peer *peer);
1149 static void sip_destroy_user(struct sip_user *user);
1150 static int sip_poke_peer(struct sip_peer *peer);
1151 static void set_peer_defaults(struct sip_peer *peer);
1152 static struct sip_peer *temp_peer(const char *name);
1153 static void register_peer_exten(struct sip_peer *peer, int onoff);
1154 static void sip_destroy_peer(struct sip_peer *peer);
1155 static void sip_destroy_user(struct sip_user *user);
1156 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1157 static struct sip_user *find_user(const char *name, int realtime);
1158 /* Realtime device support */
1159 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1160 static struct sip_user *realtime_user(const char *username);
1161 static void update_peer(struct sip_peer *p, int expiry);
1162 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1163
1164 /*--- Internal UA client handling (outbound registrations) */
1165 static int __sip_do_register(struct sip_registry *r);
1166 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1167 static void sip_registry_destroy(struct sip_registry *reg);
1168 static int sip_register(char *value, int lineno);
1169
1170 /*--- Parsing SIP requests and responses */
1171 static void append_date(struct sip_request *req);       /* Append date to SIP packet */
1172 static int determine_firstline_parts(struct sip_request *req);
1173 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1174 static const char *gettag(const struct sip_request *req, char *header, char *tagbuf, int tagbufsize);
1175 static int find_sip_method(const char *msg);
1176 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1177 static void parse_request(struct sip_request *req);
1178 static const char *get_header(const struct sip_request *req, const char *name);
1179 static char *referstatus2str(enum referstatus rstatus);
1180 static int method_match(enum sipmethod id, const char *name);
1181 static void parse_copy(struct sip_request *dst, struct sip_request *src);
1182 static char *get_in_brackets(char *tmp);
1183 static const char *find_alias(const char *name, const char *_default);
1184 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1185 static const char *get_header(const struct sip_request *req, const char *name);
1186 static int lws2sws(char *msgbuf, int len);
1187 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1188
1189 /*--- Constructing requests and responses */
1190 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1191 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1192 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1193 static int init_resp(struct sip_request *resp, const char *msg);
1194 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, struct sip_request *req);
1195 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1196 static void build_via(struct sip_pvt *p);
1197 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1198 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1199 static char *generate_random_string(char *buf, size_t size);
1200 static void build_callid_pvt(struct sip_pvt *pvt);
1201 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1202 static void make_our_tag(char *tagbuf, size_t len);
1203 static int add_header(struct sip_request *req, const char *var, const char *value);
1204 static int add_header_contentLength(struct sip_request *req, int len);
1205 static int add_line(struct sip_request *req, const char *line);
1206 static int add_text(struct sip_request *req, const char *text);
1207 static int add_digit(struct sip_request *req, char digit);
1208 static int add_vidupdate(struct sip_request *req);
1209 static void add_route(struct sip_request *req, struct sip_route *route);
1210 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field);
1211 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field);
1212 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field);
1213 static void set_destination(struct sip_pvt *p, char *uri);
1214 static void append_date(struct sip_request *req);
1215 static void build_contact(struct sip_pvt *p);
1216 static void build_rpid(struct sip_pvt *p);
1217
1218 /*------Request handling functions */
1219 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e);
1220 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
1221 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1222 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1223 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1224 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1225 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1226 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1227 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1228
1229 /*------Response handling functions */
1230 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1231 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1232 static int handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req);
1233
1234 /*----- RTP interface functions */
1235 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1236 static struct ast_rtp *sip_get_rtp_peer(struct ast_channel *chan);
1237 static struct ast_rtp *sip_get_vrtp_peer(struct ast_channel *chan);
1238 static int sip_get_codec(struct ast_channel *chan);
1239 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p);
1240
1241 /*! \brief Definition of this channel for PBX channel registration */
1242 static const struct ast_channel_tech sip_tech = {
1243         .type = "SIP",
1244         .description = "Session Initiation Protocol (SIP)",
1245         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1246         .properties = AST_CHAN_TP_WANTSJITTER,
1247         .requester = sip_request_call,
1248         .devicestate = sip_devicestate,
1249         .call = sip_call,
1250         .hangup = sip_hangup,
1251         .answer = sip_answer,
1252         .read = sip_read,
1253         .write = sip_write,
1254         .write_video = sip_write,
1255         .indicate = sip_indicate,
1256         .transfer = sip_transfer,
1257         .fixup = sip_fixup,
1258         .send_digit = sip_senddigit,
1259         .bridge = ast_rtp_bridge,
1260         .send_text = sip_sendtext,
1261 };
1262
1263 /**--- some list management macros. **/
1264  
1265 #define UNLINK(element, head, prev) do {        \
1266         if (prev)                               \
1267                 (prev)->next = (element)->next; \
1268         else                                    \
1269                 (head) = (element)->next;       \
1270         } while (0)
1271
1272 /*! \brief Interface structure with callbacks used to connect to RTP module */
1273 static struct ast_rtp_protocol sip_rtp = {
1274         type: "SIP",
1275         get_rtp_info: sip_get_rtp_peer,
1276         get_vrtp_info: sip_get_vrtp_peer,
1277         set_rtp_peer: sip_set_rtp_peer,
1278         get_codec: sip_get_codec,
1279 };
1280
1281 /*! \brief Convert transfer status to string */
1282 static char *referstatus2str(enum referstatus rstatus)
1283 {
1284         int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1285         int x;
1286
1287         for (x = 0; x < i; x++) {
1288                 if (referstatusstrings[x].status ==  rstatus)
1289                         return (char *) referstatusstrings[x].text;
1290         }
1291         return "";
1292 }
1293
1294 /*! \brief Initialize the initital request packet in the pvt structure.
1295         This packet is used for creating replies and future requests in
1296         a dialog */
1297 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1298 {
1299         if (p->initreq.headers) {
1300                 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1301         }
1302         /* Use this as the basis */
1303         copy_request(&p->initreq, req);
1304         parse_request(&p->initreq);
1305         if (ast_test_flag(req, SIP_PKT_DEBUG))
1306                 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1307 }
1308
1309
1310 /*! \brief returns true if 'name' (with optional trailing whitespace)
1311  * matches the sip method 'id'.
1312  * Strictly speaking, SIP methods are case SENSITIVE, but we do
1313  * a case-insensitive comparison to be more tolerant.
1314  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1315  */
1316 static int method_match(enum sipmethod id, const char *name)
1317 {
1318         int len = strlen(sip_methods[id].text);
1319         int l_name = name ? strlen(name) : 0;
1320         /* true if the string is long enough, and ends with whitespace, and matches */
1321         return (l_name >= len && name[len] < 33 &&
1322                 !strncasecmp(sip_methods[id].text, name, len));
1323 }
1324
1325 /*! \brief  find_sip_method: Find SIP method from header */
1326 static int find_sip_method(const char *msg)
1327 {
1328         int i, res = 0;
1329         
1330         if (ast_strlen_zero(msg))
1331                 return 0;
1332         for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1333                 if (method_match(i, msg))
1334                         res = sip_methods[i].id;
1335         }
1336         return res;
1337 }
1338
1339 /*! \brief Parse supported header in incoming packet */
1340 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1341 {
1342         char *next, *sep;
1343         char *temp = ast_strdupa(supported);
1344         unsigned int profile = 0;
1345         int i, found;
1346
1347         if (!pvt || ast_strlen_zero(supported) )
1348                 return 0;
1349
1350         if (option_debug > 2 && sipdebug)
1351                 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1352
1353         for (next = temp; next; next = sep) {
1354                 found = FALSE;
1355                 if ( (sep = strchr(next, ',')) != NULL)
1356                         *sep++ = '\0';
1357                 next = ast_skip_blanks(next);
1358                 if (option_debug > 2 && sipdebug)
1359                         ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1360                 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1361                         if (!strcasecmp(next, sip_options[i].text)) {
1362                                 profile |= sip_options[i].id;
1363                                 found = TRUE;
1364                                 if (option_debug > 2 && sipdebug)
1365                                         ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1366                                 break;
1367                         }
1368                 }
1369                 if (!found && option_debug > 2 && sipdebug)
1370                         ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1371         }
1372
1373         pvt->sipoptions = profile;
1374         return profile;
1375 }
1376
1377 /*! \brief See if we pass debug IP filter */
1378 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
1379 {
1380         if (!sipdebug)
1381                 return 0;
1382         if (debugaddr.sin_addr.s_addr) {
1383                 if (((ntohs(debugaddr.sin_port) != 0)
1384                         && (debugaddr.sin_port != addr->sin_port))
1385                         || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1386                         return 0;
1387         }
1388         return 1;
1389 }
1390
1391 /*! \brief The real destination address for a write */
1392 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1393 {
1394         return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1395 }
1396
1397 /*! \brief Display SIP nat mode */
1398 static const char *sip_nat_mode(const struct sip_pvt *p)
1399 {
1400         return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1401 }
1402
1403 /*! \brief Test PVT for debugging output */
1404 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
1405 {
1406         if (!sipdebug)
1407                 return 0;
1408         return sip_debug_test_addr(sip_real_dst(p));
1409 }
1410
1411 /*! \brief Transmit SIP message */
1412 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1413 {
1414         int res;
1415         char iabuf[INET_ADDRSTRLEN];
1416         const struct sockaddr_in *dst = sip_real_dst(p);
1417         res=sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1418
1419         if (res != len)
1420                 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
1421         return res;
1422 }
1423
1424
1425 /*! \brief Build a Via header for a request */
1426 static void build_via(struct sip_pvt *p)
1427 {
1428         char iabuf[INET_ADDRSTRLEN];
1429         /* Work around buggy UNIDEN UIP200 firmware */
1430         const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1431
1432         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
1433         ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1434                          ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch, rport);
1435 }
1436
1437 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1438  * Only used for outbound registrations */
1439 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1440 {
1441         /*
1442          * Using the localaddr structure built up with localnet statements
1443          * apply it to their address to see if we need to substitute our
1444          * externip or can get away with our internal bindaddr
1445          */
1446         struct sockaddr_in theirs;
1447         theirs.sin_addr = *them;
1448
1449         if (localaddr && externip.sin_addr.s_addr &&
1450            ast_apply_ha(localaddr, &theirs)) {
1451                 if (externexpire && time(NULL) >= externexpire) {
1452                         struct ast_hostent ahp;
1453                         struct hostent *hp;
1454
1455                         time(&externexpire);
1456                         externexpire += externrefresh;
1457                         if ((hp = ast_gethostbyname(externhost, &ahp))) {
1458                                 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1459                         } else
1460                                 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1461                 }
1462                 *us = externip.sin_addr;
1463                 if (option_debug) {
1464                         char iabuf[INET_ADDRSTRLEN];
1465                         ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
1466                 
1467                         ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
1468                 }
1469         } else if (bindaddr.sin_addr.s_addr)
1470                 *us = bindaddr.sin_addr;
1471         else
1472                 return ast_ouraddrfor(them, us);
1473         return 0;
1474 }
1475
1476 /*! \brief Append to SIP dialog history 
1477         \return Always returns 0 */
1478 #define append_history(p, event, fmt , args... )        append_history_full(p, "%-15s " fmt, event, ## args)
1479
1480 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1481         __attribute__ ((format (printf, 2, 3)));
1482
1483 /*! \brief Append to SIP dialog history with arg list  */
1484 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1485 {
1486         char buf[80], *c = buf; /* max history length */
1487         struct sip_history *hist;
1488         int l;
1489
1490         vsnprintf(buf, sizeof(buf), fmt, ap);
1491         strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1492         l = strlen(buf) + 1;
1493         if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1494                 return;
1495         if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1496                 free(hist);
1497                 return;
1498         }
1499         memcpy(hist->event, buf, l);
1500         AST_LIST_INSERT_TAIL(p->history, hist, list);
1501 }
1502
1503 /*! \brief Append to SIP dialog history with arg list  */
1504 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1505 {
1506         va_list ap;
1507
1508         if (!recordhistory || !p)
1509                 return 0;
1510         va_start(ap, fmt);
1511         append_history_va(p, fmt, ap);
1512         va_end(ap);
1513
1514         return 0;
1515 }
1516
1517 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1518 static int retrans_pkt(void *data)
1519 {
1520         struct sip_pkt *pkt = data, *prev, *cur = NULL;
1521         char iabuf[INET_ADDRSTRLEN];
1522         int reschedule = DEFAULT_RETRANS;
1523
1524         /* Lock channel PVT */
1525         ast_mutex_lock(&pkt->owner->lock);
1526
1527         if (pkt->retrans < MAX_RETRANS) {
1528                 pkt->retrans++;
1529                 if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
1530                         if (sipdebug && option_debug > 3)
1531                                 ast_log(LOG_DEBUG, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
1532                 } else {
1533                         int siptimer_a;
1534
1535                         if (sipdebug && option_debug > 3)
1536                                 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1537                         if (!pkt->timer_a)
1538                                 pkt->timer_a = 2 ;
1539                         else
1540                                 pkt->timer_a = 2 * pkt->timer_a;
1541  
1542                         /* For non-invites, a maximum of 4 secs */
1543                         siptimer_a = pkt->timer_t1 * pkt->timer_a;      /* Double each time */
1544                         if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1545                                 siptimer_a = 4000;
1546                 
1547                         /* Reschedule re-transmit */
1548                         reschedule = siptimer_a;
1549                         if (option_debug > 3)
1550                                 ast_log(LOG_DEBUG, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
1551                 } 
1552
1553                 if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
1554                         if (ast_test_flag(&pkt->owner->flags[0], SIP_NAT_ROUTE))
1555                                 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);
1556                         else
1557                                 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);
1558                 }
1559
1560                 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1561                 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1562                 ast_mutex_unlock(&pkt->owner->lock);
1563                 return  reschedule;
1564         } 
1565         /* Too many retries */
1566         if (pkt->owner && pkt->method != SIP_OPTIONS) {
1567                 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1568                         ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %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");
1569         } else {
1570                 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1571                         ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1572         }
1573         append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1574                 
1575         pkt->retransid = -1;
1576
1577         if (ast_test_flag(pkt, FLAG_FATAL)) {
1578                 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
1579                         ast_mutex_unlock(&pkt->owner->lock);
1580                         usleep(1);
1581                         ast_mutex_lock(&pkt->owner->lock);
1582                 }
1583                 if (pkt->owner->owner) {
1584                         ast_set_flag(&pkt->owner->flags[0], SIP_ALREADYGONE);
1585                         ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1586                         ast_queue_hangup(pkt->owner->owner);
1587                         ast_channel_unlock(pkt->owner->owner);
1588                 } else {
1589                         /* If no channel owner, destroy now */
1590                         ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);   
1591                 }
1592         }
1593         /* In any case, go ahead and remove the packet */
1594         for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
1595                 if (cur == pkt)
1596                         break;
1597         }
1598         if (cur) {
1599                 if (prev)
1600                         prev->next = cur->next;
1601                 else
1602                         pkt->owner->packets = cur->next;
1603                 ast_mutex_unlock(&pkt->owner->lock);
1604                 free(cur);
1605                 pkt = NULL;
1606         } else
1607                 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1608         if (pkt)
1609                 ast_mutex_unlock(&pkt->owner->lock);
1610         return 0;
1611 }
1612
1613 /*! \brief Transmit packet with retransmits 
1614         \return 0 on success, -1 on failure to allocate packet 
1615 */
1616 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1617 {
1618         struct sip_pkt *pkt;
1619         int siptimer_a = DEFAULT_RETRANS;
1620
1621         if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1622                 return -1;
1623         memcpy(pkt->data, data, len);
1624         pkt->method = sipmethod;
1625         pkt->packetlen = len;
1626         pkt->next = p->packets;
1627         pkt->owner = p;
1628         pkt->seqno = seqno;
1629         pkt->flags = resp;
1630         pkt->data[len] = '\0';
1631         pkt->timer_t1 = p->timer_t1;    /* Set SIP timer T1 */
1632         if (fatal)
1633                 ast_set_flag(pkt, FLAG_FATAL);
1634         if (pkt->timer_t1)
1635                 siptimer_a = pkt->timer_t1 * 2;
1636
1637         /* Schedule retransmission */
1638         pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1639         if (option_debug > 3 && sipdebug)
1640                 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id  #%d\n", pkt->retransid);
1641         pkt->next = p->packets;
1642         p->packets = pkt;
1643
1644         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);      /* Send packet */
1645         if (sipmethod == SIP_INVITE) {
1646                 /* Note this is a pending invite */
1647                 p->pendinginvite = seqno;
1648         }
1649         return 0;
1650 }
1651
1652 /*! \brief Kill a SIP dialog (called by scheduler) */
1653 static int __sip_autodestruct(void *data)
1654 {
1655         struct sip_pvt *p = data;
1656
1657         /* If this is a subscription, tell the phone that we got a timeout */
1658         if (p->subscribed) {
1659                 p->subscribed = TIMEOUT;
1660                 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1); /* Send last notification */
1661                 p->subscribed = NONE;
1662                 append_history(p, "Subscribestatus", "timeout");
1663                 if (option_debug > 2)
1664                         ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
1665                 return 10000;   /* Reschedule this destruction so that we know that it's gone */
1666         }
1667
1668         /* Reset schedule ID */
1669         p->autokillid = -1;
1670
1671         if (option_debug)
1672                 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
1673         append_history(p, "AutoDestroy", "");
1674         if (p->owner) {
1675                 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
1676                 ast_queue_hangup(p->owner);
1677         } else {
1678                 sip_destroy(p);
1679         }
1680         return 0;
1681 }
1682
1683 /*! \brief Schedule destruction of SIP call */
1684 static int sip_scheddestroy(struct sip_pvt *p, int ms)
1685 {
1686         if (sip_debug_test_pvt(p))
1687                 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
1688         if (recordhistory)
1689                 append_history(p, "SchedDestroy", "%d ms", ms);
1690
1691         if (p->autokillid > -1)
1692                 ast_sched_del(sched, p->autokillid);
1693         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
1694         return 0;
1695 }
1696
1697 /*! \brief Cancel destruction of SIP dialog */
1698 static int sip_cancel_destroy(struct sip_pvt *p)
1699 {
1700         if (p->autokillid > -1) {
1701                 ast_sched_del(sched, p->autokillid);
1702                 append_history(p, "CancelDestroy", "");
1703                 p->autokillid = -1;
1704         }
1705         return 0;
1706 }
1707
1708 /*! \brief Acknowledges receipt of a packet and stops retransmission */
1709 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod, int reset)
1710 {
1711         struct sip_pkt *cur, *prev = NULL;
1712         int res = -1;
1713
1714         /* Just in case... */
1715         char *msg;
1716
1717         msg = sip_methods[sipmethod].text;
1718
1719         ast_mutex_lock(&p->lock);
1720         for (cur = p->packets; cur; prev = cur, cur = cur->next) {
1721                 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1722                         ((ast_test_flag(cur, FLAG_RESPONSE)) || 
1723                          (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1724                         if (!resp && (seqno == p->pendinginvite)) {
1725                                 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
1726                                 p->pendinginvite = 0;
1727                         }
1728                         /* this is our baby */
1729                         UNLINK(cur, p->packets, prev);
1730                         if (cur->retransid > -1) {
1731                                 if (sipdebug && option_debug > 3)
1732                                         ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
1733                                 ast_sched_del(sched, cur->retransid);
1734                         }
1735                         if (!reset)
1736                                 free(cur);
1737                         res = 0;
1738                         break;
1739                 }
1740         }
1741         ast_mutex_unlock(&p->lock);
1742         if (option_debug)
1743                 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
1744         return res;
1745 }
1746
1747 /*! \brief Pretend to ack all packets */
1748 /* maybe the lock on p is not strictly necessary but there might be a race */
1749 static int __sip_pretend_ack(struct sip_pvt *p)
1750 {
1751         struct sip_pkt *cur = NULL;
1752
1753         while (p->packets) {
1754                 int method;
1755                 if (cur == p->packets) {
1756                         ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
1757                         return -1;
1758                 }
1759                 cur = p->packets;
1760                 method = (cur->method) ? cur->method : find_sip_method(cur->data);
1761                 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method, FALSE);
1762         }
1763         return 0;
1764 }
1765
1766 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
1767 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1768 {
1769         struct sip_pkt *cur;
1770         int res = -1;
1771
1772         for (cur = p->packets; cur; cur = cur->next) {
1773                 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
1774                         (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
1775                         /* this is our baby */
1776                         if (cur->retransid > -1) {
1777                                 if (option_debug > 3 && sipdebug)
1778                                         ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
1779                                 ast_sched_del(sched, cur->retransid);
1780                         }
1781                         cur->retransid = -1;
1782                         res = 0;
1783                         break;
1784                 }
1785         }
1786         if (option_debug)
1787                 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");
1788         return res;
1789 }
1790
1791
1792 /*! \brief Copy SIP request, parse it */
1793 static void parse_copy(struct sip_request *dst, struct sip_request *src)
1794 {
1795         memset(dst, 0, sizeof(*dst));
1796         memcpy(dst->data, src->data, sizeof(dst->data));
1797         dst->len = src->len;
1798         parse_request(dst);
1799 }
1800
1801 /* add a blank line if no body */
1802 static void add_blank(struct sip_request *req)
1803 {
1804         if (!req->lines) {
1805                 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
1806                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1807                 req->len += strlen(req->data + req->len);
1808         }
1809 }
1810
1811 /*! \brief Transmit response on SIP request*/
1812 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
1813 {
1814         int res;
1815
1816         add_blank(req);
1817         if (sip_debug_test_pvt(p)) {
1818                 char iabuf[INET_ADDRSTRLEN];
1819                 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
1820                         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);
1821                 else
1822                         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);
1823         }
1824         if (recordhistory) {
1825                 struct sip_request tmp;
1826                 parse_copy(&tmp, req);
1827                 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), 
1828                         tmp.method == SIP_RESPONSE ? tmp.rlPart2 : sip_methods[tmp.method].text);
1829         }
1830         res = (reliable) ?
1831                 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
1832                 __sip_xmit(p, req->data, req->len);
1833         if (res > 0)
1834                 return 0;
1835         return res;
1836 }
1837
1838 /*! \brief Send SIP Request to the other part of the dialogue */
1839 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
1840 {
1841         int res;
1842
1843         add_blank(req);
1844         if (sip_debug_test_pvt(p)) {
1845                 char iabuf[INET_ADDRSTRLEN];
1846                 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
1847                         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);
1848                 else
1849                         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);
1850         }
1851         if (recordhistory) {
1852                 struct sip_request tmp;
1853                 parse_copy(&tmp, req);
1854                 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
1855         }
1856         res = (reliable) ?
1857                 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
1858                 __sip_xmit(p, req->data, req->len);
1859         return res;
1860 }
1861
1862 /*! \brief Pick out text in brackets from character string
1863         \return pointer to terminated stripped string
1864         \param tmp input string that will be modified */
1865 static char *get_in_brackets(char *tmp)
1866 {
1867         char *parse;
1868         char *first_quote;
1869         char *first_bracket;
1870         char *second_bracket;
1871         char last_char;
1872
1873         parse = tmp;
1874         for (;;) {
1875                 first_quote = strchr(parse, '"');
1876                 first_bracket = strchr(parse, '<');
1877                 if (first_quote && first_bracket && (first_quote < first_bracket)) {
1878                         last_char = '\0';
1879                         for (parse = first_quote + 1; *parse; parse++) {
1880                                 if ((*parse == '"') && (last_char != '\\'))
1881                                         break;
1882                                 last_char = *parse;
1883                         }
1884                         if (!*parse) {
1885                                 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
1886                                 return tmp;
1887                         }
1888                         parse++;
1889                         continue;
1890                 }
1891                 if (first_bracket) {
1892                         second_bracket = strchr(first_bracket + 1, '>');
1893                         if (second_bracket) {
1894                                 *second_bracket = '\0';
1895                                 return first_bracket + 1;
1896                         } else {
1897                                 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
1898                                 return tmp;
1899                         }
1900                 }
1901                 return tmp;
1902         }
1903 }
1904
1905 /*! \brief Send SIP MESSAGE text within a call
1906         Called from PBX core sendtext() application */
1907 static int sip_sendtext(struct ast_channel *ast, const char *text)
1908 {
1909         struct sip_pvt *p = ast->tech_pvt;
1910         int debug = sip_debug_test_pvt(p);
1911
1912         if (debug)
1913                 ast_verbose("Sending text %s on %s\n", text, ast->name);
1914         if (!p)
1915                 return -1;
1916         if (ast_strlen_zero(text))
1917                 return 0;
1918         if (debug)
1919                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1920         transmit_message_with_text(p, text);
1921         return 0;       
1922 }
1923
1924 /*! \brief Update peer object in realtime storage */
1925 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
1926 {
1927         char port[10];
1928         char ipaddr[20];
1929         char regseconds[20];
1930         time_t nowtime;
1931         const char *fc = fullcontact ? "fullcontact" : NULL;
1932         
1933         time(&nowtime);
1934         nowtime += expirey;
1935         snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);   /* Expiration time */
1936         ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1937         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1938         
1939         ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
1940                 "port", port, "regseconds", regseconds,
1941                 "username", username, fc, fullcontact, NULL); /* note fc _can_ be NULL */
1942 }
1943
1944 /*! \brief Automatically add peer extension to dial plan */
1945 static void register_peer_exten(struct sip_peer *peer, int onoff)
1946 {
1947         char multi[256];
1948         char *stringp, *ext, *context;
1949         if (!ast_strlen_zero(global_regcontext)) {
1950
1951                 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
1952                 stringp = multi;
1953                 while((ext = strsep(&stringp, "&"))) {
1954                         if((context = strchr(ext, '@'))) {
1955                                 context++;
1956                                 if (!ast_context_find(context)) {
1957                                         ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
1958                                         continue;
1959                                 }
1960                                 ext = strsep(&ext, "@");
1961                                 if (onoff)
1962                                         ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
1963                                                  ast_strdup(peer->name), free, "SIP");
1964                                 else
1965                                         ast_context_remove_extension(context, ext, 1, NULL);
1966                         } else {
1967                         if (onoff)
1968                                 ast_add_extension(global_regcontext, 1, ext, 1, NULL, NULL, "Noop",
1969                                                   ast_strdup(peer->name), free, "SIP");
1970                         else
1971                                 ast_context_remove_extension(global_regcontext, ext, 1, NULL);
1972                         }
1973                 }
1974         }
1975 }
1976
1977 /*! \brief Destroy peer object from memory */
1978 static void sip_destroy_peer(struct sip_peer *peer)
1979 {
1980         if (option_debug > 2)
1981                 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
1982
1983         /* Delete it, it needs to disappear */
1984         if (peer->call)
1985                 sip_destroy(peer->call);
1986
1987         if (peer->mwipvt) {     /* We have an active subscription, delete it */
1988                 sip_destroy(peer->mwipvt);
1989         }
1990
1991         if (peer->chanvars) {
1992                 ast_variables_destroy(peer->chanvars);
1993                 peer->chanvars = NULL;
1994         }
1995         if (peer->expire > -1)
1996                 ast_sched_del(sched, peer->expire);
1997         if (peer->pokeexpire > -1)
1998                 ast_sched_del(sched, peer->pokeexpire);
1999         register_peer_exten(peer, FALSE);
2000         ast_free_ha(peer->ha);
2001         if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2002                 apeerobjs--;
2003         else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
2004                 rpeerobjs--;
2005         else
2006                 speerobjs--;
2007         clear_realm_authentication(peer->auth);
2008         peer->auth = NULL;
2009         if (peer->dnsmgr)
2010                 ast_dnsmgr_release(peer->dnsmgr);
2011         free(peer);
2012 }
2013
2014 /*! \brief Update peer data in database (if used) */
2015 static void update_peer(struct sip_peer *p, int expiry)
2016 {
2017         int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2018         if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2019             (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2020                 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2021         }
2022 }
2023
2024
2025 /*! \brief  realtime_peer: Get peer from realtime storage
2026  * Checks the "sippeers" realtime family from extconfig.conf 
2027  * \todo Consider adding check of port address when matching here to follow the same
2028  *      algorithm as for static peers. Will we break anything by adding that?
2029 */
2030 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2031 {
2032         struct sip_peer *peer;
2033         struct ast_variable *var = NULL;
2034         struct ast_variable *tmp;
2035         char iabuf[80];
2036
2037         /* First check on peer name */
2038         if (newpeername) 
2039                 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2040         else if (sin) { /* Then check on IP address for dynamic peers */
2041                 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
2042                 var = ast_load_realtime("sippeers", "host", iabuf, NULL);       /* First check for fixed IP hosts */
2043                 if (!var)
2044                         var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL);     /* Then check for registred hosts */
2045         
2046         }
2047
2048         if (!var)
2049                 return NULL;
2050
2051         for (tmp = var; tmp; tmp = tmp->next) {
2052                 /* If this is type=user, then skip this object. */
2053                 if (!strcasecmp(tmp->name, "type") &&
2054                     !strcasecmp(tmp->value, "user")) {
2055                         ast_variables_destroy(var);
2056                         return NULL;
2057                 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2058                         newpeername = tmp->value;
2059                 }
2060         }
2061         
2062         if (!newpeername) {     /* Did not find peer in realtime */
2063                 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
2064                 ast_variables_destroy(var);
2065                 return NULL;
2066         }
2067
2068         /* Peer found in realtime, now build it in memory */
2069         peer = build_peer(newpeername, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2070         if (!peer) {
2071                 ast_variables_destroy(var);
2072                 return NULL;
2073         }
2074
2075         if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2076                 /* Cache peer */
2077                 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2078                 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2079                         if (peer->expire > -1) {
2080                                 ast_sched_del(sched, peer->expire);
2081                         }
2082                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
2083                 }
2084                 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2085         } else {
2086                 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2087         }
2088         ast_variables_destroy(var);
2089
2090         return peer;
2091 }
2092
2093 /*! \brief Support routine for find_peer */
2094 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2095 {
2096         /* We know name is the first field, so we can cast */
2097         struct sip_peer *p = (struct sip_peer *) name;
2098         return  !(!inaddrcmp(&p->addr, sin) || 
2099                                         (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2100                                         (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2101 }
2102
2103 /*! \brief Locate peer by name or ip address 
2104  *      This is used on incoming SIP message to find matching peer on ip
2105         or outgoing message to find matching peer on name */
2106 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
2107 {
2108         struct sip_peer *p = NULL;
2109
2110         if (peer)
2111                 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2112         else
2113                 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2114
2115         if (!p && realtime) {
2116                 p = realtime_peer(peer, sin);
2117         }
2118         return p;
2119 }
2120
2121 /*! \brief Remove user object from in-memory storage */
2122 static void sip_destroy_user(struct sip_user *user)
2123 {
2124         if (option_debug > 2)
2125                 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2126         ast_free_ha(user->ha);
2127         if (user->chanvars) {
2128                 ast_variables_destroy(user->chanvars);
2129                 user->chanvars = NULL;
2130         }
2131         if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2132                 ruserobjs--;
2133         else
2134                 suserobjs--;
2135         free(user);
2136 }
2137
2138 /*! \brief Load user from realtime storage
2139  * Loads user from "sipusers" category in realtime (extconfig.conf)
2140  * Users are matched on From: user name (the domain in skipped) */
2141 static struct sip_user *realtime_user(const char *username)
2142 {
2143         struct ast_variable *var;
2144         struct ast_variable *tmp;
2145         struct sip_user *user = NULL;
2146
2147         var = ast_load_realtime("sipusers", "name", username, NULL);
2148
2149         if (!var)
2150                 return NULL;
2151
2152         for (tmp = var; tmp; tmp = tmp->next) {
2153                 if (!strcasecmp(tmp->name, "type") &&
2154                         !strcasecmp(tmp->value, "peer")) {
2155                         ast_variables_destroy(var);
2156                         return NULL;
2157                 }
2158         }
2159
2160         user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2161         
2162         if (!user) {    /* No user found */
2163                 ast_variables_destroy(var);
2164                 return NULL;
2165         }
2166
2167         if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2168                 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2169                 suserobjs++;
2170                 ASTOBJ_CONTAINER_LINK(&userl,user);
2171         } else {
2172                 /* Move counter from s to r... */
2173                 suserobjs--;
2174                 ruserobjs++;
2175                 ast_set_flag(&user->flags[0], SIP_REALTIME);
2176         }
2177         ast_variables_destroy(var);
2178         return user;
2179 }
2180
2181 /*! \brief Locate user by name 
2182  * Locates user by name (From: sip uri user name part) first
2183  * from in-memory list (static configuration) then from 
2184  * realtime storage (defined in extconfig.conf) */
2185 static struct sip_user *find_user(const char *name, int realtime)
2186 {
2187         struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2188         if (!u && realtime)
2189                 u = realtime_user(name);
2190         return u;
2191 }
2192
2193 /*! \brief Create address structure from peer reference.
2194  *  return -1 on error, 0 on success.
2195  */
2196 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
2197 {
2198         int natflags;
2199
2200         if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2201             (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
2202                 r->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2203                 r->recv = r->sa;
2204         } else {
2205                 return -1;
2206         }
2207
2208         ast_copy_flags(&r->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2209         ast_copy_flags(&r->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2210         r->capability = peer->capability;
2211         if (!ast_test_flag(&r->flags[1], SIP_PAGE2_VIDEOSUPPORT) && r->vrtp) {
2212                 ast_rtp_destroy(r->vrtp);
2213                 r->vrtp = NULL;
2214         }
2215         r->prefs = peer->prefs;
2216         natflags = ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE;
2217         if (r->rtp) {
2218                 if (option_debug)
2219                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", natflags);
2220                 ast_rtp_setnat(r->rtp, natflags);
2221                 ast_rtp_setdtmf(r->rtp, ast_test_flag(&r->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
2222         }
2223         if (r->vrtp) {
2224                 if (option_debug)
2225                         ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", natflags);
2226                 ast_rtp_setnat(r->vrtp, natflags);
2227                 ast_rtp_setdtmf(r->vrtp, 0);
2228         }
2229         ast_string_field_set(r, peername, peer->username);
2230         ast_string_field_set(r, authname, peer->username);
2231         ast_string_field_set(r, username, peer->username);
2232         ast_string_field_set(r, peersecret, peer->secret);
2233         ast_string_field_set(r, peermd5secret, peer->md5secret);
2234         ast_string_field_set(r, tohost, peer->tohost);
2235         ast_string_field_set(r, fullcontact, peer->fullcontact);
2236         if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2237                 char *tmpcall;
2238                 char *c;
2239                 tmpcall = ast_strdupa(r->callid);
2240                 c = strchr(tmpcall, '@');
2241                 if (c) {
2242                         *c = '\0';
2243                         ast_string_field_build(r, callid, "%s@%s", tmpcall, peer->fromdomain);
2244                 }
2245         }
2246         if (ast_strlen_zero(r->tohost)) {
2247                 char iabuf[INET_ADDRSTRLEN];
2248
2249                 ast_inet_ntoa(iabuf, sizeof(iabuf),  r->sa.sin_addr);
2250                 ast_string_field_set(r, tohost, iabuf);
2251         }
2252         if (!ast_strlen_zero(peer->fromdomain))
2253                 ast_string_field_set(r, fromdomain, peer->fromdomain);
2254         if (!ast_strlen_zero(peer->fromuser))
2255                 ast_string_field_set(r, fromuser, peer->fromuser);
2256         r->maxtime = peer->maxms;
2257         r->callgroup = peer->callgroup;
2258         r->pickupgroup = peer->pickupgroup;
2259         r->allowtransfer = peer->allowtransfer;
2260         /* Set timer T1 to RTT for this peer (if known by qualify=) */
2261         /* Minimum is settable or default to 100 ms */
2262         if (peer->maxms && peer->lastms)
2263                 r->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2264         if ((ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2265             (ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2266                 r->noncodeccapability |= AST_RTP_DTMF;
2267         else
2268                 r->noncodeccapability &= ~AST_RTP_DTMF;
2269         ast_string_field_set(r, context, peer->context);
2270         r->rtptimeout = peer->rtptimeout;
2271         r->rtpholdtimeout = peer->rtpholdtimeout;
2272         r->rtpkeepalive = peer->rtpkeepalive;
2273         if (peer->call_limit)
2274                 ast_set_flag(&r->flags[0], SIP_CALL_LIMIT);
2275         r->maxcallbitrate = peer->maxcallbitrate;
2276         
2277         return 0;
2278 }
2279
2280 /*! \brief create address structure from peer name
2281  *      Or, if peer not found, find it in the global DNS 
2282  *      returns TRUE (-1) on failure, FALSE on success */
2283 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2284 {
2285         struct hostent *hp;
2286         struct ast_hostent ahp;
2287         struct sip_peer *p;
2288         char *port;
2289         int portno;
2290         char host[MAXHOSTNAMELEN], *hostn;
2291         char peer[256];
2292
2293         ast_copy_string(peer, opeer, sizeof(peer));
2294         port = strchr(peer, ':');
2295         if (port)
2296                 *port++ = '\0';
2297         dialog->sa.sin_family = AF_INET;
2298         dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2299         p = find_peer(peer, NULL, 1);
2300
2301         if (p) {
2302                 int res = create_addr_from_peer(dialog, p);
2303                 ASTOBJ_UNREF(p, sip_destroy_peer);
2304                 return res;
2305         } else {
2306                 hostn = peer;
2307                 portno = port ? atoi(port) : DEFAULT_SIP_PORT;
2308                 if (srvlookup) {
2309                         char service[MAXHOSTNAMELEN];
2310                         int tportno;
2311                         int ret;
2312                         snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2313                         ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2314                         if (ret > 0) {
2315                                 hostn = host;
2316                                 portno = tportno;
2317                         }
2318                 }
2319                 hp = ast_gethostbyname(hostn, &ahp);
2320                 if (hp) {
2321                         ast_string_field_set(dialog, tohost, peer);
2322                         memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2323                         dialog->sa.sin_port = htons(portno);
2324                         dialog->recv = dialog->sa;
2325                         return 0;
2326                 } else {
2327                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
2328                         return -1;
2329                 }
2330         }
2331 }
2332
2333 /*! \brief Scheduled congestion on a call */
2334 static int auto_congest(void *nothing)
2335 {
2336         struct sip_pvt *p = nothing;
2337
2338         ast_mutex_lock(&p->lock);
2339         p->initid = -1;
2340         if (p->owner) {
2341                 /* XXX fails on possible deadlock */
2342                 if (!ast_channel_trylock(p->owner)) {
2343                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2344                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2345                         ast_channel_unlock(p->owner);
2346                 }
2347         }
2348         ast_mutex_unlock(&p->lock);
2349         return 0;
2350 }
2351
2352
2353 /*! \brief Initiate SIP call from PBX 
2354  *      used from the dial() application      */
2355 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2356 {
2357         int res;
2358         struct sip_pvt *p;
2359         struct varshead *headp;
2360         struct ast_var_t *current;
2361         const char *referer = NULL;   /* SIP refererer */       
2362
2363         p = ast->tech_pvt;
2364         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2365                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2366                 return -1;
2367         }
2368
2369         /* Check whether there is vxml_url, distinctive ring variables */
2370         headp=&ast->varshead;
2371         AST_LIST_TRAVERSE(headp,current,entries) {
2372                 /* Check whether there is a VXML_URL variable */
2373                 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2374                         p->options->vxml_url = ast_var_value(current);
2375                 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2376                         p->options->uri_options = ast_var_value(current);
2377                 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2378                         /* Check whether there is a ALERT_INFO variable */
2379                         p->options->distinctive_ring = ast_var_value(current);
2380                 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2381                         /* Check whether there is a variable with a name starting with SIPADDHEADER */
2382                         p->options->addsipheaders = 1;
2383                 } else if (!strcasecmp(ast_var_name(current),"SIPTRANSFER")) {
2384                         /* This is a transfered call */
2385                         p->options->transfer = 1;
2386                 } else if (!strcasecmp(ast_var_name(current),"SIPTRANSFER_REFERER")) {
2387                         /* This is the referer */
2388                         referer = ast_var_value(current);
2389                 } else if (!strcasecmp(ast_var_name(current),"SIPTRANSFER_REPLACES")) {
2390                         /* We're replacing a call. */
2391                         p->options->replaces = ast_var_value(current);
2392                 }
2393         }
2394         
2395         res = 0;
2396         ast_set_flag(&p->flags[0], SIP_OUTGOING);
2397
2398         if (p->options->transfer) {
2399                 char buf[BUFSIZ/2];
2400
2401                 if (referer) {
2402                         if (sipdebug && option_debug > 2)
2403                                 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
2404                         snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
2405                 } else {
2406                         snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
2407                 }
2408                 ast_string_field_set(p, cid_name, buf);
2409         } 
2410         if (option_debug)
2411                 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2412
2413         res = update_call_counter(p, INC_CALL_LIMIT);
2414         if ( res != -1 ) {
2415                 p->callingpres = ast->cid.cid_pres;
2416                 p->jointcapability = p->capability;
2417                 transmit_invite(p, SIP_INVITE, 1, 2);
2418                 if (p->maxtime) {
2419                         /* Initialize auto-congest time */
2420                         p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
2421                 } else {
2422                         p->initid = ast_sched_add(sched, SIP_TRANS_TIMEOUT, auto_congest, p);
2423                 }
2424         }
2425         return res;
2426 }
2427
2428 /*! \brief Destroy registry object
2429         Objects created with the register= statement in static configuration */
2430 static void sip_registry_destroy(struct sip_registry *reg)
2431 {
2432         /* Really delete */
2433         if (option_debug > 2)
2434                 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
2435
2436         if (reg->call) {
2437                 /* Clear registry before destroying to ensure
2438                    we don't get reentered trying to grab the registry lock */
2439                 reg->call->registry = NULL;
2440                 if (option_debug > 2)
2441                         ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
2442                 sip_destroy(reg->call);
2443         }
2444         if (reg->expire > -1)
2445                 ast_sched_del(sched, reg->expire);
2446         if (reg->timeout > -1)
2447                 ast_sched_del(sched, reg->timeout);
2448         ast_string_field_free_all(reg);
2449         regobjs--;
2450         free(reg);
2451         
2452 }
2453
2454 /*! \brief Execute destruction of SIP dialog structure, release memory */
2455 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2456 {
2457         struct sip_pvt *cur, *prev = NULL;
2458         struct sip_pkt *cp;
2459
2460         if (sip_debug_test_pvt(p) || option_debug > 2)
2461                 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2462
2463         /* Remove link from peer to subscription of MWI */
2464         if (p->relatedpeer && p->relatedpeer->mwipvt)
2465                 p->relatedpeer->mwipvt = NULL;
2466
2467         if (dumphistory)
2468                 sip_dump_history(p);
2469
2470         if (p->options)
2471                 free(p->options);
2472
2473         if (p->stateid > -1)
2474                 ast_extension_state_del(p->stateid, NULL);
2475         if (p->initid > -1)
2476                 ast_sched_del(sched, p->initid);
2477         if (p->autokillid > -1)
2478                 ast_sched_del(sched, p->autokillid);
2479
2480         if (p->rtp)
2481                 ast_rtp_destroy(p->rtp);
2482         if (p->vrtp)
2483                 ast_rtp_destroy(p->vrtp);
2484         if (p->refer)
2485                 free(p->refer);
2486         if (p->route) {
2487                 free_old_route(p->route);
2488                 p->route = NULL;
2489         }
2490         if (p->registry) {
2491                 if (p->registry->call == p)
2492                         p->registry->call = NULL;
2493                 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
2494         }
2495
2496         /* Unlink us from the owner if we have one */
2497         if (p->owner) {
2498                 if (lockowner)
2499                         ast_channel_lock(p->owner);
2500                 if (option_debug)
2501                         ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2502                 p->owner->tech_pvt = NULL;
2503                 if (lockowner)
2504                         ast_channel_unlock(p->owner);
2505         }
2506         /* Clear history */
2507         if (p->history) {
2508                 struct sip_history *hist;
2509                 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
2510                         free(hist);
2511                 free(p->history);
2512                 p->history = NULL;
2513         }
2514
2515         for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
2516                 if (cur == p) {
2517                         UNLINK(cur, iflist, prev);
2518                         break;
2519                 }
2520         }
2521         if (!cur) {
2522                 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2523                 return;
2524         } 
2525         if (p->initid > -1)
2526                 ast_sched_del(sched, p->initid);
2527
2528         /* remove all current packets in this dialog */
2529         while((cp = p->packets)) {
2530                 p->packets = p->packets->next;
2531                 if (cp->retransid > -1)
2532                         ast_sched_del(sched, cp->retransid);
2533                 free(cp);
2534         }
2535         if (p->chanvars) {
2536                 ast_variables_destroy(p->chanvars);
2537                 p->chanvars = NULL;
2538         }
2539         ast_mutex_destroy(&p->lock);
2540
2541         ast_string_field_free_all(p);
2542
2543         free(p);
2544 }
2545
2546 /*! \brief  update_call_counter: Handle call_limit for SIP users 
2547  * Setting a call-limit will cause calls above the limit not to be accepted.
2548  *
2549  * Remember that for a type=friend, there's one limit for the user and
2550  * another for the peer, not a combined call limit.
2551  * This will cause unexpected behaviour in subscriptions, since a "friend"
2552  * is *two* devices in Asterisk, not one.
2553  *
2554  * Thought: For realtime, we should propably update storage with inuse counter... 
2555  *
2556  * \return 0 if call is ok (no call limit, below treshold)
2557  *      -1 on rejection of call
2558  *              
2559  */
2560 static int update_call_counter(struct sip_pvt *fup, int event)
2561 {
2562         char name[256];
2563         int *inuse, *call_limit;
2564         int outgoing = ast_test_flag(&fup->flags[0], SIP_OUTGOING);
2565         struct sip_user *u = NULL;
2566         struct sip_peer *p = NULL;
2567
2568         if (option_debug > 2)
2569                 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
2570         /* Test if we need to check call limits, in order to avoid 
2571            realtime lookups if we do not need it */
2572         if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
2573                 return 0;
2574
2575         ast_copy_string(name, fup->username, sizeof(name));
2576
2577         /* Check the list of users */
2578         if (!outgoing)  /* Only check users for incoming calls */
2579                 u = find_user(name, 1);
2580
2581         if (u) {
2582                 inuse = &u->inUse;
2583                 call_limit = &u->call_limit;
2584                 p = NULL;
2585         } else {
2586                 /* Try to find peer */
2587                 if (!p)
2588                         p = find_peer(fup->peername, NULL, 1);
2589                 if (p) {
2590                         inuse = &p->inUse;
2591                         call_limit = &p->call_limit;
2592                         ast_copy_string(name, fup->peername, sizeof(name));
2593                 } else {
2594                         if (option_debug > 1)
2595                                 ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
2596                         return 0;
2597                 }
2598         }
2599         switch(event) {
2600                 /* incoming and outgoing affects the inUse counter */
2601                 case DEC_CALL_LIMIT:
2602                         if ( *inuse > 0 ) {
2603                                 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT))
2604                                         (*inuse)--;
2605                         } else {
2606                                 *inuse = 0;
2607                         }
2608                         if (option_debug > 1 || sipdebug) {
2609                                 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2610                         }
2611                         break;
2612                 case INC_CALL_LIMIT:
2613                         if (*call_limit > 0 ) {
2614                                 if (*inuse >= *call_limit) {
2615                                         ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2616                                         if (u)
2617                                                 ASTOBJ_UNREF(u, sip_destroy_user);
2618                                         else
2619                                                 ASTOBJ_UNREF(p, sip_destroy_peer);
2620                                         return -1; 
2621                                 }
2622                         }
2623                         (*inuse)++;
2624                         ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
2625                         if (option_debug > 1 || sipdebug) {
2626                                 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
2627                         }
2628                         break;
2629                 default:
2630                         ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
2631         }
2632         if (u)
2633                 ASTOBJ_UNREF(u, sip_destroy_user);
2634         else
2635                 ASTOBJ_UNREF(p, sip_destroy_peer);
2636         return 0;
2637 }
2638
2639 /*! \brief Destroy SIP call structure */
2640 static void sip_destroy(struct sip_pvt *p)
2641 {
2642         ast_mutex_lock(&iflock);
2643         if (option_debug > 2)
2644                 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
2645         __sip_destroy(p, 1);
2646         ast_mutex_unlock(&iflock);
2647 }
2648
2649 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
2650 static int hangup_sip2cause(int cause)
2651 {
2652         /* Possible values taken from causes.h */
2653
2654         switch(cause) {
2655                 case 401:       /* Unauthorized */
2656                         return AST_CAUSE_CALL_REJECTED;
2657                 case 403:       /* Not found */
2658                         return AST_CAUSE_CALL_REJECTED;
2659                 case 404:       /* Not found */
2660                         return AST_CAUSE_UNALLOCATED;
2661                 case 405:       /* Method not allowed */
2662                         return AST_CAUSE_INTERWORKING;
2663                 case 407:       /* Proxy authentication required */
2664                         return AST_CAUSE_CALL_REJECTED;
2665                 case 408:       /* No reaction */
2666                         return AST_CAUSE_NO_USER_RESPONSE;
2667                 case 409:       /* Conflict */
2668                         return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
2669                 case 410:       /* Gone */
2670                         return AST_CAUSE_UNALLOCATED;
2671                 case 411:       /* Length required */
2672                         return AST_CAUSE_INTERWORKING;
2673                 case 413:       /* Request entity too large */
2674                         return AST_CAUSE_INTERWORKING;
2675                 case 414:       /* Request URI too large */
2676                         return AST_CAUSE_INTERWORKING;
2677                 case 415:       /* Unsupported media type */
2678                         return AST_CAUSE_INTERWORKING;
2679                 case 420:       /* Bad extension */
2680                         return AST_CAUSE_NO_ROUTE_DESTINATION;
2681                 case 480:       /* No answer */
2682                         return AST_CAUSE_NO_ANSWER;
2683                 case 481:       /* No answer */
2684                         return AST_CAUSE_INTERWORKING;
2685                 case 482:       /* Loop detected */
2686                         return AST_CAUSE_INTERWORKING;
2687                 case 483:       /* Too many hops */
2688                         return AST_CAUSE_NO_ANSWER;
2689                 case 484:       /* Address incomplete */
2690                         return AST_CAUSE_INVALID_NUMBER_FORMAT;
2691                 case 485:       /* Ambigous */
2692                         return AST_CAUSE_UNALLOCATED;
2693                 case 486:       /* Busy everywhere */
2694                         return AST_CAUSE_BUSY;
2695                 case 487:       /* Request terminated */
2696                         return AST_CAUSE_INTERWORKING;
2697                 case 488:       /* No codecs approved */
2698                         return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2699                 case 491:       /* Request pending */
2700                         return AST_CAUSE_INTERWORKING;
2701                 case 493:       /* Undecipherable */
2702                         return AST_CAUSE_INTERWORKING;
2703                 case 500:       /* Server internal failure */
2704                         return AST_CAUSE_FAILURE;
2705                 case 501:       /* Call rejected */
2706                         return AST_CAUSE_FACILITY_REJECTED;
2707                 case 502:       
2708                         return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2709                 case 503:       /* Service unavailable */
2710                         return AST_CAUSE_CONGESTION;
2711                 case 504:       /* Gateway timeout */
2712                         return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
2713                 case 505:       /* SIP version not supported */
2714                         return AST_CAUSE_INTERWORKING;
2715                 case 600:       /* Busy everywhere */
2716                         return AST_CAUSE_USER_BUSY;
2717                 case 603:       /* Decline */
2718                         return AST_CAUSE_CALL_REJECTED;
2719                 case 604:       /* Does not exist anywhere */
2720                         return AST_CAUSE_UNALLOCATED;
2721                 case 606:       /* Not acceptable */
2722                         return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2723                 default:
2724                         return AST_CAUSE_NORMAL;
2725         }
2726         /* Never reached */
2727         return 0;
2728 }
2729
2730 /*! \brief Convert Asterisk hangup causes to SIP codes 
2731 \verbatim
2732  Possible values from causes.h
2733         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
2734         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
2735
2736         In addition to these, a lot of PRI codes is defined in causes.h 
2737         ...should we take care of them too ?
2738         
2739         Quote RFC 3398
2740
2741    ISUP Cause value                        SIP response
2742    ----------------                        ------------
2743    1  unallocated number                   404 Not Found
2744    2  no route to network                  404 Not found
2745    3  no route to destination              404 Not found
2746    16 normal call clearing                 --- (*)
2747    17 user busy                            486 Busy here
2748    18 no user responding                   408 Request Timeout
2749    19 no answer from the user              480 Temporarily unavailable
2750    20 subscriber absent                    480 Temporarily unavailable
2751    21 call rejected                        403 Forbidden (+)
2752    22 number changed (w/o diagnostic)      410 Gone
2753    22 number changed (w/ diagnostic)       301 Moved Permanently
2754    23 redirection to new destination       410 Gone
2755    26 non-selected user clearing           404 Not Found (=)
2756    27 destination out of order             502 Bad Gateway
2757    28 address incomplete                   484 Address incomplete
2758    29 facility rejected                    501 Not implemented
2759    31 normal unspecified                   480 Temporarily unavailable
2760 \endverbatim
2761 */
2762 static const char *hangup_cause2sip(int cause)
2763 {
2764         switch (cause) {
2765                 case AST_CAUSE_UNALLOCATED:             /* 1 */
2766                 case AST_CAUSE_NO_ROUTE_DESTINATION:    /* 3 IAX2: Can't find extension in context */
2767                 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:    /* 2 */
2768                         return "404 Not Found";
2769                 case AST_CAUSE_CONGESTION:              /* 34 */
2770                 case AST_CAUSE_SWITCH_CONGESTION:       /* 42 */
2771                         return "503 Service Unavailable";
2772                 case AST_CAUSE_NO_USER_RESPONSE:        /* 18 */
2773                         return "408 Request Timeout";
2774                 case AST_CAUSE_NO_ANSWER:               /* 19 */
2775                         return "480 Temporarily unavailable";
2776                 case AST_CAUSE_CALL_REJECTED:           /* 21 */
2777                         return "403 Forbidden";
2778                 case AST_CAUSE_NUMBER_CHANGED:          /* 22 */
2779                         return "410 Gone";
2780                 case AST_CAUSE_NORMAL_UNSPECIFIED:      /* 31 */
2781                         return "480 Temporarily unavailable";
2782                 case AST_CAUSE_INVALID_NUMBER_FORMAT:
2783                         return "484 Address incomplete";
2784                 case AST_CAUSE_USER_BUSY:
2785                         return "486 Busy here";
2786                 case AST_CAUSE_FAILURE:
2787                         return "500 Server internal failure";
2788                 case AST_CAUSE_FACILITY_REJECTED:       /* 29 */
2789                         return "501 Not Implemented";
2790                 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2791                         return "503 Service Unavailable";
2792                 /* Used in chan_iax2 */
2793                 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2794                         return "502 Bad Gateway";
2795                 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:       /* Can't find codec to connect to host */
2796                         return "488 Not Acceptable Here";
2797                         
2798                 case AST_CAUSE_NOTDEFINED:
2799                 default:
2800                         ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
2801                         return NULL;
2802         }
2803
2804         /* Never reached */
2805         return 0;
2806 }
2807
2808
2809 /*! \brief  sip_hangup: Hangup SIP call
2810  * Part of PBX interface, called from ast_hangup */
2811 static int sip_hangup(struct ast_channel *ast)
2812 {
2813         struct sip_pvt *p = ast->tech_pvt;
2814         int needcancel = FALSE;
2815         struct ast_flags locflags = {0};
2816
2817         if (!p) {
2818                 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
2819                 return 0;
2820         }
2821         if (option_debug && sipdebug)
2822                 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
2823
2824         ast_mutex_lock(&p->lock);
2825         if (option_debug && sipdebug)
2826                 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
2827         update_call_counter(p, DEC_CALL_LIMIT);
2828         /* Determine how to disconnect */
2829         if (p->owner != ast) {
2830                 ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
2831                 ast_mutex_unlock(&p->lock);
2832                 return 0;
2833         }
2834         /* If the call is not UP, we need to send CANCEL instead of BYE */
2835         if (ast->_state != AST_STATE_UP)
2836                 needcancel = TRUE;
2837
2838         /* Disconnect */
2839         p = ast->tech_pvt;
2840         if (p->vad)
2841                 ast_dsp_free(p->vad);
2842
2843         p->owner = NULL;
2844         ast->tech_pvt = NULL;
2845
2846         ast_mutex_lock(&usecnt_lock);
2847         usecnt--;
2848         ast_mutex_unlock(&usecnt_lock);
2849         ast_update_use_count();
2850
2851         ast_set_flag(&locflags, SIP_NEEDDESTROY);       
2852
2853         /* Start the process if it's not already started */
2854         if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
2855                 if (needcancel) {       /* Outgoing call, not up */
2856                         if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2857                                 /* stop retransmitting an INVITE that has not received a response */
2858                                 __sip_pretend_ack(p);
2859
2860                                 /* Send a new request: CANCEL */
2861                                 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
2862                                 /* Actually don't destroy us yet, wait for the 487 on our original 
2863                                    INVITE, but do set an autodestruct just in case we never get it. */
2864                                 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
2865
2866                                 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
2867                                 if ( p->initid != -1 ) {
2868                                         /* channel still up - reverse dec of inUse counter
2869                                            only if the channel is not auto-congested */
2870                                         update_call_counter(p, INC_CALL_LIMIT);
2871                                 }
2872                         } else {        /* Incoming call, not up */
2873                                 const char *res;
2874                                 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
2875                                         transmit_response_reliable(p, res, &p->initreq);
2876                                 else 
2877                                         transmit_response_reliable(p, "603 Declined", &p->initreq);
2878                         }
2879                 } else {        /* Call is in UP state, send BYE */
2880                         if (!p->pendinginvite) {
2881                                 /* Send a hangup */
2882                                 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2883                         } else {
2884                                 /* Note we will need a BYE when this all settles out
2885                                    but we can't send one while we have "INVITE" outstanding. */
2886                                 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);     
2887                                 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
2888                         }
2889                 }
2890         }
2891         ast_copy_flags(&p->flags[0], &locflags, SIP_NEEDDESTROY);       
2892         ast_mutex_unlock(&p->lock);
2893         return 0;
2894 }
2895
2896 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
2897 static void try_suggested_sip_codec(struct sip_pvt *p)
2898 {
2899         int fmt;
2900         const char *codec;
2901
2902         codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
2903         if (!codec) 
2904                 return;
2905
2906         fmt = ast_getformatbyname(codec);
2907         if (fmt) {
2908                 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n", codec);
2909                 if (p->jointcapability & fmt) {
2910                         p->jointcapability &= fmt;
2911                         p->capability &= fmt;
2912                 } else
2913                         ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
2914         } else
2915                 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
2916         return; 
2917 }
2918
2919 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
2920  * Part of PBX interface */
2921 static int sip_answer(struct ast_channel *ast)
2922 {
2923         int res = 0;
2924         struct sip_pvt *p = ast->tech_pvt;
2925
2926         ast_mutex_lock(&p->lock);
2927         if (ast->_state != AST_STATE_UP) {
2928                 try_suggested_sip_codec(p);     
2929
2930                 ast_setstate(ast, AST_STATE_UP);
2931                 if (option_debug)
2932                         ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
2933                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
2934         }
2935         ast_mutex_unlock(&p->lock);
2936         return res;
2937 }
2938
2939 /*! \brief Send frame to media channel (rtp) */
2940 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
2941 {
2942         struct sip_pvt *p = ast->tech_pvt;
2943         int res = 0;
2944
2945         switch (frame->frametype) {
2946         case AST_FRAME_VOICE:
2947                 if (!(frame->subclass & ast->nativeformats)) {
2948                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2949                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2950                         return 0;
2951                 }
2952                 if (p) {
2953                         ast_mutex_lock(&p->lock);
2954                         if (p->rtp) {
2955                                 /* If channel is not up, activate early media session */
2956                                 if ((ast->_state != AST_STATE_UP) &&
2957                                     !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2958                                     !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2959                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2960                                         ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);  
2961                                 }
2962                                 time(&p->lastrtptx);
2963                                 res =  ast_rtp_write(p->rtp, frame);
2964                         }
2965                         ast_mutex_unlock(&p->lock);
2966                 }
2967                 break;
2968         case AST_FRAME_VIDEO:
2969                 if (p) {
2970                         ast_mutex_lock(&p->lock);
2971                         if (p->vrtp) {
2972                                 /* Activate video early media */
2973                                 if ((ast->_state != AST_STATE_UP) &&
2974                                     !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2975                                     !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2976                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2977                                         ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);  
2978                                 }
2979                                 time(&p->lastrtptx);
2980                                 res =  ast_rtp_write(p->vrtp, frame);
2981                         }
2982                         ast_mutex_unlock(&p->lock);
2983                 }
2984                 break;
2985         case AST_FRAME_IMAGE:
2986                 return 0;
2987                 break;
2988         default: 
2989                 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
2990                 return 0;
2991         }
2992
2993         return res;
2994 }
2995
2996 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
2997         Basically update any ->owner links */
2998 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2999 {
3000         int ret = -1;
3001         struct sip_pvt *p;
3002
3003         if (!newchan || !newchan->tech_pvt) {
3004                 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
3005                 return -1;
3006         }
3007         p = newchan->tech_pvt;
3008
3009         ast_mutex_lock(&p->lock);
3010         append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
3011         append_history(p, "Masq (cont)", "...new owner: %s\n", p->owner->name);
3012         if (p->owner != oldchan)
3013                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
3014         else {
3015                 p->owner = newchan;
3016                 ret = 0;
3017         }
3018         ast_mutex_unlock(&p->lock);
3019         return ret;
3020 }
3021
3022 /*! \brief Send DT