4a8ea43463a5df58723250b73004a27da2277acf
[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 #include "asterisk.h"
87
88 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
89
90 #include <stdio.h>
91 #include <ctype.h>
92 #include <string.h>
93 #include <unistd.h>
94 #include <sys/socket.h>
95 #include <sys/ioctl.h>
96 #include <net/if.h>
97 #include <errno.h>
98 #include <stdlib.h>
99 #include <fcntl.h>
100 #include <netdb.h>
101 #include <signal.h>
102 #include <sys/signal.h>
103 #include <netinet/in.h>
104 #include <netinet/in_systm.h>
105 #include <arpa/inet.h>
106 #include <netinet/ip.h>
107 #include <regex.h>
108
109 #include "asterisk/lock.h"
110 #include "asterisk/channel.h"
111 #include "asterisk/config.h"
112 #include "asterisk/logger.h"
113 #include "asterisk/module.h"
114 #include "asterisk/pbx.h"
115 #include "asterisk/options.h"
116 #include "asterisk/sched.h"
117 #include "asterisk/io.h"
118 #include "asterisk/rtp.h"
119 #include "asterisk/udptl.h"
120 #include "asterisk/acl.h"
121 #include "asterisk/manager.h"
122 #include "asterisk/callerid.h"
123 #include "asterisk/cli.h"
124 #include "asterisk/app.h"
125 #include "asterisk/musiconhold.h"
126 #include "asterisk/dsp.h"
127 #include "asterisk/features.h"
128 #include "asterisk/srv.h"
129 #include "asterisk/astdb.h"
130 #include "asterisk/causes.h"
131 #include "asterisk/utils.h"
132 #include "asterisk/file.h"
133 #include "asterisk/astobj.h"
134 #include "asterisk/dnsmgr.h"
135 #include "asterisk/devicestate.h"
136 #include "asterisk/linkedlists.h"
137 #include "asterisk/stringfields.h"
138 #include "asterisk/monitor.h"
139 #include "asterisk/netsock.h"
140 #include "asterisk/localtime.h"
141 #include "asterisk/abstract_jb.h"
142 #include "asterisk/compiler.h"
143 #include "asterisk/threadstorage.h"
144 #include "asterisk/translate.h"
145 #include "asterisk/version.h"
146 #include "asterisk/event.h"
147
148 #ifndef FALSE
149 #define FALSE    0
150 #endif
151
152 #ifndef TRUE
153 #define TRUE     1
154 #endif
155
156 #define XMIT_ERROR              -2
157
158 #define VIDEO_CODEC_MASK        0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
159 #ifndef IPTOS_MINCOST
160 #define IPTOS_MINCOST           0x02
161 #endif
162
163 /* #define VOCAL_DATA_HACK */
164
165 #define DEFAULT_DEFAULT_EXPIRY  120
166 #define DEFAULT_MIN_EXPIRY      60
167 #define DEFAULT_MAX_EXPIRY      3600
168 #define DEFAULT_REGISTRATION_TIMEOUT 20
169 #define DEFAULT_MAX_FORWARDS    "70"
170
171 /* guard limit must be larger than guard secs */
172 /* guard min must be < 1000, and should be >= 250 */
173 #define EXPIRY_GUARD_SECS       15                /*!< How long before expiry do we reregister */
174 #define EXPIRY_GUARD_LIMIT      30                /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
175                                                          EXPIRY_GUARD_SECS */
176 #define EXPIRY_GUARD_MIN        500                /*!< This is the minimum guard time applied. If 
177                                                    GUARD_PCT turns out to be lower than this, it 
178                                                    will use this time instead.
179                                                    This is in milliseconds. */
180 #define EXPIRY_GUARD_PCT        0.20                /*!< Percentage of expires timeout to use when 
181                                                     below EXPIRY_GUARD_LIMIT */
182 #define DEFAULT_EXPIRY 900                          /*!< Expire slowly */
183
184 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
185 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
186 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
187 static int expiry = DEFAULT_EXPIRY;
188
189 #ifndef MAX
190 #define MAX(a,b) ((a) > (b) ? (a) : (b))
191 #endif
192
193 #define CALLERID_UNKNOWN        "Unknown"
194
195 #define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
196 #define DEFAULT_FREQ_OK              60 * 1000        /*!< Qualification: How often to check for the host to be up */
197 #define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */
198
199 #define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
200 #define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
201 #define SIP_TIMER_T1                 500              /* SIP timer T1 (according to RFC 3261) */
202 #define SIP_TRANS_TIMEOUT            32000            /*!< SIP request timeout (rfc 3261) 64*T1 
203                                                       \todo Use known T1 for timeout (peerpoke)
204                                                       */
205 #define DEFAULT_TRANS_TIMEOUT        -1               /* Use default SIP transaction timeout */
206 #define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */
207
208 #define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
209 #define SIP_MAX_LINES                64               /*!< Max amount of lines in SIP attachment (like SDP) */
210 #define SIP_MAX_PACKET               4096             /*!< Also from RFC 3261 (2543), should sub headers tho */
211
212 #define INITIAL_CSEQ                 101              /*!< our initial sip sequence number */
213
214 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
215 static struct ast_jb_conf default_jbconf =
216 {
217         .flags = 0,
218         .max_size = -1,
219         .resync_threshold = -1,
220         .impl = ""
221 };
222 static struct ast_jb_conf global_jbconf;
223
224 static const char config[] = "sip.conf";
225 static const char notify_config[] = "sip_notify.conf";
226
227 #define RTP     1
228 #define NO_RTP  0
229
230 /*! \brief Authorization scheme for call transfers 
231 \note Not a bitfield flag, since there are plans for other modes,
232         like "only allow transfers for authenticated devices" */
233 enum transfermodes {
234         TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
235         TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
236 };
237
238
239 enum sip_result {
240         AST_SUCCESS = 0,
241         AST_FAILURE = -1,
242 };
243
244 /*! \brief States for the INVITE transaction, not the dialog 
245         \note this is for the INVITE that sets up the dialog
246 */
247 enum invitestates {
248         INV_NONE = 0,           /*!< No state at all, maybe not an INVITE dialog */
249         INV_CALLING = 1,        /*!< Invite sent, no answer */
250         INV_PROCEEDING = 2,     /*!< We got/sent 1xx message */
251         INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
252         INV_COMPLETED = 4,      /*!< Got final response with error. Wait for ACK, then CONFIRMED */
253         INV_CONFIRMED = 5,      /*!< Confirmed response - we've got an ack (Incoming calls only) */
254         INV_TERMINATED = 6,     /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
255                                      The only way out of this is a BYE from one side */
256         INV_CANCELLED = 7,      /*!< Transaction cancelled by client or server in non-terminated state */
257 };
258
259 /* Do _NOT_ make any changes to this enum, or the array following it;
260    if you think you are doing the right thing, you are probably
261    not doing the right thing. If you think there are changes
262    needed, get someone else to review them first _before_
263    submitting a patch. If these two lists do not match properly
264    bad things will happen.
265 */
266
267 enum xmittype {
268         XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
269                                               If it fails, it's critical and will cause a teardown of the session */
270         XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
271         XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
272 };
273
274 enum parse_register_result {
275         PARSE_REGISTER_FAILED,
276         PARSE_REGISTER_UPDATE,
277         PARSE_REGISTER_QUERY,
278 };
279
280 enum subscriptiontype { 
281         NONE = 0,
282         XPIDF_XML,
283         DIALOG_INFO_XML,
284         CPIM_PIDF_XML,
285         PIDF_XML,
286         MWI_NOTIFICATION
287 };
288
289 static const struct cfsubscription_types {
290         enum subscriptiontype type;
291         const char * const event;
292         const char * const mediatype;
293         const char * const text;
294 } subscription_types[] = {
295         { NONE,            "-",        "unknown",                    "unknown" },
296         /* RFC 4235: SIP Dialog event package */
297         { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
298         { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
299         { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
300         { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
301         { MWI_NOTIFICATION,     "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
302 };
303
304 /*! \brief SIP Request methods known by Asterisk */
305 enum sipmethod {
306         SIP_UNKNOWN,            /* Unknown response */
307         SIP_RESPONSE,           /* Not request, response to outbound request */
308         SIP_REGISTER,
309         SIP_OPTIONS,
310         SIP_NOTIFY,
311         SIP_INVITE,
312         SIP_ACK,
313         SIP_PRACK,              /* Not supported at all */
314         SIP_BYE,
315         SIP_REFER,
316         SIP_SUBSCRIBE,
317         SIP_MESSAGE,
318         SIP_UPDATE,             /* We can send UPDATE; but not accept it */
319         SIP_INFO,
320         SIP_CANCEL,
321         SIP_PUBLISH,            /* Not supported at all */
322         SIP_PING,               /* Not supported at all, no standard but still implemented out there */
323 };
324
325 /*! \brief Authentication types - proxy or www authentication 
326         \note Endpoints, like Asterisk, should always use WWW authentication to
327         allow multiple authentications in the same call - to the proxy and
328         to the end point.
329 */
330 enum sip_auth_type {
331         PROXY_AUTH = 407,
332         WWW_AUTH = 401,
333 };
334
335 /*! \brief Authentication result from check_auth* functions */
336 enum check_auth_result {
337         AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
338                 /* XXX maybe this is the same as AUTH_NOT_FOUND */
339
340         AUTH_SUCCESSFUL = 0,
341         AUTH_CHALLENGE_SENT = 1,
342         AUTH_SECRET_FAILED = -1,
343         AUTH_USERNAME_MISMATCH = -2,
344         AUTH_NOT_FOUND = -3,    /* returned by register_verify */
345         AUTH_FAKE_AUTH = -4,
346         AUTH_UNKNOWN_DOMAIN = -5,
347         AUTH_PEER_NOT_DYNAMIC = -6,
348         AUTH_ACL_FAILED = -7,
349 };
350
351 /*! \brief States for outbound registrations (with register= lines in sip.conf */
352 enum sipregistrystate {
353         REG_STATE_UNREGISTERED = 0,     /*!< We are not registred */
354         REG_STATE_REGSENT,      /*!< Registration request sent */
355         REG_STATE_AUTHSENT,     /*!< We have tried to authenticate */
356         REG_STATE_REGISTERED,   /*!< Registered and done */
357         REG_STATE_REJECTED,     /*!< Registration rejected */
358         REG_STATE_TIMEOUT,      /*!< Registration timed out */
359         REG_STATE_NOAUTH,       /*!< We have no accepted credentials */
360         REG_STATE_FAILED,       /*!< Registration failed after several tries */
361 };
362
363 /*! \brief definition of a sip proxy server
364  *
365  * For outbound proxies, this is allocated in the SIP peer dynamically or
366  * statically as the global_outboundproxy. The pointer in a SIP message is just
367  * a pointer and should *not* be de-allocated.
368  */
369 struct sip_proxy {
370         char name[MAXHOSTNAMELEN];      /*!< DNS name of domain/host or IP */
371         struct sockaddr_in ip;          /*!< Currently used IP address and port */
372         time_t last_dnsupdate;          /*!< When this was resolved */
373         int force;                      /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
374         /* Room for a SRV record chain based on the name */
375 };
376
377 enum can_create_dialog {
378         CAN_NOT_CREATE_DIALOG,
379         CAN_CREATE_DIALOG,
380         CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
381 };
382
383 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
384 static const struct  cfsip_methods { 
385         enum sipmethod id;
386         int need_rtp;           /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
387         char * const text;
388         enum can_create_dialog can_create;
389 } sip_methods[] = {
390         { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",   CAN_CREATE_DIALOG },
391         { SIP_RESPONSE,  NO_RTP, "SIP/2.0",     CAN_NOT_CREATE_DIALOG },
392         { SIP_REGISTER,  NO_RTP, "REGISTER",    CAN_CREATE_DIALOG },
393         { SIP_OPTIONS,   NO_RTP, "OPTIONS",     CAN_CREATE_DIALOG },
394         { SIP_NOTIFY,    NO_RTP, "NOTIFY",      CAN_CREATE_DIALOG },
395         { SIP_INVITE,    RTP,    "INVITE",      CAN_CREATE_DIALOG },
396         { SIP_ACK,       NO_RTP, "ACK",         CAN_NOT_CREATE_DIALOG },
397         { SIP_PRACK,     NO_RTP, "PRACK",       CAN_NOT_CREATE_DIALOG },
398         { SIP_BYE,       NO_RTP, "BYE",         CAN_NOT_CREATE_DIALOG },
399         { SIP_REFER,     NO_RTP, "REFER",       CAN_CREATE_DIALOG },
400         { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",   CAN_CREATE_DIALOG },
401         { SIP_MESSAGE,   NO_RTP, "MESSAGE",     CAN_CREATE_DIALOG },
402         { SIP_UPDATE,    NO_RTP, "UPDATE",      CAN_NOT_CREATE_DIALOG },
403         { SIP_INFO,      NO_RTP, "INFO",        CAN_NOT_CREATE_DIALOG },
404         { SIP_CANCEL,    NO_RTP, "CANCEL",      CAN_NOT_CREATE_DIALOG },
405         { SIP_PUBLISH,   NO_RTP, "PUBLISH",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
406         { SIP_PING,      NO_RTP, "PING",        CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
407 };
408
409 /*!  Define SIP option tags, used in Require: and Supported: headers 
410         We need to be aware of these properties in the phones to use 
411         the replace: header. We should not do that without knowing
412         that the other end supports it... 
413         This is nothing we can configure, we learn by the dialog
414         Supported: header on the REGISTER (peer) or the INVITE
415         (other devices)
416         We are not using many of these today, but will in the future.
417         This is documented in RFC 3261
418 */
419 #define SUPPORTED               1
420 #define NOT_SUPPORTED           0
421
422 #define SIP_OPT_REPLACES        (1 << 0)
423 #define SIP_OPT_100REL          (1 << 1)
424 #define SIP_OPT_TIMER           (1 << 2)
425 #define SIP_OPT_EARLY_SESSION   (1 << 3)
426 #define SIP_OPT_JOIN            (1 << 4)
427 #define SIP_OPT_PATH            (1 << 5)
428 #define SIP_OPT_PREF            (1 << 6)
429 #define SIP_OPT_PRECONDITION    (1 << 7)
430 #define SIP_OPT_PRIVACY         (1 << 8)
431 #define SIP_OPT_SDP_ANAT        (1 << 9)
432 #define SIP_OPT_SEC_AGREE       (1 << 10)
433 #define SIP_OPT_EVENTLIST       (1 << 11)
434 #define SIP_OPT_GRUU            (1 << 12)
435 #define SIP_OPT_TARGET_DIALOG   (1 << 13)
436 #define SIP_OPT_NOREFERSUB      (1 << 14)
437 #define SIP_OPT_HISTINFO        (1 << 15)
438 #define SIP_OPT_RESPRIORITY     (1 << 16)
439
440 /*! \brief List of well-known SIP options. If we get this in a require,
441    we should check the list and answer accordingly. */
442 static const struct cfsip_options {
443         int id;                 /*!< Bitmap ID */
444         int supported;          /*!< Supported by Asterisk ? */
445         char * const text;      /*!< Text id, as in standard */
446 } sip_options[] = {     /* XXX used in 3 places */
447         /* RFC3891: Replaces: header for transfer */
448         { SIP_OPT_REPLACES,     SUPPORTED,      "replaces" },   
449         /* One version of Polycom firmware has the wrong label */
450         { SIP_OPT_REPLACES,     SUPPORTED,      "replace" },    
451         /* RFC3262: PRACK 100% reliability */
452         { SIP_OPT_100REL,       NOT_SUPPORTED,  "100rel" },     
453         /* RFC4028: SIP Session Timers */
454         { SIP_OPT_TIMER,        NOT_SUPPORTED,  "timer" },
455         /* RFC3959: SIP Early session support */
456         { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
457         /* RFC3911: SIP Join header support */
458         { SIP_OPT_JOIN,         NOT_SUPPORTED,  "join" },
459         /* RFC3327: Path support */
460         { SIP_OPT_PATH,         NOT_SUPPORTED,  "path" },
461         /* RFC3840: Callee preferences */
462         { SIP_OPT_PREF,         NOT_SUPPORTED,  "pref" },
463         /* RFC3312: Precondition support */
464         { SIP_OPT_PRECONDITION, NOT_SUPPORTED,  "precondition" },
465         /* RFC3323: Privacy with proxies*/
466         { SIP_OPT_PRIVACY,      NOT_SUPPORTED,  "privacy" },
467         /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
468         { SIP_OPT_SDP_ANAT,     NOT_SUPPORTED,  "sdp-anat" },
469         /* RFC3329: Security agreement mechanism */
470         { SIP_OPT_SEC_AGREE,    NOT_SUPPORTED,  "sec_agree" },
471         /* SIMPLE events:  RFC4662 */
472         { SIP_OPT_EVENTLIST,    NOT_SUPPORTED,  "eventlist" },
473         /* GRUU: Globally Routable User Agent URI's */
474         { SIP_OPT_GRUU,         NOT_SUPPORTED,  "gruu" },
475         /* RFC4538: Target-dialog */
476         { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,  "tdialog" },
477         /* Disable the REFER subscription, RFC 4488 */
478         { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED,  "norefersub" },
479         /* ietf-sip-history-info-06.txt */
480         { SIP_OPT_HISTINFO,     NOT_SUPPORTED,  "histinfo" },
481         /* ietf-sip-resource-priority-10.txt */
482         { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED,  "resource-priority" },
483 };
484
485
486 /*! \brief SIP Methods we support */
487 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
488
489 /*! \brief SIP Extensions we support */
490 #define SUPPORTED_EXTENSIONS "replaces" 
491
492 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
493 #define STANDARD_SIP_PORT       5060
494 /* Note: in many SIP headers, absence of a port number implies port 5060,
495  * and this is why we cannot change the above constant.
496  * There is a limited number of places in asterisk where we could,
497  * in principle, use a different "default" port number, but
498  * we do not support this feature at the moment.
499  */
500
501 /* Default values, set and reset in reload_config before reading configuration */
502 /* These are default values in the source. There are other recommended values in the
503    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
504    yet encouraging new behaviour on new installations 
505  */
506 #define DEFAULT_CONTEXT         "default"
507 #define DEFAULT_MOHINTERPRET    "default"
508 #define DEFAULT_MOHSUGGEST      ""
509 #define DEFAULT_VMEXTEN         "asterisk"
510 #define DEFAULT_CALLERID        "asterisk"
511 #define DEFAULT_NOTIFYMIME      "application/simple-message-summary"
512 #define DEFAULT_ALLOWGUEST      TRUE
513 #define DEFAULT_SRVLOOKUP       FALSE           /*!< Recommended setting is ON */
514 #define DEFAULT_COMPACTHEADERS  FALSE
515 #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. */
516 #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. */
517 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
518 #define DEFAULT_TOS_TEXT        0               /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
519 #define DEFAULT_COS_SIP         4
520 #define DEFAULT_COS_AUDIO       5
521 #define DEFAULT_COS_VIDEO       6
522 #define DEFAULT_COS_TEXT        0
523 #define DEFAULT_ALLOW_EXT_DOM   TRUE
524 #define DEFAULT_REALM           "asterisk"
525 #define DEFAULT_NOTIFYRINGING   TRUE
526 #define DEFAULT_PEDANTIC        FALSE
527 #define DEFAULT_AUTOCREATEPEER  FALSE
528 #define DEFAULT_QUALIFY         FALSE
529 #define DEFAULT_REGEXTENONQUALIFY FALSE
530 #define DEFAULT_T1MIN           100             /*!< 100 MS for minimal roundtrip time */
531 #define DEFAULT_MAX_CALL_BITRATE (384)          /*!< Max bitrate for video */
532 #ifndef DEFAULT_USERAGENT
533 #define DEFAULT_USERAGENT "Asterisk PBX"        /*!< Default Useragent: header unless re-defined in sip.conf */
534 #endif
535
536 /* Default setttings are used as a channel setting and as a default when
537    configuring devices */
538 static char default_context[AST_MAX_CONTEXT];
539 static char default_subscribecontext[AST_MAX_CONTEXT];
540 static char default_language[MAX_LANGUAGE];
541 static char default_callerid[AST_MAX_EXTENSION];
542 static char default_fromdomain[AST_MAX_EXTENSION];
543 static char default_notifymime[AST_MAX_EXTENSION];
544 static int default_qualify;             /*!< Default Qualify= setting */
545 static char default_vmexten[AST_MAX_EXTENSION];
546 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
547 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting 
548                                                     *   a bridged channel on hold */
549 static int default_maxcallbitrate;      /*!< Maximum bitrate for call */
550 static struct ast_codec_pref default_prefs;             /*!< Default codec prefs */
551
552 /* Global settings only apply to the channel */
553 static int global_directrtpsetup;       /*!< Enable support for Direct RTP setup (no re-invites) */
554 static int global_limitonpeers;         /*!< Match call limit on peers only */
555 static int global_rtautoclear;
556 static int global_notifyringing;        /*!< Send notifications on ringing */
557 static int global_notifyhold;           /*!< Send notifications on hold */
558 static int global_alwaysauthreject;     /*!< Send 401 Unauthorized for all failing requests */
559 static int global_srvlookup;                    /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
560 static int pedanticsipchecking;         /*!< Extra checking ?  Default off */
561 static int autocreatepeer;              /*!< Auto creation of peers at registration? Default off. */
562 static int global_match_auth_username;          /*!< Match auth username if available instead of From: Default off. */
563 static int global_relaxdtmf;                    /*!< Relax DTMF */
564 static int global_rtptimeout;           /*!< Time out call if no RTP */
565 static int global_rtpholdtimeout;
566 static int global_rtpkeepalive;         /*!< Send RTP keepalives */
567 static int global_reg_timeout;  
568 static int global_regattempts_max;      /*!< Registration attempts before giving up */
569 static int global_allowguest;           /*!< allow unauthenticated users/peers to connect? */
570 static int global_allowsubscribe;       /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
571                                             the global setting is in globals_flags[1] */
572 static unsigned int global_tos_sip;             /*!< IP type of service for SIP packets */
573 static unsigned int global_tos_audio;           /*!< IP type of service for audio RTP packets */
574 static unsigned int global_tos_video;           /*!< IP type of service for video RTP packets */
575 static unsigned int global_tos_text;            /*!< IP type of service for text RTP packets */
576 static unsigned int global_cos_sip;             /*!< 802.1p class of service for SIP packets */
577 static unsigned int global_cos_audio;           /*!< 802.1p class of service for audio RTP packets */
578 static unsigned int global_cos_video;           /*!< 802.1p class of service for video RTP packets */
579 static unsigned int global_cos_text;            /*!< 802.1p class of service for text RTP packets */
580 static int compactheaders;              /*!< send compact sip headers */
581 static int recordhistory;               /*!< Record SIP history. Off by default */
582 static int dumphistory;                 /*!< Dump history to verbose before destroying SIP dialog */
583 static char global_realm[MAXHOSTNAMELEN];               /*!< Default realm */
584 static char global_regcontext[AST_MAX_CONTEXT];         /*!< Context for auto-extensions */
585 static char global_useragent[AST_MAX_EXTENSION];        /*!< Useragent for the SIP channel */
586 static int allow_external_domains;      /*!< Accept calls to external SIP domains? */
587 static int global_callevents;           /*!< Whether we send manager events or not */
588 static int global_t1min;                /*!< T1 roundtrip time minimum */
589 static int global_regextenonqualify;  /*!< Whether to add/remove regexten when qualifying peers */
590 static int global_autoframing;          /*!< Turn autoframing on or off. */
591 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
592 static struct sip_proxy global_outboundproxy;   /*!< Outbound proxy */
593
594 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
595
596 /*! \brief Codecs that we support by default: */
597 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
598
599 /* Object counters */
600 static int suserobjs = 0;                /*!< Static users */
601 static int ruserobjs = 0;                /*!< Realtime users */
602 static int speerobjs = 0;                /*!< Statis peers */
603 static int rpeerobjs = 0;                /*!< Realtime peers */
604 static int apeerobjs = 0;                /*!< Autocreated peer objects */
605 static int regobjs = 0;                  /*!< Registry objects */
606
607 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
608
609 AST_MUTEX_DEFINE_STATIC(netlock);
610
611 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
612    when it's doing something critical. */
613
614 AST_MUTEX_DEFINE_STATIC(monlock);
615
616 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
617
618 /*! \brief This is the thread for the monitor which checks for input on the channels
619    which are not currently in use.  */
620 static pthread_t monitor_thread = AST_PTHREADT_NULL;
621
622 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
623 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
624
625 static struct sched_context *sched;     /*!< The scheduling context */
626 static struct io_context *io;           /*!< The IO context */
627 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
628
629 #define DEC_CALL_LIMIT  0
630 #define INC_CALL_LIMIT  1
631 #define DEC_CALL_RINGING 2
632 #define INC_CALL_RINGING 3
633
634 /*! \brief sip_request: The data grabbed from the UDP socket */
635 struct sip_request {
636         char *rlPart1;          /*!< SIP Method Name or "SIP/2.0" protocol version */
637         char *rlPart2;          /*!< The Request URI or Response Status */
638         int len;                /*!< Length */
639         int headers;            /*!< # of SIP Headers */
640         int method;             /*!< Method of this request */
641         int lines;              /*!< Body Content */
642         uint64_t flags;     /*!< SIP_PKT Flags for this packet */
643         char *header[SIP_MAX_HEADERS];
644         char *line[SIP_MAX_LINES];
645         char data[SIP_MAX_PACKET];
646         unsigned int sdp_start; /*!< the line number where the SDP begins */
647         unsigned int sdp_end;   /*!< the line number where the SDP ends */
648 };
649
650 /*
651  * A sip packet is stored into the data[] buffer, with the header followed
652  * by an empty line and the body of the message.
653  * On outgoing packets, data is accumulated in data[] with len reflecting
654  * the next available byte, headers and lines count the number of lines
655  * in both parts. There are no '\0' in data[0..len-1].
656  *
657  * On received packet, the input read from the socket is copied into data[],
658  * len is set and the string is NUL-terminated. Then a parser fills up
659  * the other fields -header[] and line[] to point to the lines of the
660  * message, rlPart1 and rlPart2 parse the first lnie as below:
661  *
662  * Requests have in the first line      METHOD URI SIP/2.0
663  *      rlPart1 = method; rlPart2 = uri;
664  * Responses have in the first line     SIP/2.0 code description
665  *      rlPart1 = SIP/2.0; rlPart2 = code + description;
666  *
667  */
668
669 /*! \brief structure used in transfers */
670 struct sip_dual {
671         struct ast_channel *chan1;      /*!< First channel involved */
672         struct ast_channel *chan2;      /*!< Second channel involved */
673         struct sip_request req;         /*!< Request that caused the transfer (REFER) */
674         int seqno;                      /*!< Sequence number */
675 };
676
677 struct sip_pkt;
678
679 /*! \brief Parameters to the transmit_invite function */
680 struct sip_invite_param {
681         int addsipheaders;              /*!< Add extra SIP headers */
682         const char *uri_options;        /*!< URI options to add to the URI */
683         const char *vxml_url;           /*!< VXML url for Cisco phones */
684         char *auth;                     /*!< Authentication */
685         char *authheader;               /*!< Auth header */
686         enum sip_auth_type auth_type;   /*!< Authentication type */
687         const char *replaces;           /*!< Replaces header for call transfers */
688         int transfer;                   /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
689 };
690
691 /*! \brief Structure to save routing information for a SIP session */
692 struct sip_route {
693         struct sip_route *next;
694         char hop[0];
695 };
696
697 /*! \brief Modes for SIP domain handling in the PBX */
698 enum domain_mode {
699         SIP_DOMAIN_AUTO,                /*!< This domain is auto-configured */
700         SIP_DOMAIN_CONFIG,              /*!< This domain is from configuration */
701 };
702
703 /*! \brief Domain data structure. 
704         \note In the future, we will connect this to a configuration tree specific
705         for this domain
706 */
707 struct domain {
708         char domain[MAXHOSTNAMELEN];            /*!< SIP domain we are responsible for */
709         char context[AST_MAX_EXTENSION];        /*!< Incoming context for this domain */
710         enum domain_mode mode;                  /*!< How did we find this domain? */
711         AST_LIST_ENTRY(domain) list;            /*!< List mechanics */
712 };
713
714 static AST_LIST_HEAD_STATIC(domain_list, domain);       /*!< The SIP domain list */
715
716
717 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
718 struct sip_history {
719         AST_LIST_ENTRY(sip_history) list;
720         char event[0];  /* actually more, depending on needs */
721 };
722
723 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
724
725 /*! \brief sip_auth: Credentials for authentication to other SIP services */
726 struct sip_auth {
727         char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
728         char username[256];             /*!< Username */
729         char secret[256];               /*!< Secret */
730         char md5secret[256];            /*!< MD5Secret */
731         struct sip_auth *next;          /*!< Next auth structure in list */
732 };
733
734 /*--- Various flags for the flags field in the pvt structure 
735         Trying to sort these up:
736         D: Dialog only
737         DP: Dialog and peer/user
738         P: Peer/user only, not dialog
739         G: Global flag only
740 */
741 #define SIP_ALREADYGONE         (1 << 0)        /*!< D: Whether or not we've already been destroyed by our peer */
742 #define SIP_NEEDDESTROY         (1 << 1)        /*!< D: if we need to be destroyed by the monitor thread */
743 #define SIP_NOVIDEO             (1 << 2)        /*!< D: Didn't get video in invite, don't offer */
744 #define SIP_RINGING             (1 << 3)        /*!< D: Have sent 180 ringing */
745 #define SIP_PROGRESS_SENT       (1 << 4)        /*!< D: Have sent 183 message progress */
746 #define SIP_NEEDREINVITE        (1 << 5)        /*!< D: Do we need to send another reinvite? */
747 #define SIP_PENDINGBYE          (1 << 6)        /*!< D: Need to send bye after we ack? */
748 #define SIP_GOTREFER            (1 << 7)        /*!< D: Got a refer? */
749 #define SIP_PROMISCREDIR        (1 << 8)        /*!< DP: Promiscuous redirection */
750 #define SIP_TRUSTRPID           (1 << 9)        /*!< DP: Trust RPID headers? */
751 #define SIP_USEREQPHONE         (1 << 10)       /*!< DP: Add user=phone to numeric URI. Default off */
752 #define SIP_REALTIME            (1 << 11)       /*!< P: Flag for realtime users */
753 #define SIP_USECLIENTCODE       (1 << 12)       /*!< DP: Trust X-ClientCode info message */
754 #define SIP_OUTGOING            (1 << 13)       /*!< D: Direction of the last transaction in this dialog */
755 #define SIP_DIALOG_ANSWEREDELSEWHERE    (1 << 14)       /*!< D: This call is cancelled due to answer on another channel */
756 #define SIP_DEFER_BYE_ON_TRANSFER       (1 << 15)       /*!< D: Do not hangup at first ast_hangup */
757 #define SIP_DTMF                (3 << 16)       /*!< DP: DTMF Support: four settings, uses two bits */
758 #define SIP_DTMF_RFC2833        (0 << 16)       /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
759 #define SIP_DTMF_INBAND         (1 << 16)       /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
760 #define SIP_DTMF_INFO           (2 << 16)       /*!< DP: DTMF Support: SIP Info messages - "info" */
761 #define SIP_DTMF_AUTO           (3 << 16)       /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
762 /* NAT settings */
763 #define SIP_NAT                 (3 << 18)       /*!< DP: four settings, uses two bits */
764 #define SIP_NAT_NEVER           (0 << 18)       /*!< DP: No nat support */
765 #define SIP_NAT_RFC3581         (1 << 18)       /*!< DP: NAT RFC3581 */
766 #define SIP_NAT_ROUTE           (2 << 18)       /*!< DP: NAT Only ROUTE */
767 #define SIP_NAT_ALWAYS          (3 << 18)       /*!< DP: NAT Both ROUTE and RFC3581 */
768 /* re-INVITE related settings */
769 #define SIP_REINVITE            (7 << 20)       /*!< DP: three bits used */
770 #define SIP_CAN_REINVITE        (1 << 20)       /*!< DP: allow peers to be reinvited to send media directly p2p */
771 #define SIP_CAN_REINVITE_NAT    (2 << 20)       /*!< DP: allow media reinvite when new peer is behind NAT */
772 #define SIP_REINVITE_UPDATE     (4 << 20)       /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
773 /* "insecure" settings */
774 #define SIP_INSECURE_PORT       (1 << 23)       /*!< DP: don't require matching port for incoming requests */
775 #define SIP_INSECURE_INVITE     (1 << 24)       /*!< DP: don't require authentication for incoming INVITEs */
776 /* Sending PROGRESS in-band settings */
777 #define SIP_PROG_INBAND         (3 << 25)       /*!< DP: three settings, uses two bits */
778 #define SIP_PROG_INBAND_NEVER   (0 << 25)
779 #define SIP_PROG_INBAND_NO      (1 << 25)
780 #define SIP_PROG_INBAND_YES     (2 << 25)
781 #define SIP_NO_HISTORY          (1 << 27)       /*!< D: Suppress recording request/response history */
782 #define SIP_CALL_LIMIT          (1 << 28)       /*!< D: Call limit enforced for this call */
783 #define SIP_SENDRPID            (1 << 29)       /*!< DP: Remote Party-ID Support */
784 #define SIP_INC_COUNT           (1 << 30)       /*!< D: Did this dialog increment the counter of in-use calls? */
785 #define SIP_G726_NONSTANDARD    (1 << 31)       /*!< DP: Use non-standard packing for G726-32 data */
786
787 /*! \brief Flags to copy from peer/user to dialog */
788 #define SIP_FLAGS_TO_COPY \
789         (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
790          SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
791          SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
792
793 /*--- a new page of flags (for flags[1] */
794 /* realtime flags */
795 #define SIP_PAGE2_RTCACHEFRIENDS        (1 << 0)        /*!< G: Should we keep RT objects in memory for extended time? */
796 #define SIP_PAGE2_RTUPDATE              (1 << 1)        /*!< G: Update database with registration data for peer? */
797 #define SIP_PAGE2_RTAUTOCLEAR           (1 << 2)        /*!< G: Should we clean memory from peers after expiry? */
798 #define SIP_PAGE2_RT_FROMCONTACT        (1 << 4)        
799 #define SIP_PAGE2_RTSAVE_SYSNAME        (1 << 5)        /*!< G: Save system name at registration? */
800 /* Space for addition of other realtime flags in the future */
801 #define SIP_PAGE2_IGNOREREGEXPIRE       (1 << 10)       /*!< G: Ignore expiration of peer  */
802 #define SIP_PAGE2_DEBUG                 (3 << 11)       /*!< G: Debug flags */
803 #define SIP_PAGE2_DEBUG_CONFIG          (1 << 11)       /*!< G: Debug flags */
804 #define SIP_PAGE2_DEBUG_CONSOLE         (1 << 12)       /*!< G: Debug flags */
805 #define SIP_PAGE2_DYNAMIC               (1 << 13)       /*!< P: Dynamic Peers register with Asterisk */
806 #define SIP_PAGE2_SELFDESTRUCT          (1 << 14)       /*!< P: Automatic peers need to destruct themselves */
807 #define SIP_PAGE2_VIDEOSUPPORT          (1 << 15)       /*!< DP: Video supported if offered? */
808 #define SIP_PAGE2_ALLOWSUBSCRIBE        (1 << 16)       /*!< GP: Allow subscriptions from this peer? */
809 #define SIP_PAGE2_ALLOWOVERLAP          (1 << 17)       /*!< DP: Allow overlap dialing ? */
810 #define SIP_PAGE2_SUBSCRIBEMWIONLY      (1 << 18)       /*!< GP: Only issue MWI notification if subscribed to */
811 #define SIP_PAGE2_INC_RINGING           (1 << 19)       /*!< D: Did this connection increment the counter of in-use calls? */
812 #define SIP_PAGE2_T38SUPPORT            (7 << 20)       /*!< GDP: T38 Fax Passthrough Support */
813 #define SIP_PAGE2_T38SUPPORT_UDPTL      (1 << 20)       /*!< GDP: 20: T38 Fax Passthrough Support */
814 #define SIP_PAGE2_T38SUPPORT_RTP        (2 << 20)       /*!< GDP: 21: T38 Fax Passthrough Support (not implemented) */
815 #define SIP_PAGE2_T38SUPPORT_TCP        (4 << 20)       /*!< GDP: 22: T38 Fax Passthrough Support (not implemented) */
816 #define SIP_PAGE2_CALL_ONHOLD           (3 << 23)       /*!< D: Call hold states */
817 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: 23: Active hold */
818 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR    (2 << 23)       /*!< D: 23: One directional hold */
819 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE  (3 << 23)       /*!< D: 23: Inactive hold */
820 #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)       /*!< DP: 25: Compensate for buggy RFC2833 implementations */
821 #define SIP_PAGE2_BUGGY_MWI             (1 << 26)       /*!< DP: 26: Buggy CISCO MWI fix */
822 #define SIP_PAGE2_NOTEXT                (1 << 27)       /*!< GPD: 27: Text not supported  */
823 #define SIP_PAGE2_TEXTSUPPORT           (1 << 28)       /*!< GPD: 28: Global text enable */
824 #define SIP_PAGE2_DEBUG_TEXT            (1 << 29)       /*!< GPD: 29: Global text debug */
825 #define SIP_PAGE2_OUTGOING_CALL         (1 << 30)       /*!< D: 30: Is this an outgoing call? */
826
827 #define SIP_PAGE2_FLAGS_TO_COPY \
828         (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
829         SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | \
830         SIP_PAGE2_TEXTSUPPORT )
831
832 /* SIP packet flags */
833 #define SIP_PKT_DEBUG           (1 << 0)        /*!< Debug this packet */
834 #define SIP_PKT_WITH_TOTAG      (1 << 1)        /*!< This packet has a to-tag */
835 #define SIP_PKT_IGNORE          (1 << 2)        /*!< This is a re-transmit, ignore it */
836
837 /* T.38 set of flags */
838 #define T38FAX_FILL_BIT_REMOVAL         (1 << 0)        /*!< Default: 0 (unset)*/
839 #define T38FAX_TRANSCODING_MMR                  (1 << 1)        /*!< Default: 0 (unset)*/
840 #define T38FAX_TRANSCODING_JBIG         (1 << 2)        /*!< Default: 0 (unset)*/
841 /* Rate management */
842 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF   (0 << 3)
843 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF        (1 << 3)        /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
844 /* UDP Error correction */
845 #define T38FAX_UDP_EC_NONE                      (0 << 4)        /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
846 #define T38FAX_UDP_EC_FEC                       (1 << 4)        /*!< Set for t38UDPFEC */
847 #define T38FAX_UDP_EC_REDUNDANCY                (2 << 4)        /*!< Set for t38UDPRedundancy */
848 /* T38 Spec version */
849 #define T38FAX_VERSION                          (3 << 6)        /*!< two bits, 2 values so far, up to 4 values max */
850 #define T38FAX_VERSION_0                        (0 << 6)        /*!< Version 0 */
851 #define T38FAX_VERSION_1                        (1 << 6)        /*!< Version 1 */
852 /* Maximum Fax Rate */
853 #define T38FAX_RATE_2400                        (1 << 8)        /*!< 2400 bps t38FaxRate */
854 #define T38FAX_RATE_4800                        (1 << 9)        /*!< 4800 bps t38FaxRate */
855 #define T38FAX_RATE_7200                        (1 << 10)       /*!< 7200 bps t38FaxRate */
856 #define T38FAX_RATE_9600                        (1 << 11)       /*!< 9600 bps t38FaxRate */
857 #define T38FAX_RATE_12000                       (1 << 12)       /*!< 12000 bps t38FaxRate */
858 #define T38FAX_RATE_14400                       (1 << 13)       /*!< 14400 bps t38FaxRate */
859
860 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
861 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
862
863 #define sipdebug                ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
864 #define sipdebug_config         ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
865 #define sipdebug_console        ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
866 #define sipdebug_text           ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_TEXT)
867
868 /*! \brief T38 States for a call */
869 enum t38state {
870         T38_DISABLED = 0,                /*!< Not enabled */
871         T38_LOCAL_DIRECT,                /*!< Offered from local */
872         T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
873         T38_PEER_DIRECT,                 /*!< Offered from peer */
874         T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
875         T38_ENABLED                      /*!< Negotiated (enabled) */
876 };
877
878 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
879 struct t38properties {
880         struct ast_flags t38support;    /*!< Flag for udptl, rtp or tcp support for this session */
881         int capability;                 /*!< Our T38 capability */
882         int peercapability;             /*!< Peers T38 capability */
883         int jointcapability;            /*!< Supported T38 capability at both ends */
884         enum t38state state;            /*!< T.38 state */
885 };
886
887 /*! \brief Parameters to know status of transfer */
888 enum referstatus {
889         REFER_IDLE,                    /*!< No REFER is in progress */
890         REFER_SENT,                    /*!< Sent REFER to transferee */
891         REFER_RECEIVED,                /*!< Received REFER from transferrer */
892         REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING */
893         REFER_ACCEPTED,                /*!< Accepted by transferee */
894         REFER_RINGING,                 /*!< Target Ringing */
895         REFER_200OK,                   /*!< Answered by transfer target */
896         REFER_FAILED,                  /*!< REFER declined - go on */
897         REFER_NOAUTH                   /*!< We had no auth for REFER */
898 };
899
900 static const struct c_referstatusstring {
901         enum referstatus status;
902         char *text;
903 } referstatusstrings[] = {
904         { REFER_IDLE,           "<none>" },
905         { REFER_SENT,           "Request sent" },
906         { REFER_RECEIVED,       "Request received" },
907         { REFER_ACCEPTED,       "Accepted" },
908         { REFER_RINGING,        "Target ringing" },
909         { REFER_200OK,          "Done" },
910         { REFER_FAILED,         "Failed" },
911         { REFER_NOAUTH,         "Failed - auth failure" }
912 } ;
913
914 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
915         \note OEJ: Should be moved to string fields */
916 struct sip_refer {
917         char refer_to[AST_MAX_EXTENSION];               /*!< Place to store REFER-TO extension */
918         char refer_to_domain[AST_MAX_EXTENSION];        /*!< Place to store REFER-TO domain */
919         char refer_to_urioption[AST_MAX_EXTENSION];     /*!< Place to store REFER-TO uri options */
920         char refer_to_context[AST_MAX_EXTENSION];       /*!< Place to store REFER-TO context */
921         char referred_by[AST_MAX_EXTENSION];            /*!< Place to store REFERRED-BY extension */
922         char referred_by_name[AST_MAX_EXTENSION];       /*!< Place to store REFERRED-BY extension */
923         char refer_contact[AST_MAX_EXTENSION];          /*!< Place to store Contact info from a REFER extension */
924         char replaces_callid[BUFSIZ];                   /*!< Replace info: callid */
925         char replaces_callid_totag[BUFSIZ/2];           /*!< Replace info: to-tag */
926         char replaces_callid_fromtag[BUFSIZ/2];         /*!< Replace info: from-tag */
927         struct sip_pvt *refer_call;                     /*!< Call we are referring */
928         int attendedtransfer;                           /*!< Attended or blind transfer? */
929         int localtransfer;                              /*!< Transfer to local domain? */
930         enum referstatus status;                        /*!< REFER status */
931 };
932
933 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe  */
934 struct sip_pvt {
935         ast_mutex_t pvt_lock;                   /*!< Dialog private lock */
936         enum invitestates invitestate;          /*!< Track state of SIP_INVITEs */
937         int method;                             /*!< SIP method that opened this dialog */
938         AST_DECLARE_STRING_FIELDS(
939                 AST_STRING_FIELD(callid);       /*!< Global CallID */
940                 AST_STRING_FIELD(randdata);     /*!< Random data */
941                 AST_STRING_FIELD(accountcode);  /*!< Account code */
942                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
943                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
944                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
945                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
946                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
947                 AST_STRING_FIELD(from);         /*!< The From: header */
948                 AST_STRING_FIELD(useragent);    /*!< User agent in SIP request */
949                 AST_STRING_FIELD(exten);        /*!< Extension where to start */
950                 AST_STRING_FIELD(context);      /*!< Context for this call */
951                 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
952                 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
953                 AST_STRING_FIELD(fromdomain);   /*!< Domain to show in the from field */
954                 AST_STRING_FIELD(fromuser);     /*!< User to show in the user field */
955                 AST_STRING_FIELD(fromname);     /*!< Name to show in the user field */
956                 AST_STRING_FIELD(tohost);       /*!< Host we should put in the "to" field */
957                 AST_STRING_FIELD(language);     /*!< Default language for this call */
958                 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
959                 AST_STRING_FIELD(mohsuggest);   /*!< MOH class to suggest when putting a peer on hold */
960                 AST_STRING_FIELD(rdnis);        /*!< Referring DNIS */
961                 AST_STRING_FIELD(redircause);   /*!< Referring cause */
962                 AST_STRING_FIELD(theirtag);     /*!< Their tag */
963                 AST_STRING_FIELD(username);     /*!< [user] name */
964                 AST_STRING_FIELD(peername);     /*!< [peer] name, not set if [user] */
965                 AST_STRING_FIELD(authname);     /*!< Who we use for authentication */
966                 AST_STRING_FIELD(uri);          /*!< Original requested URI */
967                 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
968                 AST_STRING_FIELD(peersecret);   /*!< Password */
969                 AST_STRING_FIELD(peermd5secret);
970                 AST_STRING_FIELD(cid_num);      /*!< Caller*ID number */
971                 AST_STRING_FIELD(cid_name);     /*!< Caller*ID name */
972                 AST_STRING_FIELD(via);          /*!< Via: header */
973                 AST_STRING_FIELD(fullcontact);  /*!< The Contact: that the UA registers with us */
974                         /* we only store the part in <brackets> in this field. */
975                 AST_STRING_FIELD(our_contact);  /*!< Our contact header */
976                 AST_STRING_FIELD(rpid);         /*!< Our RPID header */
977                 AST_STRING_FIELD(rpid_from);    /*!< Our RPID From header */
978                 AST_STRING_FIELD(url);          /*!< URL to be sent with next message to peer */
979         );
980         unsigned int ocseq;                     /*!< Current outgoing seqno */
981         unsigned int icseq;                     /*!< Current incoming seqno */
982         ast_group_t callgroup;                  /*!< Call group */
983         ast_group_t pickupgroup;                /*!< Pickup group */
984         int lastinvite;                         /*!< Last Cseq of invite */
985         struct ast_flags flags[2];              /*!< SIP_ flags */
986         int timer_t1;                           /*!< SIP timer T1, ms rtt */
987         unsigned int sipoptions;                /*!< Supported SIP options on the other end */
988         struct ast_codec_pref prefs;            /*!< codec prefs */
989         int capability;                         /*!< Special capability (codec) */
990         int jointcapability;                    /*!< Supported capability at both ends (codecs) */
991         int peercapability;                     /*!< Supported peer capability */
992         int prefcodec;                          /*!< Preferred codec (outbound only) */
993         int noncodeccapability;                 /*!< DTMF RFC2833 telephony-event */
994         int jointnoncodeccapability;            /*!< Joint Non codec capability */
995         int redircodecs;                        /*!< Redirect codecs */
996         int maxcallbitrate;                     /*!< Maximum Call Bitrate for Video Calls */    
997         struct sip_proxy *outboundproxy;        /*!< Outbound proxy for this dialog */
998         struct t38properties t38;               /*!< T38 settings */
999         struct sockaddr_in udptlredirip;        /*!< Where our T.38 UDPTL should be going if not to us */
1000         struct ast_udptl *udptl;                /*!< T.38 UDPTL session */
1001         int callingpres;                        /*!< Calling presentation */
1002         int authtries;                          /*!< Times we've tried to authenticate */
1003         int expiry;                             /*!< How long we take to expire */
1004         long branch;                            /*!< The branch identifier of this session */
1005         char tag[11];                           /*!< Our tag for this session */
1006         int sessionid;                          /*!< SDP Session ID */
1007         int sessionversion;                     /*!< SDP Session Version */
1008         struct sockaddr_in sa;                  /*!< Our peer */
1009         struct sockaddr_in redirip;             /*!< Where our RTP should be going if not to us */
1010         struct sockaddr_in vredirip;            /*!< Where our Video RTP should be going if not to us */
1011         struct sockaddr_in tredirip;            /*!< Where our Text RTP should be going if not to us */
1012         time_t lastrtprx;                       /*!< Last RTP received */
1013         time_t lastrtptx;                       /*!< Last RTP sent */
1014         int rtptimeout;                         /*!< RTP timeout time */
1015         struct sockaddr_in recv;                /*!< Received as */
1016         struct in_addr ourip;                   /*!< Our IP */
1017         struct ast_channel *owner;              /*!< Who owns us (if we have an owner) */
1018         struct sip_route *route;                /*!< Head of linked list of routing steps (fm Record-Route) */
1019         int route_persistant;                   /*!< Is this the "real" route? */
1020         struct sip_auth *peerauth;              /*!< Realm authentication */
1021         int noncecount;                         /*!< Nonce-count */
1022         char lastmsg[256];                      /*!< Last Message sent/received */
1023         int amaflags;                           /*!< AMA Flags */
1024         int pendinginvite;                      /*!< Any pending invite ? (seqno of this) */
1025         struct sip_request initreq;             /*!< Latest request that opened a new transaction
1026                                                         within this dialog.
1027                                                         NOT the request that opened the dialog
1028                                                 */
1029         
1030         int initid;                             /*!< Auto-congest ID if appropriate (scheduler) */
1031         int autokillid;                         /*!< Auto-kill ID (scheduler) */
1032         enum transfermodes allowtransfer;       /*!< REFER: restriction scheme */
1033         struct sip_refer *refer;                /*!< REFER: SIP transfer data structure */
1034         enum subscriptiontype subscribed;       /*!< SUBSCRIBE: Is this dialog a subscription?  */
1035         int stateid;                            /*!< SUBSCRIBE: ID for devicestate subscriptions */
1036         int laststate;                          /*!< SUBSCRIBE: Last known extension state */
1037         int dialogver;                          /*!< SUBSCRIBE: Version for subscription dialog-info */
1038         
1039         struct ast_dsp *vad;                    /*!< Inband DTMF Detection dsp */
1040         
1041         struct sip_peer *relatedpeer;           /*!< If this dialog is related to a peer, which one 
1042                                                         Used in peerpoke, mwi subscriptions */
1043         struct sip_registry *registry;          /*!< If this is a REGISTER dialog, to which registry */
1044         struct ast_rtp *rtp;                    /*!< RTP Session */
1045         struct ast_rtp *vrtp;                   /*!< Video RTP session */
1046         struct ast_rtp *trtp;                   /*!< Text RTP session */
1047         struct sip_pkt *packets;                /*!< Packets scheduled for re-transmission */
1048         struct sip_history_head *history;       /*!< History of this SIP dialog */
1049         struct ast_variable *chanvars;          /*!< Channel variables to set for inbound call */
1050         struct sip_pvt *next;                   /*!< Next dialog in chain */
1051         struct sip_invite_param *options;       /*!< Options for INVITE */
1052         int autoframing;                        /*!< The number of Asters we group in a Pyroflax
1053                                                         before strolling to the GrokyzpÃ¥
1054                                                         (A bit unsure of this, please correct if
1055                                                         you know more) */
1056 };
1057
1058 static struct sip_pvt *dialoglist = NULL;
1059
1060 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
1061 AST_MUTEX_DEFINE_STATIC(dialoglock);
1062
1063 /*! \brief hide the way the list is locked/unlocked */
1064 static void dialoglist_lock(void)
1065 {
1066         ast_mutex_lock(&dialoglock);
1067 }
1068
1069 static void dialoglist_unlock(void)
1070 {
1071         ast_mutex_unlock(&dialoglock);
1072 }
1073
1074 #define FLAG_RESPONSE (1 << 0)
1075 #define FLAG_FATAL (1 << 1)
1076
1077 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1078 struct sip_pkt {
1079         struct sip_pkt *next;                   /*!< Next packet in linked list */
1080         int retrans;                            /*!< Retransmission number */
1081         int method;                             /*!< SIP method for this packet */
1082         int seqno;                              /*!< Sequence number */
1083         uint64_t flags;                 /*!< non-zero if this is a response packet (e.g. 200 OK) */
1084         struct sip_pvt *owner;                  /*!< Owner AST call */
1085         int retransid;                          /*!< Retransmission ID */
1086         int timer_a;                            /*!< SIP timer A, retransmission timer */
1087         int timer_t1;                           /*!< SIP Timer T1, estimated RTT or 500 ms */
1088         int packetlen;                          /*!< Length of packet */
1089         char data[0];
1090 };      
1091
1092 /*! \brief Structure for SIP user data. User's place calls to us */
1093 struct sip_user {
1094         /* Users who can access various contexts */
1095         ASTOBJ_COMPONENTS(struct sip_user);
1096         char secret[80];                /*!< Password */
1097         char md5secret[80];             /*!< Password in md5 */
1098         char context[AST_MAX_CONTEXT];  /*!< Default context for incoming calls */
1099         char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1100         char cid_num[80];               /*!< Caller ID num */
1101         char cid_name[80];              /*!< Caller ID name */
1102         char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1103         char language[MAX_LANGUAGE];    /*!< Default language for this user */
1104         char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1105         char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1106         char useragent[256];            /*!< User agent in SIP request */
1107         struct ast_codec_pref prefs;    /*!< codec prefs */
1108         ast_group_t callgroup;          /*!< Call group */
1109         ast_group_t pickupgroup;        /*!< Pickup Group */
1110         unsigned int sipoptions;        /*!< Supported SIP options */
1111         struct ast_flags flags[2];      /*!< SIP_ flags */
1112         int amaflags;                   /*!< AMA flags for billing */
1113         int callingpres;                /*!< Calling id presentation */
1114         int capability;                 /*!< Codec capability */
1115         int inUse;                      /*!< Number of calls in use */
1116         int call_limit;                 /*!< Limit of concurrent calls */
1117         enum transfermodes allowtransfer;       /*! SIP Refer restriction scheme */
1118         struct ast_ha *ha;              /*!< ACL setting */
1119         struct ast_variable *chanvars;  /*!< Variables to set for channel created by user */
1120         int maxcallbitrate;             /*!< Maximum Bitrate for a video call */
1121         int autoframing;
1122 };
1123
1124 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) */
1125 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1126 struct sip_peer {
1127         ASTOBJ_COMPONENTS(struct sip_peer);     /*!< name, refcount, objflags,  object pointers */
1128                                         /*!< peer->name is the unique name of this object */
1129         char secret[80];                /*!< Password */
1130         char md5secret[80];             /*!< Password in MD5 */
1131         struct sip_auth *auth;          /*!< Realm authentication list */
1132         char context[AST_MAX_CONTEXT];  /*!< Default context for incoming calls */
1133         char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1134         char username[80];              /*!< Temporary username until registration */ 
1135         char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1136         int amaflags;                   /*!< AMA Flags (for billing) */
1137         char tohost[MAXHOSTNAMELEN];    /*!< If not dynamic, IP address */
1138         char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1139         char fromuser[80];              /*!< From: user when calling this peer */
1140         char fromdomain[MAXHOSTNAMELEN];        /*!< From: domain when calling this peer */
1141         char fullcontact[256];          /*!< Contact registered with us (not in sip.conf) */
1142         char cid_num[80];               /*!< Caller ID num */
1143         char cid_name[80];              /*!< Caller ID name */
1144         int callingpres;                /*!< Calling id presentation */
1145         int inUse;                      /*!< Number of calls in use */
1146         int inRinging;                  /*!< Number of calls ringing */
1147         int onHold;                     /*!< Peer has someone on hold */
1148         int call_limit;                 /*!< Limit of concurrent calls */
1149         int busy_level;                 /*!< Level of active channels where we signal busy */
1150         enum transfermodes allowtransfer;       /*! SIP Refer restriction scheme */
1151         char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1152         char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1153         char language[MAX_LANGUAGE];    /*!<  Default language for prompts */
1154         char mohinterpret[MAX_MUSICCLASS];/*!<  Music on Hold class */
1155         char mohsuggest[MAX_MUSICCLASS];/*!<  Music on Hold class */
1156         char useragent[256];            /*!<  User agent in SIP request (saved from registration) */
1157         struct ast_codec_pref prefs;    /*!<  codec prefs */
1158         int lastmsgssent;
1159         unsigned int sipoptions;        /*!<  Supported SIP options */
1160         struct ast_flags flags[2];      /*!<  SIP_ flags */
1161         int expire;                     /*!<  When to expire this peer registration */
1162         int capability;                 /*!<  Codec capability */
1163         int rtptimeout;                 /*!<  RTP timeout */
1164         int rtpholdtimeout;             /*!<  RTP Hold Timeout */
1165         int rtpkeepalive;               /*!<  Send RTP packets for keepalive */
1166         ast_group_t callgroup;          /*!<  Call group */
1167         ast_group_t pickupgroup;        /*!<  Pickup group */
1168         struct sip_proxy *outboundproxy;        /*!< Outbound proxy for this peer */
1169         struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
1170         struct sockaddr_in addr;        /*!<  IP address of peer */
1171         int maxcallbitrate;             /*!< Maximum Bitrate for a video call */
1172         
1173         /* Qualification */
1174         struct sip_pvt *call;           /*!<  Call pointer */
1175         int pokeexpire;                 /*!<  When to expire poke (qualify= checking) */
1176         int lastms;                     /*!<  How long last response took (in ms), or -1 for no response */
1177         int maxms;                      /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
1178         struct timeval ps;              /*!<  Time for sending SIP OPTION in sip_pke_peer() */
1179         struct sockaddr_in defaddr;     /*!<  Default IP address, used until registration */
1180         struct ast_ha *ha;              /*!<  Access control list */
1181         struct ast_variable *chanvars;  /*!<  Variables to set for channel created by user */
1182         struct sip_pvt *mwipvt;         /*!<  Subscription for MWI */
1183         int autoframing;
1184         struct ast_event_sub *mwi_event_sub; /*!< The MWI event subscription */
1185 };
1186
1187
1188
1189 /*! \brief Registrations with other SIP proxies */
1190 struct sip_registry {
1191         ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1192         AST_DECLARE_STRING_FIELDS(
1193                 AST_STRING_FIELD(callid);       /*!< Global Call-ID */
1194                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
1195                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
1196                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
1197                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1198                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
1199                 AST_STRING_FIELD(username);     /*!< Who we are registering as */
1200                 AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
1201                 AST_STRING_FIELD(hostname);     /*!< Domain or host we register to */
1202                 AST_STRING_FIELD(secret);       /*!< Password in clear text */  
1203                 AST_STRING_FIELD(md5secret);    /*!< Password in md5 */
1204                 AST_STRING_FIELD(callback);     /*!< Contact extension */
1205                 AST_STRING_FIELD(random);
1206         );
1207         int portno;                     /*!<  Optional port override */
1208         int expire;                     /*!< Sched ID of expiration */
1209         int expiry;                     /*!< Value to use for the Expires header */
1210         int regattempts;                /*!< Number of attempts (since the last success) */
1211         int timeout;                    /*!< sched id of sip_reg_timeout */
1212         int refresh;                    /*!< How often to refresh */
1213         struct sip_pvt *call;           /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1214         enum sipregistrystate regstate; /*!< Registration state (see above) */
1215         time_t regtime;         /*!< Last successful registration time */
1216         int callid_valid;               /*!< 0 means we haven't chosen callid for this registry yet. */
1217         unsigned int ocseq;             /*!< Sequence number we got to for REGISTERs for this registry */
1218         struct sockaddr_in us;          /*!< Who the server thinks we are */
1219         int noncecount;                 /*!< Nonce-count */
1220         char lastmsg[256];              /*!< Last Message sent/received */
1221 };
1222
1223 /* --- Linked lists of various objects --------*/
1224
1225 /*! \brief  The user list: Users and friends */
1226 static struct ast_user_list {
1227         ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1228 } userl;
1229
1230 /*! \brief  The peer list: Peers and Friends */
1231 static struct ast_peer_list {
1232         ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1233 } peerl;
1234
1235 /*! \brief  The register list: Other SIP proxies we register with and place calls to */
1236 static struct ast_register_list {
1237         ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1238         int recheck;
1239 } regl;
1240
1241 static int temp_pvt_init(void *);
1242 static void temp_pvt_cleanup(void *);
1243
1244 /*! \brief A per-thread temporary pvt structure */
1245 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1246
1247 /*! \brief Authentication list for realm authentication 
1248  * \todo Move the sip_auth list to AST_LIST */
1249 static struct sip_auth *authl = NULL;
1250
1251
1252 /* --- Sockets and networking --------------*/
1253 static int sipsock  = -1;                       /*!< Main socket for SIP network communication */
1254 static struct sockaddr_in bindaddr = { 0, };    /*!< The address we bind to */
1255 static struct sockaddr_in externip;             /*!< External IP address if we are behind NAT */
1256 static char externhost[MAXHOSTNAMELEN];         /*!< External host name (possibly with dynamic DNS and DHCP */
1257 static time_t externexpire = 0;                 /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1258 static int externrefresh = 10;
1259 static struct ast_ha *localaddr;                /*!< List of local networks, on the same side of NAT as this Asterisk */
1260 static struct in_addr __ourip;
1261 static int ourport;
1262 static struct sockaddr_in debugaddr;
1263
1264 static struct ast_config *notify_types;         /*!< The list of manual NOTIFY types we know how to send */
1265
1266 /*---------------------------- Forward declarations of functions in chan_sip.c */
1267 /*! \note This is added to help splitting up chan_sip.c into several files
1268         in coming releases */
1269
1270 /*--- PBX interface functions */
1271 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1272 static int sip_devicestate(void *data);
1273 static int sip_sendtext(struct ast_channel *ast, const char *text);
1274 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1275 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1276 static int sip_hangup(struct ast_channel *ast);
1277 static int sip_answer(struct ast_channel *ast);
1278 static struct ast_frame *sip_read(struct ast_channel *ast);
1279 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1280 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1281 static int sip_transfer(struct ast_channel *ast, const char *dest);
1282 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1283 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1284 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1285
1286 /*--- Transmitting responses and requests */
1287 static int sipsock_read(int *id, int fd, short events, void *ignore);
1288 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1289 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1290 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1291 static int retrans_pkt(void *data);
1292 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1293 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1294 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1295 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1296 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1297 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1298 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1299 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
1300 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1301 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1302 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1303 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1304 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1305 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version);
1306 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1307 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1308 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1309 static int transmit_refer(struct sip_pvt *p, const char *dest);
1310 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1311 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1312 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1313 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1314 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1315 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1316 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1317 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1318 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1319
1320 /*--- Dialog management */
1321 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1322                                  int useglobal_nat, const int intended_method);
1323 static int __sip_autodestruct(void *data);
1324 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1325 static void sip_cancel_destroy(struct sip_pvt *p);
1326 static void sip_destroy(struct sip_pvt *p);
1327 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
1328 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1329 static void __sip_pretend_ack(struct sip_pvt *p);
1330 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1331 static int auto_congest(void *nothing);
1332 static int update_call_counter(struct sip_pvt *fup, int event);
1333 static int hangup_sip2cause(int cause);
1334 static const char *hangup_cause2sip(int cause);
1335 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1336 static void free_old_route(struct sip_route *route);
1337 static void list_route(struct sip_route *route);
1338 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1339 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1340                                               struct sip_request *req, char *uri);
1341 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1342 static void check_pendings(struct sip_pvt *p);
1343 static void *sip_park_thread(void *stuff);
1344 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1345 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1346
1347 /*--- Codec handling / SDP */
1348 static void try_suggested_sip_codec(struct sip_pvt *p);
1349 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1350 static const char *get_sdp(struct sip_request *req, const char *name);
1351 static int find_sdp(struct sip_request *req);
1352 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1353 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1354                              char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1355                              int debug, int *min_packet_size);
1356 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1357                                 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1358                                 int debug);
1359 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1360 static void do_setnat(struct sip_pvt *p, int natflags);
1361 static void stop_media_flows(struct sip_pvt *p);
1362
1363 /*--- Authentication stuff */
1364 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1365 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1366 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1367                                          const char *secret, const char *md5secret, int sipmethod,
1368                                          char *uri, enum xmittype reliable, int ignore);
1369 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1370                                               int sipmethod, char *uri, enum xmittype reliable,
1371                                               struct sockaddr_in *sin, struct sip_peer **authpeer);
1372 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1373
1374 /*--- Domain handling */
1375 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1376 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1377 static void clear_sip_domains(void);
1378
1379 /*--- SIP realm authentication */
1380 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1381 static int clear_realm_authentication(struct sip_auth *authlist);       /* Clear realm authentication list (at reload) */
1382 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1383
1384 /*--- Misc functions */
1385 static int sip_do_reload(enum channelreloadreason reason);
1386 static int reload_config(enum channelreloadreason reason);
1387 static int expire_register(void *data);
1388 static void *do_monitor(void *data);
1389 static int restart_monitor(void);
1390 static void sip_destroy(struct sip_pvt *p);
1391 static int sip_addrcmp(char *name, struct sockaddr_in *sin);    /* Support for peer matching */
1392 static int sip_refer_allocate(struct sip_pvt *p);
1393 static void ast_quiet_chan(struct ast_channel *chan);
1394 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1395
1396 /*--- Device monitoring and Device/extension state/event handling */
1397 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1398 static int sip_devicestate(void *data);
1399 static int sip_poke_noanswer(void *data);
1400 static int sip_poke_peer(struct sip_peer *peer);
1401 static void sip_poke_all_peers(void);
1402 static void sip_peer_hold(struct sip_pvt *p, int hold);
1403 static void mwi_event_cb(const struct ast_event *, void *);
1404
1405 /*--- Applications, functions, CLI and manager command helpers */
1406 static const char *sip_nat_mode(const struct sip_pvt *p);
1407 static int sip_show_inuse(int fd, int argc, char *argv[]);
1408 static char *transfermode2str(enum transfermodes mode) attribute_const;
1409 static char *nat2str(int nat) attribute_const;
1410 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1411 static int sip_show_users(int fd, int argc, char *argv[]);
1412 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1413 static int sip_show_peers(int fd, int argc, char *argv[]);
1414 static int sip_show_objects(int fd, int argc, char *argv[]);
1415 static void  print_group(int fd, ast_group_t group, int crlf);
1416 static const char *dtmfmode2str(int mode) attribute_const;
1417 static const char *insecure2str(int port, int invite) attribute_const;
1418 static void cleanup_stale_contexts(char *new, char *old);
1419 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1420 static const char *domain_mode_to_text(const enum domain_mode mode);
1421 static int sip_show_domains(int fd, int argc, char *argv[]);
1422 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1423 static int sip_show_peer(int fd, int argc, char *argv[]);
1424 static int sip_show_user(int fd, int argc, char *argv[]);
1425 static int sip_show_registry(int fd, int argc, char *argv[]);
1426 static int sip_unregister(int fd, int argc, char *argv[]);
1427 static int sip_show_settings(int fd, int argc, char *argv[]);
1428 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1429 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1430 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1431 static int sip_show_channels(int fd, int argc, char *argv[]);
1432 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1433 static char *complete_sip_channel(const char *word, int state);
1434 static char *complete_sip_peer(const char *word, int state, int flags2);
1435 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1436 static char *complete_sip_show_channel(const char *line, const char *word, int pos, int state);
1437 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1438 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1439 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1440 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1441 static char *complete_sip_user(const char *word, int state, int flags2);
1442 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1443 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1444 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1445 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1446 static int sip_show_channel(int fd, int argc, char *argv[]);
1447 static int sip_show_history(int fd, int argc, char *argv[]);
1448 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1449 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1450 static int sip_do_debug(int fd, int argc, char *argv[]);
1451 static int sip_no_debug(int fd, int argc, char *argv[]);
1452 static int sip_notify(int fd, int argc, char *argv[]);
1453 static int sip_do_history(int fd, int argc, char *argv[]);
1454 static int sip_no_history(int fd, int argc, char *argv[]);
1455 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1456 static int sip_addheader(struct ast_channel *chan, void *data);
1457 static int sip_do_reload(enum channelreloadreason reason);
1458 static int sip_reload(int fd, int argc, char *argv[]);
1459 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1460
1461 /*--- Debugging 
1462         Functions for enabling debug per IP or fully, or enabling history logging for
1463         a SIP dialog
1464 */
1465 static void sip_dump_history(struct sip_pvt *dialog);   /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1466 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1467 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1468 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1469 static void sip_dump_history(struct sip_pvt *dialog);
1470
1471 /*--- Device object handling */
1472 static struct sip_peer *temp_peer(const char *name);
1473 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1474 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1475 static int update_call_counter(struct sip_pvt *fup, int event);
1476 static void sip_destroy_peer(struct sip_peer *peer);
1477 static void sip_destroy_user(struct sip_user *user);
1478 static int sip_poke_peer(struct sip_peer *peer);
1479 static void set_peer_defaults(struct sip_peer *peer);
1480 static struct sip_peer *temp_peer(const char *name);
1481 static void register_peer_exten(struct sip_peer *peer, int onoff);
1482 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1483 static struct sip_user *find_user(const char *name, int realtime);
1484 static int sip_poke_peer_s(void *data);
1485 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1486 static void reg_source_db(struct sip_peer *peer);
1487 static void destroy_association(struct sip_peer *peer);
1488 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1489
1490 /* Realtime device support */
1491 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1492 static struct sip_user *realtime_user(const char *username);
1493 static void update_peer(struct sip_peer *p, int expiry);
1494 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1495 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1496
1497 /*--- Internal UA client handling (outbound registrations) */
1498 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1499 static void sip_registry_destroy(struct sip_registry *reg);
1500 static int sip_register(char *value, int lineno);
1501 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1502 static int sip_reregister(void *data);
1503 static int __sip_do_register(struct sip_registry *r);
1504 static int sip_reg_timeout(void *data);
1505 static void sip_send_all_registers(void);
1506
1507 /*--- Parsing SIP requests and responses */
1508 static void append_date(struct sip_request *req);       /* Append date to SIP packet */
1509 static int determine_firstline_parts(struct sip_request *req);
1510 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1511 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1512 static int find_sip_method(const char *msg);
1513 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1514 static void parse_request(struct sip_request *req);
1515 static const char *get_header(const struct sip_request *req, const char *name);
1516 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1517 static int method_match(enum sipmethod id, const char *name);
1518 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1519 static char *get_in_brackets(char *tmp);
1520 static const char *find_alias(const char *name, const char *_default);
1521 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1522 static int lws2sws(char *msgbuf, int len);
1523 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1524 static char *remove_uri_parameters(char *uri);
1525 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1526 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1527 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1528 static int set_address_from_contact(struct sip_pvt *pvt);
1529 static void check_via(struct sip_pvt *p, struct sip_request *req);
1530 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1531 static int get_rpid_num(const char *input, char *output, int maxlen);
1532 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1533 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1534 static int get_msg_text(char *buf, int len, struct sip_request *req);
1535 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1536
1537 /*--- Constructing requests and responses */
1538 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1539 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1540 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1541 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1542 static int init_resp(struct sip_request *resp, const char *msg);
1543 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1544 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1545 static void build_via(struct sip_pvt *p);
1546 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1547 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1548 static char *generate_random_string(char *buf, size_t size);
1549 static void build_callid_pvt(struct sip_pvt *pvt);
1550 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1551 static void make_our_tag(char *tagbuf, size_t len);
1552 static int add_header(struct sip_request *req, const char *var, const char *value);
1553 static int add_header_contentLength(struct sip_request *req, int len);
1554 static int add_line(struct sip_request *req, const char *line);
1555 static int add_text(struct sip_request *req, const char *text);
1556 static int add_digit(struct sip_request *req, char digit, unsigned int duration);
1557 static int add_vidupdate(struct sip_request *req);
1558 static void add_route(struct sip_request *req, struct sip_route *route);
1559 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1560 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1561 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1562 static void set_destination(struct sip_pvt *p, char *uri);
1563 static void append_date(struct sip_request *req);
1564 static void build_contact(struct sip_pvt *p);
1565 static void build_rpid(struct sip_pvt *p);
1566
1567 /*------Request handling functions */
1568 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1569 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, int *nounlock);
1570 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1571 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1572 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1573 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1574 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1575 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1576 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1577 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1578 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1579 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1580 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1581
1582 /*------Response handling functions */
1583 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1584 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1585 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1586 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1587
1588 /*----- RTP interface functions */
1589 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp,  struct ast_rtp *trtp, int codecs, int nat_active);
1590 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1591 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1592 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1593 static int sip_get_codec(struct ast_channel *chan);
1594 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1595
1596 /*------ T38 Support --------- */
1597 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); 
1598 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1599 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1600 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1601
1602 /*! \brief Definition of this channel for PBX channel registration */
1603 static const struct ast_channel_tech sip_tech = {
1604         .type = "SIP",
1605         .description = "Session Initiation Protocol (SIP)",
1606         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1607         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1608         .requester = sip_request_call,
1609         .devicestate = sip_devicestate,
1610         .call = sip_call,
1611         .send_html = sip_sendhtml,
1612         .hangup = sip_hangup,
1613         .answer = sip_answer,
1614         .read = sip_read,
1615         .write = sip_write,
1616         .write_video = sip_write,
1617         .write_text = sip_write,
1618         .indicate = sip_indicate,
1619         .transfer = sip_transfer,
1620         .fixup = sip_fixup,
1621         .send_digit_begin = sip_senddigit_begin,
1622         .send_digit_end = sip_senddigit_end,
1623         .bridge = ast_rtp_bridge,
1624         .early_bridge = ast_rtp_early_bridge,
1625         .send_text = sip_sendtext,
1626         .func_channel_read = acf_channel_read,
1627 };
1628
1629 /*! \brief This version of the sip channel tech has no send_digit_begin
1630  *  callback.  This is for use with channels using SIP INFO DTMF so that
1631  *  the core knows that the channel doesn't want DTMF BEGIN frames. */
1632 static const struct ast_channel_tech sip_tech_info = {
1633         .type = "SIP",
1634         .description = "Session Initiation Protocol (SIP)",
1635         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1636         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1637         .requester = sip_request_call,
1638         .devicestate = sip_devicestate,
1639         .call = sip_call,
1640         .hangup = sip_hangup,
1641         .answer = sip_answer,
1642         .read = sip_read,
1643         .write = sip_write,
1644         .write_video = sip_write,
1645         .indicate = sip_indicate,
1646         .transfer = sip_transfer,
1647         .fixup = sip_fixup,
1648         .send_digit_end = sip_senddigit_end,
1649         .bridge = ast_rtp_bridge,
1650         .send_text = sip_sendtext,
1651         .func_channel_read = acf_channel_read,
1652 };
1653
1654 /**--- some list management macros. **/
1655  
1656 #define UNLINK(element, head, prev) do {        \
1657         if (prev)                               \
1658                 (prev)->next = (element)->next; \
1659         else                                    \
1660                 (head) = (element)->next;       \
1661         } while (0)
1662
1663 /*! \brief Interface structure with callbacks used to connect to RTP module */
1664 static struct ast_rtp_protocol sip_rtp = {
1665         type: "SIP",
1666         get_rtp_info: sip_get_rtp_peer,
1667         get_vrtp_info: sip_get_vrtp_peer,
1668         get_trtp_info: sip_get_trtp_peer,
1669         set_rtp_peer: sip_set_rtp_peer,
1670         get_codec: sip_get_codec,
1671 };
1672
1673 /*! \brief Helper function to lock, hiding the underlying locking mechanism.  */
1674 static void sip_pvt_lock(struct sip_pvt *pvt)
1675 {
1676         ast_mutex_lock(&pvt->pvt_lock);
1677 }
1678
1679 /*! \brief Helper function to unlock pvt, hiding the underlying locking mechanism. */
1680 static void sip_pvt_unlock(struct sip_pvt *pvt)
1681 {
1682         ast_mutex_unlock(&pvt->pvt_lock);
1683 }
1684
1685 /*!
1686  * helper functions to unreference various types of objects.
1687  * By handling them this way, we don't have to declare the
1688  * destructor on each call, which removes the chance of errors.
1689  */
1690 static void unref_peer(struct sip_peer *peer)
1691 {
1692         ASTOBJ_UNREF(peer, sip_destroy_peer);
1693 }
1694
1695 static void unref_user(struct sip_user *user)
1696 {
1697         ASTOBJ_UNREF(user, sip_destroy_user);
1698 }
1699
1700 static void registry_unref(struct sip_registry *reg)
1701 {
1702         ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
1703         ASTOBJ_UNREF(reg, sip_registry_destroy);
1704 }
1705
1706 /*! \brief Add object reference to SIP registry */
1707 static struct sip_registry *registry_addref(struct sip_registry *reg)
1708 {
1709         ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
1710         return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
1711 }
1712
1713 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1714 static struct ast_udptl_protocol sip_udptl = {
1715         type: "SIP",
1716         get_udptl_info: sip_get_udptl_peer,
1717         set_udptl_peer: sip_set_udptl_peer,
1718 };
1719
1720 /*! \brief Append to SIP dialog history 
1721         \return Always returns 0 */
1722 #define append_history(p, event, fmt , args... )        append_history_full(p, "%-15s " fmt, event, ## args)
1723
1724 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1725         __attribute__ ((format (printf, 2, 3)));
1726
1727
1728 /*! \brief Convert transfer status to string */
1729 static const char *referstatus2str(enum referstatus rstatus)
1730 {
1731         int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1732         int x;
1733
1734         for (x = 0; x < i; x++) {
1735                 if (referstatusstrings[x].status ==  rstatus)
1736                         return referstatusstrings[x].text;
1737         }
1738         return "";
1739 }
1740
1741 /*! \brief Initialize the initital request packet in the pvt structure.
1742         This packet is used for creating replies and future requests in
1743         a dialog */
1744 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1745 {
1746         if (p->initreq.headers)
1747                 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1748         else
1749                 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
1750         /* Use this as the basis */
1751         copy_request(&p->initreq, req);
1752         parse_request(&p->initreq);
1753         if (ast_test_flag(req, SIP_PKT_DEBUG))
1754                 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1755 }
1756
1757 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
1758 static void sip_alreadygone(struct sip_pvt *dialog)
1759 {
1760         ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1761         ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
1762 }
1763
1764 /*! Resolve DNS srv name or host name in a sip_proxy structure */
1765 static int proxy_update(struct sip_proxy *proxy)
1766 {
1767         /* if it's actually an IP address and not a name,
1768            there's no need for a managed lookup */
1769         if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
1770                 /* Ok, not an IP address, then let's check if it's a domain or host */
1771                 /* XXX Todo - if we have proxy port, don't do SRV */
1772                 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
1773                         ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
1774                         return FALSE;
1775                 }
1776         }
1777         proxy->last_dnsupdate = time(NULL);
1778         return TRUE;
1779 }
1780
1781 /*! \brief Allocate and initialize sip proxy */
1782 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
1783 {
1784         struct sip_proxy *proxy;
1785         proxy = ast_calloc(1, sizeof(*proxy));
1786         if (!proxy)
1787                 return NULL;
1788         proxy->force = force;
1789         ast_copy_string(proxy->name, name, sizeof(proxy->name));
1790         proxy->ip.sin_port = htons((!ast_strlen_zero(port) ? atoi(port) : STANDARD_SIP_PORT));
1791         proxy_update(proxy);
1792         return proxy;
1793 }
1794
1795 /*! \brief Get default outbound proxy or global proxy */
1796 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
1797 {
1798         if (peer && peer->outboundproxy) {
1799                 if (sipdebug)
1800                         ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
1801                 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
1802                 return peer->outboundproxy;
1803         }
1804         if (global_outboundproxy.name[0]) {
1805                 if (sipdebug)
1806                         ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
1807                 append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
1808                 return &global_outboundproxy;
1809         }
1810         if (sipdebug)
1811                 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
1812         return NULL;
1813 }
1814
1815 /*! \brief returns true if 'name' (with optional trailing whitespace)
1816  * matches the sip method 'id'.
1817  * Strictly speaking, SIP methods are case SENSITIVE, but we do
1818  * a case-insensitive comparison to be more tolerant.
1819  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1820  */
1821 static int method_match(enum sipmethod id, const char *name)
1822 {
1823         int len = strlen(sip_methods[id].text);
1824         int l_name = name ? strlen(name) : 0;
1825         /* true if the string is long enough, and ends with whitespace, and matches */
1826         return (l_name >= len && name[len] < 33 &&
1827                 !strncasecmp(sip_methods[id].text, name, len));
1828 }
1829
1830 /*! \brief  find_sip_method: Find SIP method from header */
1831 static int find_sip_method(const char *msg)
1832 {
1833         int i, res = 0;
1834         
1835         if (ast_strlen_zero(msg))
1836                 return 0;
1837         for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1838                 if (method_match(i, msg))
1839                         res = sip_methods[i].id;
1840         }
1841         return res;
1842 }
1843
1844 /*! \brief Parse supported header in incoming packet */
1845 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1846 {
1847         char *next, *sep;
1848         char *temp;
1849         unsigned int profile = 0;
1850         int i, found;
1851
1852         if (ast_strlen_zero(supported) )
1853                 return 0;
1854         temp = ast_strdupa(supported);
1855
1856         if (sipdebug)
1857                 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1858
1859         for (next = temp; next; next = sep) {
1860                 found = FALSE;
1861                 if ( (sep = strchr(next, ',')) != NULL)
1862                         *sep++ = '\0';
1863                 next = ast_skip_blanks(next);
1864                 if (sipdebug)
1865                         ast_debug(3, "Found SIP option: -%s-\n", next);
1866                 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1867                         if (!strcasecmp(next, sip_options[i].text)) {
1868                                 profile |= sip_options[i].id;
1869                                 found = TRUE;
1870                                 if (sipdebug)
1871                                         ast_debug(3, "Matched SIP option: %s\n", next);
1872                                 break;
1873                         }
1874                 }
1875                 if (!found && sipdebug) {
1876                         if (!strncasecmp(next, "x-", 2))
1877                                 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
1878                         else
1879                                 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1880                 }
1881         }
1882
1883         if (pvt)
1884                 pvt->sipoptions = profile;
1885         return profile;
1886 }
1887
1888 /*! \brief See if we pass debug IP filter */
1889 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
1890 {
1891         if (!sipdebug)
1892                 return 0;
1893         if (debugaddr.sin_addr.s_addr) {
1894                 if (((ntohs(debugaddr.sin_port) != 0)
1895                         && (debugaddr.sin_port != addr->sin_port))
1896                         || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1897                         return 0;
1898         }
1899         return 1;
1900 }
1901
1902 /*! \brief The real destination address for a write */
1903 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1904 {
1905         if (p->outboundproxy)
1906                 return &p->outboundproxy->ip;
1907
1908         return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1909 }
1910
1911 /*! \brief Display SIP nat mode */
1912 static const char *sip_nat_mode(const struct sip_pvt *p)
1913 {
1914         return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1915 }
1916
1917 /*! \brief Test PVT for debugging output */
1918 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
1919 {
1920         if (!sipdebug)
1921                 return 0;
1922         return sip_debug_test_addr(sip_real_dst(p));
1923 }
1924
1925 /*! \brief Transmit SIP message */
1926 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1927 {
1928         int res;
1929         const struct sockaddr_in *dst = sip_real_dst(p);
1930         res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1931
1932         if (res == -1) {
1933                 switch (errno) {
1934                         case EBADF:             /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
1935                         case EHOSTUNREACH:      /* Host can't be reached */
1936                         case ENETDOWN:          /* Inteface down */
1937                         case ENETUNREACH:       /* Network failure */
1938                                 res = XMIT_ERROR;       /* Don't bother with trying to transmit again */
1939                 }
1940         }
1941         if (res != len)
1942                 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
1943         return res;
1944 }
1945
1946
1947 /*! \brief Build a Via header for a request */
1948 static void build_via(struct sip_pvt *p)
1949 {
1950         /* Work around buggy UNIDEN UIP200 firmware */
1951         const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1952
1953         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
1954         ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1955                          ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1956 }
1957
1958 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1959  *
1960  * Using the localaddr structure built up with localnet statements in sip.conf
1961  * apply it to their address to see if we need to substitute our
1962  * externip or can get away with our internal bindaddr
1963  */
1964 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1965 {
1966         struct sockaddr_in theirs, ours;
1967
1968         /* Get our local information */
1969         ast_ouraddrfor(them, us);
1970         theirs.sin_addr = *them;
1971         ours.sin_addr = *us;
1972
1973         if (localaddr && externip.sin_addr.s_addr &&
1974             (ast_apply_ha(localaddr, &theirs)) &&
1975             (!global_matchexterniplocally || !ast_apply_ha(localaddr, &ours))) {
1976                 if (externexpire && time(NULL) >= externexpire) {
1977                         struct ast_hostent ahp;
1978                         struct hostent *hp;
1979
1980                         externexpire = time(NULL) + externrefresh;
1981                         if ((hp = ast_gethostbyname(externhost, &ahp))) {
1982                                 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1983                         } else
1984                                 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1985                 }
1986                 *us = externip.sin_addr;
1987                 ast_debug(1, "Target address %s is not local, substituting externip\n", 
1988                         ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1989         } else if (bindaddr.sin_addr.s_addr)
1990                 *us = bindaddr.sin_addr;
1991         return AST_SUCCESS;
1992 }
1993
1994 /*! \brief Append to SIP dialog history with arg list  */
1995 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1996 {
1997         char buf[80], *c = buf; /* max history length */
1998         struct sip_history *hist;
1999         int l;
2000
2001         vsnprintf(buf, sizeof(buf), fmt, ap);
2002         strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
2003         l = strlen(buf) + 1;
2004         if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
2005                 return;
2006         if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
2007                 ast_free(hist);
2008                 return;
2009         }
2010         memcpy(hist->event, buf, l);
2011         AST_LIST_INSERT_TAIL(p->history, hist, list);
2012 }
2013
2014 /*! \brief Append to SIP dialog history with arg list  */
2015 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2016 {
2017         va_list ap;
2018
2019         if (!p)
2020                 return;
2021         va_start(ap, fmt);
2022         append_history_va(p, fmt, ap);
2023         va_end(ap);
2024
2025         return;
2026 }
2027
2028 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
2029 static int retrans_pkt(void *data)
2030 {
2031         struct sip_pkt *pkt = data, *prev, *cur = NULL;
2032         int reschedule = DEFAULT_RETRANS;
2033         int xmitres = 0;
2034
2035         /* Lock channel PVT */
2036         sip_pvt_lock(pkt->owner);
2037
2038         if (pkt->retrans < MAX_RETRANS) {
2039                 pkt->retrans++;
2040                 if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
2041                         if (sipdebug)
2042                                 ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
2043                 } else {
2044                         int siptimer_a;
2045
2046                         if (sipdebug)
2047                                 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
2048                         if (!pkt->timer_a)
2049                                 pkt->timer_a = 2 ;
2050                         else
2051                                 pkt->timer_a = 2 * pkt->timer_a;
2052  
2053                         /* For non-invites, a maximum of 4 secs */
2054                         siptimer_a = pkt->timer_t1 * pkt->timer_a;      /* Double each time */
2055                         if (pkt->method != SIP_INVITE && siptimer_a > 4000)
2056                                 siptimer_a = 4000;
2057                 
2058                         /* Reschedule re-transmit */
2059                         reschedule = siptimer_a;
2060                         ast_debug(4, "** 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);
2061                 } 
2062
2063                 if (sip_debug_test_pvt(pkt->owner)) {
2064                         const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
2065                         ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
2066                                 pkt->retrans, sip_nat_mode(pkt->owner),
2067                                 ast_inet_ntoa(dst->sin_addr),
2068                                 ntohs(dst->sin_port), pkt->data);
2069                 }
2070
2071                 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
2072                 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
2073                 sip_pvt_unlock(pkt->owner);
2074                 if (xmitres == XMIT_ERROR)
2075                         ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
2076                 else 
2077                         return  reschedule;
2078         } 
2079         /* Too many retries */
2080         if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
2081                 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
2082                         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");
2083         } else if (pkt->method == SIP_OPTIONS && sipdebug) {
2084                         ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
2085
2086         } 
2087         if (xmitres == XMIT_ERROR) {
2088                 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
2089                 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
2090         } else 
2091                 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
2092                 
2093         pkt->retransid = -1;
2094
2095         if (ast_test_flag(pkt, FLAG_FATAL)) {
2096                 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
2097                         sip_pvt_unlock(pkt->owner);     /* SIP_PVT, not channel */
2098                         usleep(1);
2099                         sip_pvt_lock(pkt->owner);
2100                 }
2101
2102                 if (pkt->owner->owner && !pkt->owner->owner->hangupcause) 
2103                         pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
2104                 
2105                 if (pkt->owner->owner) {
2106                         sip_alreadygone(pkt->owner);
2107                         ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
2108                         ast_queue_hangup(pkt->owner->owner);
2109                         ast_channel_unlock(pkt->owner->owner);
2110                 } else {
2111                         /* If no channel owner, destroy now */
2112
2113                         /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
2114                         if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
2115                                 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);   
2116                                 sip_alreadygone(pkt->owner);
2117                                 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
2118                         }
2119                 }
2120         }
2121
2122         if (pkt->method == SIP_BYE) {
2123                 /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
2124                 if (pkt->owner->owner) 
2125                         ast_channel_unlock(pkt->owner->owner);
2126                 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
2127                 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
2128         }
2129
2130         /* Remove the packet */
2131         for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2132                 if (cur == pkt) {
2133                         UNLINK(cur, pkt->owner->packets, prev);
2134                         sip_pvt_unlock(pkt->owner);
2135                         ast_free(pkt);
2136                         return 0;
2137                 }
2138         }
2139         /* error case */
2140         ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
2141         sip_pvt_unlock(pkt->owner);
2142         return 0;
2143 }
2144
2145 /*! \brief Transmit packet with retransmits 
2146         \return 0 on success, -1 on failure to allocate packet 
2147 */
2148 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
2149 {
2150         struct sip_pkt *pkt;
2151         int siptimer_a = DEFAULT_RETRANS;
2152         int xmitres = 0;
2153
2154         if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
2155                 return AST_FAILURE;
2156         memcpy(pkt->data, data, len);
2157         pkt->method = sipmethod;
2158         pkt->packetlen = len;
2159         pkt->next = p->packets;
2160         pkt->owner = p;
2161         pkt->seqno = seqno;
2162         if (resp)
2163                 ast_set_flag(pkt, FLAG_RESPONSE);
2164         pkt->data[len] = '\0';
2165         pkt->timer_t1 = p->timer_t1;    /* Set SIP timer T1 */
2166         if (fatal)
2167                 ast_set_flag(pkt, FLAG_FATAL);
2168         if (pkt->timer_t1)
2169                 siptimer_a = pkt->timer_t1 * 2;
2170
2171         /* Schedule retransmission */
2172         pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
2173         if (sipdebug)
2174                 ast_debug(4, "*** SIP TIMER: Initalizing retransmit timer on packet: Id  #%d\n", pkt->retransid);
2175         pkt->next = p->packets;
2176         p->packets = pkt;
2177         if (sipmethod == SIP_INVITE) {
2178                 /* Note this is a pending invite */
2179                 p->pendinginvite = seqno;
2180         }
2181
2182         xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);    /* Send packet */
2183
2184         if (xmitres == XMIT_ERROR) {    /* Serious network trouble, no need to try again */
2185                 append_history(pkt->owner, "XmitErr", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
2186                 ast_sched_del(sched, pkt->retransid);   /* No more retransmission */
2187                 pkt->retransid = -1;
2188                 return AST_FAILURE;
2189         } else
2190                 return AST_SUCCESS;
2191 }
2192
2193 /*! \brief Kill a SIP dialog (called by scheduler) */
2194 static int __sip_autodestruct(void *data)
2195 {
2196         struct sip_pvt *p = data;
2197
2198         /* If this is a subscription, tell the phone that we got a timeout */
2199         if (p->subscribed) {
2200                 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);   /* Send last notification */
2201                 p->subscribed = NONE;
2202                 append_history(p, "Subscribestatus", "timeout");
2203                 ast_debug(3, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
2204                 return 10000;   /* Reschedule this destruction so that we know that it's gone */
2205         }
2206
2207         if (p->subscribed == MWI_NOTIFICATION)
2208                 if (p->relatedpeer)
2209                         unref_peer(p->relatedpeer);     /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
2210
2211         /* Reset schedule ID */
2212         p->autokillid = -1;
2213
2214         if (p->owner) {
2215                 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2216                 ast_queue_hangup(p->owner);
2217         } else if (p->refer) {
2218                 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
2219                 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2220                 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
2221                 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2222         } else {
2223                 append_history(p, "AutoDestroy", "%s", p->callid);
2224                 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
2225                 sip_destroy(p);         /* Go ahead and destroy dialog. All attempts to recover is done */
2226         }
2227         return 0;
2228 }
2229
2230 /*! \brief Schedule destruction of SIP dialog */
2231 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2232 {
2233         if (ms < 0) {
2234                 if (p->timer_t1 == 0)
2235                         p->timer_t1 = SIP_TIMER_T1;     /* Set timer T1 if not set (RFC 3261) */
2236                 ms = p->timer_t1 * 64;
2237         }
2238         if (sip_debug_test_pvt(p))
2239                 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2240         if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
2241                 append_history(p, "SchedDestroy", "%d ms", ms);
2242
2243         if (p->autokillid > -1)
2244                 ast_sched_del(sched, p->autokillid);
2245         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
2246 }
2247
2248 /*! \brief Cancel destruction of SIP dialog */
2249 static void sip_cancel_destroy(struct sip_pvt *p)
2250 {
2251         if (p->autokillid > -1) {
2252                 ast_sched_del(sched, p->autokillid);
2253                 append_history(p, "CancelDestroy", "");
2254                 p->autokillid = -1;
2255         }
2256 }
2257
2258 /*! \brief Acknowledges receipt of a packet and stops retransmission */
2259 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2260 {
2261         struct sip_pkt *cur, *prev = NULL;
2262         const char *msg = "Not Found";  /* used only for debugging */
2263
2264         sip_pvt_lock(p);
2265
2266         /* If we have an outbound proxy for this dialog, then delete it now since
2267           the rest of the requests in this dialog needs to follow the routing.
2268           If obforcing is set, we will keep the outbound proxy during the whole
2269           dialog, regardless of what the SIP rfc says
2270         */
2271         if (p->outboundproxy && !p->outboundproxy->force)
2272                 p->outboundproxy = NULL;
2273
2274         for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2275                 if (cur->seqno != seqno || ast_test_flag(cur, FLAG_RESPONSE) != resp)
2276                         continue;
2277                 if (ast_test_flag(cur, FLAG_RESPONSE) || cur->method == sipmethod) {
2278                         msg = "Found";
2279                         if (!resp && (seqno == p->pendinginvite)) {
2280                                 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
2281                                 p->pendinginvite = 0;
2282                         }
2283                         if (cur->retransid > -1) {
2284                                 if (sipdebug)
2285                                         ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2286                                 ast_sched_del(sched, cur->retransid);
2287                                 cur->retransid = -1;
2288                         }
2289                         UNLINK(cur, p->packets, prev);
2290                         ast_free(cur);
2291                         break;
2292                 }
2293         }
2294         sip_pvt_unlock(p);
2295         ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
2296                 p->callid, resp ? "Response" : "Request", seqno, msg);
2297 }
2298
2299 /*! \brief Pretend to ack all packets
2300  * maybe the lock on p is not strictly necessary but there might be a race */
2301 static void __sip_pretend_ack(struct sip_pvt *p)
2302 {
2303         struct sip_pkt *cur = NULL;
2304
2305         while (p->packets) {
2306                 int method;
2307                 if (cur == p->packets) {
2308                         ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2309                         return;
2310                 }
2311                 cur = p->packets;
2312                 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2313                 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
2314         }
2315 }
2316
2317 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2318 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2319 {
2320         struct sip_pkt *cur;
2321         int res = -1;
2322
2323         for (cur = p->packets; cur; cur = cur->next) {
2324                 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2325                         (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2326                         /* this is our baby */
2327                         if (cur->retransid > -1) {
2328                                 if (sipdebug)
2329                                         ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2330                                 ast_sched_del(sched, cur->retransid);
2331                                 cur->retransid = -1;
2332                         }
2333                         res = 0;
2334                         break;
2335                 }
2336         }
2337         ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
2338         return res;
2339 }
2340
2341
2342 /*! \brief Copy SIP request, parse it */
2343 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2344 {
2345         memset(dst, 0, sizeof(*dst));
2346         memcpy(dst->data, src->data, sizeof(dst->data));
2347         dst->len = src->len;
2348         parse_request(dst);
2349 }
2350
2351 /*! \brief add a blank line if no body */
2352 static void add_blank(struct sip_request *req)
2353 {
2354         if (!req->lines) {
2355                 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2356                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2357                 req->len += strlen(req->data + req->len);
2358         }
2359 }
2360
2361 /*! \brief Transmit response on SIP request*/
2362 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2363 {
2364         int res;
2365
2366         add_blank(req);
2367         if (sip_debug_test_pvt(p)) {
2368                 const struct sockaddr_in *dst = sip_real_dst(p);
2369
2370                 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2371                         reliable ? "Reliably " : "", sip_nat_mode(p),
2372                         ast_inet_ntoa(dst->sin_addr),
2373                         ntohs(dst->sin_port), req->data);
2374         }
2375         if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2376                 struct sip_request tmp;
2377                 parse_copy(&tmp, req);
2378                 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), 
2379                         (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2380         }
2381         res = (reliable) ?
2382                  __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2383                 __sip_xmit(p, req->data, req->len);
2384         if (res > 0)
2385                 return 0;
2386         return res;
2387 }
2388
2389 /*! \brief Send SIP Request to the other part of the dialogue */
2390 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2391 {
2392         int res;
2393
2394         /* If we have an outbound proxy, reset peer address 
2395                 Only do this once.
2396         */
2397         if (p->outboundproxy) {
2398                 p->sa = p->outboundproxy->ip;
2399         }
2400
2401         add_blank(req);
2402         if (sip_debug_test_pvt(p)) {
2403                 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2404                         ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
2405                 else
2406                         ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
2407         }
2408         if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2409                 struct sip_request tmp;
2410                 parse_copy(&tmp, req);
2411                 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2412         }
2413         res = (reliable) ?
2414                 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2415                 __sip_xmit(p, req->data, req->len);
2416         return res;
2417 }
2418
2419 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2420  * optionally with a limit on the search.
2421  * start must be past the first quote.
2422  */
2423 static const char *find_closing_quote(const char *start, const char *lim)
2424 {
2425         char last_char = '\0';
2426         const char *s;
2427         for (s = start; *s && s != lim; last_char = *s++) {
2428                 if (*s == '"' && last_char != '\\')
2429                         break;
2430         }
2431         return s;
2432 }
2433
2434 /*! \brief Pick out text in brackets from character string
2435         \return pointer to terminated stripped string
2436         \param tmp input string that will be modified
2437         Examples:
2438 \verbatim
2439         "foo" <bar>     valid input, returns bar
2440         foo             returns the whole string
2441         < "foo ... >    returns the string between brackets
2442         < "foo...       bogus (missing closing bracket), returns the whole string
2443                         XXX maybe should still skip the opening bracket
2444 \endverbatim
2445  */
2446 static char *get_in_brackets(char *tmp)
2447 {
2448         const char *parse = tmp;
2449         char *first_bracket;
2450
2451         /*
2452          * Skip any quoted text until we find the part in brackets.
2453         * On any error give up and return the full string.
2454         */
2455         while ( (first_bracket = strchr(parse, '<')) ) {
2456                 char *first_quote = strchr(parse, '"');
2457
2458                 if (!first_quote || first_quote > first_bracket)
2459                         break; /* no need to look at quoted part */
2460                 /* the bracket is within quotes, so ignore it */
2461                 parse = find_closing_quote(first_quote + 1, NULL);
2462                 if (!*parse) { /* not found, return full string ? */
2463                         /* XXX or be robust and return in-bracket part ? */
2464                         ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2465                         break;
2466                 }
2467                 parse++;
2468         }
2469         if (first_bracket) {
2470                 char *second_bracket = strchr(first_bracket + 1, '>');
2471                 if (second_bracket) {
2472                         *second_bracket = '\0';
2473                         tmp = first_bracket + 1;
2474                 } else {
2475                         ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2476                 }
2477         }
2478         return tmp;
2479 }
2480
2481 /*! \brief * parses a URI in its components.
2482  *
2483  * \note 
2484  *- If scheme is specified, drop it from the top.
2485  * - If a component is not requested, do not split around it.
2486  * This means that if we don't have domain, we cannot split
2487  * name:pass and domain:port.
2488  * It is safe to call with ret_name, pass, domain, port
2489  * pointing all to the same place.
2490  * Init pointers to empty string so we never get NULL dereferencing.
2491  * Overwrites the string.
2492  * return 0 on success, other values on error.
2493  * \verbatim 
2494  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
2495  * \endverbatim
2496  */
2497 static int parse_uri(char *uri, char *scheme,
2498         char **ret_name, char **pass, char **domain, char **port, char **options)
2499 {
2500         char *name = NULL;
2501         int error = 0;
2502
2503         /* init field as required */
2504         if (pass)
2505                 *pass = "";
2506         if (port)
2507                 *port = "";
2508         if (scheme) {
2509                 int l = strlen(scheme);
2510                 if (!strncasecmp(uri, scheme, l))
2511                         uri += l;
2512                 else {
2513                         ast_log(LOG_NOTICE, "Missing scheme '%s' in '%s'\n", scheme, uri);
2514                         error = -1;
2515                 }
2516         }
2517         if (!domain) {
2518                 /* if we don't want to split around domain, keep everything as a name,
2519                  * so we need to do nothing here, except remember why.
2520                  */
2521         } else {
2522                 /* store the result in a temp. variable to avoid it being
2523                  * overwritten if arguments point to the same place.
2524                  */
2525                 char *c, *dom = "";
2526
2527                 if ((c = strchr(uri, '@')) == NULL) {
2528                         /* domain-only URI, according to the SIP RFC. */
2529                         dom = uri;
2530                         name = "";
2531                 } else {
2532                         *c++ = '\0';
2533                         dom = c;
2534                         name = uri;
2535                 }
2536
2537                 /* Remove options in domain and name */
2538                 dom = strsep(&dom, ";");
2539                 name = strsep(&name, ";");
2540
2541                 if (port && (c = strchr(dom, ':'))) { /* Remove :port */
2542                         *c++ = '\0';
2543                         *port = c;
2544                 }
2545                 if (pass && (c = strchr(name, ':'))) {  /* user:password */
2546                         *c++ = '\0';
2547                         *pass = c;
2548                 }
2549                 *domain = dom;
2550         }
2551         if (ret_name)   /* same as for domain, store the result only at the end */
2552                 *ret_name = name;
2553         if (options)
2554                 *options = uri ? uri : "";
2555
2556         return error;
2557 }
2558
2559 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
2560 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2561 {
2562         struct sip_pvt *p = chan->tech_pvt;
2563
2564         if (subclass != AST_HTML_URL)
2565                 return -1;
2566
2567         ast_string_field_build(p, url, "<%s>;mode=active", data);
2568
2569         if (sip_debug_test_pvt(p))
2570                 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
2571
2572         switch (chan->_state) {
2573         case AST_STATE_RING:
2574                 transmit_response(p, "100 Trying", &p->initreq);
2575                 break;
2576         case AST_STATE_RINGING:
2577                 transmit_response(p, "180 Ringing", &p->initreq);
2578                 break;
2579         case AST_STATE_UP:
2580                 if (!p->pendinginvite) {                /* We are up, and have no outstanding invite */
2581                         transmit_reinvite_with_sdp(p, FALSE);
2582                 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
2583                         ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
2584                 }       
2585                 break;
2586         default:
2587                 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
2588         }
2589
2590         return 0;
2591 }
2592
2593 /*! \brief Send SIP MESSAGE text within a call
2594         Called from PBX core sendtext() application */
2595 static int sip_sendtext(struct ast_channel *ast, const char *text)
2596 {
2597         struct sip_pvt *p = ast->tech_pvt;
2598         int debug = sip_debug_test_pvt(p);
2599
2600         if (debug)
2601                 ast_verbose("Sending text %s on %s\n", text, ast->name);
2602         if (!p)
2603                 return -1;
2604         if (ast_strlen_zero(text))
2605                 return 0;
2606         if (debug)
2607                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2608         transmit_message_with_text(p, text);
2609         return 0;       
2610 }
2611
2612 /*! \brief Update peer object in realtime storage 
2613         If the Asterisk system name is set in asterisk.conf, we will use
2614         that name and store that in the "regserver" field in the sippeers
2615         table to facilitate multi-server setups.
2616 */
2617 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2618 {
2619         char port[10];
2620         char ipaddr[INET_ADDRSTRLEN];
2621         char regseconds[20];
2622         char *tablename = NULL;
2623
2624         char *sysname = ast_config_AST_SYSTEM_NAME;
2625         char *syslabel = NULL;
2626
2627         time_t nowtime = time(NULL) + expirey;
2628         const char *fc = fullcontact ? "fullcontact" : NULL;
2629
2630         int realtimeregs = ast_check_realtime("sipregs");
2631
2632         tablename = realtimeregs ? "sipregs" : "sippeers";
2633         
2634         snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);   /* Expiration time */
2635         ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2636         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2637         
2638         if (ast_strlen_zero(sysname))   /* No system name, disable this */
2639                 sysname = NULL;
2640         else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2641                 syslabel = "regserver";
2642
2643         if (fc)
2644                 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
2645                         "port", port, "regseconds", regseconds,
2646                         "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2647         else
2648                 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
2649                         "port", port, "regseconds", regseconds,
2650                         "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2651 }
2652
2653 /*! \brief Automatically add peer extension to dial plan */
2654 static void register_peer_exten(struct sip_peer *peer, int onoff)
2655 {
2656         char multi[256];
2657         char *stringp, *ext, *context;
2658
2659         /* XXX note that global_regcontext is both a global 'enable' flag and
2660          * the name of the global regexten context, if not specified
2661          * individually.
2662          */
2663         if (ast_strlen_zero(global_regcontext))
2664                 return;
2665
2666         ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2667         stringp = multi;
2668         while ((ext = strsep(&stringp, "&"))) {
2669                 if ((context = strchr(ext, '@'))) {
2670                         *context++ = '\0';      /* split ext@context */
2671                         if (!ast_context_find(context)) {
2672                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2673                                 continue;
2674                         }
2675                 } else {
2676                         context = global_regcontext;
2677                 }
2678                 if (onoff)
2679                         ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2680                                  ast_strdup(peer->name), ast_free, "SIP");
2681                 else
2682                         ast_context_remove_extension(context, ext, 1, NULL);
2683         }
2684 }
2685
2686 /*! \brief Destroy peer object from memory */
2687 static void sip_destroy_peer(struct sip_peer *peer)
2688 {
2689         ast_debug(3, "Destroying SIP peer %s\n", peer->name);
2690
2691         if (peer->outboundproxy)
2692                 ast_free(peer->outboundproxy);
2693
2694         /* Delete it, it needs to disappear */
2695         if (peer->call)
2696                 sip_destroy(peer->call);
2697
2698         if (peer->mwipvt)       /* We have an active subscription, delete it */
2699                 sip_destroy(peer->mwipvt);
2700
2701         if (peer->mwi_event_sub) {
2702                 ast_event_unsubscribe(peer->mwi_event_sub);
2703                 peer->mwi_event_sub = NULL;
2704         }
2705
2706         if (peer->chanvars) {
2707                 ast_variables_destroy(peer->chanvars);
2708                 peer->chanvars = NULL;
2709         }
2710         if (peer->expire > -1)
2711                 ast_sched_del(sched, peer->expire);
2712
2713         if (peer->pokeexpire > -1)
2714                 ast_sched_del(sched, peer->pokeexpire);
2715         register_peer_exten(peer, FALSE);
2716         ast_free_ha(peer->ha);
2717         if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2718                 apeerobjs--;
2719         else if (ast_test_flag(&peer->flags[0], SIP_REALTIME)) {
2720                 rpeerobjs--;
2721                 ast_debug(3,"-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
2722         } else
2723                 speerobjs--;
2724         clear_realm_authentication(peer->auth);
2725         peer->auth = NULL;
2726         if (peer->dnsmgr)
2727                 ast_dnsmgr_release(peer->dnsmgr);
2728         ast_free(peer);
2729 }
2730
2731 /*! \brief Update peer data in database (if used) */
2732 static void update_peer(struct sip_peer *p, int expiry)
2733 {
2734         int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2735         if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2736             (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2737                 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2738         }
2739 }
2740
2741
2742 /*! \brief  realtime_peer: Get peer from realtime storage
2743  * Checks the "sippeers" realtime family from extconfig.conf 
2744  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
2745  * \todo Consider adding check of port address when matching here to follow the same
2746  *      algorithm as for static peers. Will we break anything by adding that?
2747 */
2748 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2749 {
2750         struct sip_peer *peer;
2751         struct ast_variable *var = NULL;
2752         struct ast_variable *varregs = NULL;
2753         struct ast_variable *tmp;
2754         char ipaddr[INET_ADDRSTRLEN];
2755         int realtimeregs = ast_check_realtime("sipregs");
2756
2757         /* First check on peer name */
2758         if (newpeername) {
2759                 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2760                 if (realtimeregs)
2761                         varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
2762         } else if (sin) {       /* Then check on IP address for dynamic peers */
2763                 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2764                 var = ast_load_realtime("sippeers", "host", ipaddr, NULL);      /* First check for fixed IP hosts */
2765                 if (var) {
2766                         if (realtimeregs) {
2767                                 tmp = var;
2768                                 while (tmp) {
2769                                         if (!newpeername && !strcasecmp(tmp->name, "name"))
2770                                                 newpeername = tmp->value;
2771                                         tmp = tmp->next;
2772                                 }
2773                                 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
2774                         }
2775                 } else {
2776                         if (realtimeregs)
2777                                 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, NULL); /* Then check for registered hosts */
2778                         else
2779                                 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, NULL); /* Then check for registered hosts */
2780                         if (varregs) {
2781                                 tmp = varregs;
2782                                 while (tmp) {
2783                                         if (!newpeername && !strcasecmp(tmp->name, "name"))
2784                                                 newpeername = tmp->value;
2785                                         tmp = tmp->next;
2786                                 }
2787                                 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2788                         }
2789                 }
2790         }
2791
2792         if (!var)
2793                 return NULL;
2794
2795         for (tmp = var; tmp; tmp = tmp->next) {
2796                 /* If this is type=user, then skip this object. */
2797                 if (!strcasecmp(tmp->name, "type") &&
2798                     !strcasecmp(tmp->value, "user")) {
2799                         ast_variables_destroy(var);
2800                         ast_variables_destroy(varregs);
2801                         return NULL;
2802                 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2803                         newpeername = tmp->value;
2804                 }
2805         }
2806         
2807         if (!newpeername) {     /* Did not find peer in realtime */
2808                 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
2809                 ast_variables_destroy(var);
2810                 return NULL;
2811         }
2812
2813
2814         /* Peer found in realtime, now build it in memory */
2815         peer = build_peer(newpeername, var, varregs, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2816         if (!peer) {
2817                 ast_variables_destroy(var);
2818                 ast_variables_destroy(varregs);
2819                 return NULL;
2820         }
2821
2822         ast_debug(3,"-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
2823
2824         if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2825                 /* Cache peer */
2826                 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2827                 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2828                         if (peer->expire > -1) {
2829                                 ast_sched_del(sched, peer->expire);
2830                         }
2831                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
2832                 }
2833                 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2834         } else {
2835                 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2836         }
2837         ast_variables_destroy(var);
2838         ast_variables_destroy(varregs);
2839
2840         return peer;
2841 }
2842
2843 /*! \brief Support routine for find_peer */
2844 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2845 {
2846         /* We know name is the first field, so we can cast */
2847         struct sip_peer *p = (struct sip_peer *) name;
2848         return  !(!inaddrcmp(&p->addr, sin) || 
2849                                         (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2850                                         (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2851 }
2852
2853 /*! \brief Locate peer by name or ip address 
2854  *      This is used on incoming SIP message to find matching peer on ip
2855         or outgoing message to find matching peer on name */
2856 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
2857 {
2858         struct sip_peer *p = NULL;
2859
2860         if (peer)
2861                 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2862         else
2863                 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2864
2865         if (!p && realtime)
2866                 p = realtime_peer(peer, sin);
2867
2868         return p;
2869 }
2870
2871 /*! \brief Remove user object from in-memory storage */
2872 static void sip_destroy_user(struct sip_user *user)
2873 {
2874         ast_debug(3, "Destroying user object from memory: %s\n", user->name);
2875         ast_free_ha(user->ha);
2876         if (user->chanvars) {
2877                 ast_variables_destroy(user->chanvars);
2878                 user->chanvars = NULL;
2879         }
2880         if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2881                 ruserobjs--;
2882         else
2883                 suserobjs--;
2884         ast_free(user);
2885 }
2886
2887 /*! \brief Load user from realtime storage
2888  * Loads user from "sipusers" category in realtime (extconfig.conf)
2889  * Users are matched on From: user name (the domain in skipped) */
2890 static struct sip_user *realtime_user(const char *username)
2891 {
2892         struct ast_variable *var;
2893         struct ast_variable *tmp;
2894         struct sip_user *user = NULL;
2895
2896         var = ast_load_realtime("sipusers", "name", username, NULL);
2897
2898         if (!var)
2899                 return NULL;
2900
2901         for (tmp = var; tmp; tmp = tmp->next) {
2902                 if (!strcasecmp(tmp->name, "type") &&
2903                         !strcasecmp(tmp->value, "peer")) {
2904                         ast_variables_destroy(var);
2905                         return NULL;
2906                 }
2907         }
2908
2909         user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2910         
2911         if (!user) {    /* No user found */
2912                 ast_variables_destroy(var);
2913                 return NULL;
2914         }
2915
2916         if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2917                 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2918                 suserobjs++;
2919                 ASTOBJ_CONTAINER_LINK(&userl,user);
2920         } else {
2921                 /* Move counter from s to r... */
2922                 suserobjs--;
2923                 ruserobjs++;
2924                 ast_set_flag(&user->flags[0], SIP_REALTIME);
2925         }
2926         ast_variables_destroy(var);
2927         return user;
2928 }
2929
2930 /*! \brief Locate user by name 
2931  * Locates user by name (From: sip uri user name part) first
2932  * from in-memory list (static configuration) then from 
2933  * realtime storage (defined in extconfig.conf) */
2934 static struct sip_user *find_user(const char *name, int realtime)
2935 {
2936         struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2937         if (!u && realtime)
2938                 u = realtime_user(name);
2939         return u;
2940 }
2941
2942 /*! \brief Set nat mode on the various data sockets */
2943 static void do_setnat(struct sip_pvt *p, int natflags)
2944 {
2945         const char *mode = natflags ? "On" : "Off";
2946
2947         if (p->rtp) {
2948                 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
2949                 ast_rtp_setnat(p->rtp, natflags);
2950         }
2951         if (p->vrtp) {
2952                 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
2953                 ast_rtp_setnat(p->vrtp, natflags);
2954         }
2955         if (p->udptl) {
2956                 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
2957                 ast_udptl_setnat(p->udptl, natflags);
2958         }
2959         if (p->trtp) {
2960                 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
2961                 ast_rtp_setnat(p->trtp, natflags);
2962         }
2963 }
2964
2965 /*! \brief Create address structure from peer reference.
2966  *  return -1 on error, 0 on success.
2967  */
2968 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
2969 {
2970         if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2971             (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
2972                 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2973                 dialog->recv = dialog->sa;
2974         } else 
2975                 return -1;
2976
2977         ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2978         ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2979         dialog->capability = peer->capability;
2980         if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
2981                 ast_rtp_destroy(dialog->vrtp);
2982                 dialog->vrtp = NULL;
2983         }
2984         if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
2985                 ast_rtp_destroy(dialog->trtp);
2986                 dialog->trtp = NULL;
2987         }
2988         dialog->prefs = peer->prefs;
2989         if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
2990                 dialog->t38.capability = global_t38_capability;
2991                 if (dialog->udptl) {
2992                         if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2993                                 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
2994                         else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2995                                 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2996                         else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2997                                 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
2998                         dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2999                         ast_debug(2,"Our T38 capability (%d)\n", dialog->t38.capability);
3000                 }
3001                 dialog->t38.jointcapability = dialog->t38.capability;
3002         } else if (dialog->udptl) {
3003                 ast_udptl_destroy(dialog->udptl);
3004                 dialog->udptl = NULL;
3005         }
3006         do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
3007
3008         if (dialog->rtp) {
3009                 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
3010                 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
3011                 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
3012                 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
3013                 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
3014                 /* Set Frame packetization */
3015                 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
3016                 dialog->autoframing = peer->autoframing;
3017         }
3018         if (dialog->vrtp) {
3019                 ast_rtp_setdtmf(dialog->vrtp, 0);
3020                 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
3021                 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
3022                 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
3023                 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
3024         }
3025         if (dialog->trtp) {
3026                 ast_rtp_setdtmf(dialog->trtp, 0);
3027                 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
3028                 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
3029                 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
3030                 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
3031         }
3032
3033         ast_string_field_set(dialog, peername, peer->name);
3034         ast_string_field_set(dialog, authname, peer->username);
3035         ast_string_field_set(dialog, username, peer->username);
3036         ast_string_field_set(dialog, peersecret, peer->secret);
3037         ast_string_field_set(dialog, peermd5secret, peer->md5secret);
3038         ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
3039         ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
3040         ast_string_field_set(dialog, tohost, peer->tohost);
3041         ast_string_field_set(dialog, fullcontact, peer->fullcontact);
3042         if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
3043                 char *tmpcall;
3044                 char *c;
3045                 tmpcall = ast_strdupa(dialog->callid);
3046                 c = strchr(tmpcall, '@');
3047                 if (c) {
3048                         *c = '\0';
3049                         ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
3050                 }
3051         }
3052         dialog->outboundproxy = obproxy_get(dialog, peer);
3053         if (ast_strlen_zero(dialog->tohost))
3054                 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
3055         if (!ast_strlen_zero(peer->fromdomain))
3056                 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
3057         if (!ast_strlen_zero(peer->fromuser))
3058                 ast_string_field_set(dialog, fromuser, peer->fromuser);
3059         if (!ast_strlen_zero(peer->language))
3060                 ast_string_field_set(dialog, language, peer->language);
3061         dialog->callgroup = peer->callgroup;
3062         dialog->pickupgroup = peer->pickupgroup;
3063         dialog->allowtransfer = peer->allowtransfer;
3064         /* Set timer T1 to RTT for this peer (if known by qualify=) */
3065         /* Minimum is settable or default to 100 ms */
3066         if (peer->maxms && peer->lastms)
3067                 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
3068         if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
3069             (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
3070                 dialog->noncodeccapability |= AST_RTP_DTMF;
3071         else
3072                 dialog->noncodeccapability &= ~AST_RTP_DTMF;
3073         dialog->jointnoncodeccapability = dialog->noncodeccapability;
3074         ast_string_field_set(dialog, context, peer->context);
3075         dialog->rtptimeout = peer->rtptimeout;
3076         if (peer->call_limit)
3077                 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
3078         dialog->maxcallbitrate = peer->maxcallbitrate;
3079         
3080         return 0;
3081 }
3082
3083 /*! \brief create address structure from peer name
3084  *      Or, if peer not found, find it in the global DNS 
3085  *      returns TRUE (-1) on failure, FALSE on success */
3086 static int create_addr(struct sip_pvt *dialog, const char *opeer)
3087 {
3088         struct hostent *hp;
3089         struct ast_hostent ahp;
3090         struct sip_peer *peer;
3091         char *port;
3092         int portno;
3093         char host[MAXHOSTNAMELEN], *hostn;
3094         char peername[256];
3095
3096         ast_copy_string(peername, opeer, sizeof(peername));
3097         port = strchr(peername, ':');
3098         if (port)
3099                 *port++ = '\0';
3100         dialog->sa.sin_family = AF_INET;
3101         dialog->timer_t1 = SIP_TIMER_T1; /* Default SIP retransmission timer T1 (RFC 3261) */
3102         peer = find_peer(peername, NULL, 1);
3103
3104         if (peer) {
3105                 int res = create_addr_from_peer(dialog, peer);
3106                 unref_peer(peer);
3107                 return res;
3108         }
3109
3110         ast_string_field_set(dialog, tohost, peername);
3111
3112         /* Get the outbound proxy information */
3113         dialog->outboundproxy = obproxy_get(dialog, NULL);
3114
3115         /* If we have an outbound proxy, don't bother with DNS resolution at all */
3116         if (dialog->outboundproxy)
3117                 return 0;
3118
3119         /* Let's see if we can find the host in DNS. First try DNS SRV records,
3120            then hostname lookup */
3121
3122         hostn = peername;
3123         portno = port ? atoi(port) : STANDARD_SIP_PORT;
3124         if (global_srvlookup) {
3125                 char service[MAXHOSTNAMELEN];
3126                 int tportno;
3127                 int ret;
3128
3129                 snprintf(service, sizeof(service), "_sip._udp.%s", peername);
3130                 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
3131                 if (ret > 0) {
3132                         hostn = host;
3133                         portno = tportno;
3134                 }
3135         }
3136         hp = ast_gethostbyname(hostn, &ahp);
3137         if (!hp) {
3138                 ast_log(LOG_WARNING, "No such host: %s\n", peername);
3139                 return -1;
3140         }
3141         memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
3142         dialog->sa.sin_port = htons(portno);
3143         dialog->recv = dialog->sa;
3144         return 0;
3145 }
3146
3147 /*! \brief Scheduled congestion on a call */
3148 static int auto_congest(void *nothing)
3149 {
3150         struct sip_pvt *p = nothing;
3151
3152         sip_pvt_lock(p);
3153         p->initid = -1;
3154         if (p->owner) {
3155                 /* XXX fails on possible deadlock */
3156                 if (!ast_channel_trylock(p->owner)) {
3157                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
3158                         append_history(p, "Cong", "Auto-congesting (timer)");
3159                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
3160                         ast_channel_unlock(p->owner);
3161                 }
3162         }
3163         sip_pvt_unlock(p);
3164         return 0;
3165 }
3166
3167
3168 /*! \brief Initiate SIP call from PBX 
3169  *      used from the dial() application      */
3170 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
3171 {
3172         int res;
3173         struct sip_pvt *p;
3174         struct varshead *headp;
3175         struct ast_var_t *current;
3176         const char *referer = NULL;   /* SIP referrer */        
3177
3178         p = ast->tech_pvt;
3179         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
3180                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
3181                 return -1;
3182         }
3183
3184         /* Check whether there is vxml_url, distinctive ring variables */
3185         headp=&ast->varshead;
3186         AST_LIST_TRAVERSE(headp,current,entries) {
3187                 /* Check whether there is a VXML_URL variable */
3188                 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
3189                         p->options->vxml_url = ast_var_value(current);
3190                 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
3191                         p->options->uri_options = ast_var_value(current);
3192                 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
3193                         /* Check whether there is a variable with a name starting with SIPADDHEADER */
3194                         p->options->addsipheaders = 1;
3195                 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
3196                         /* This is a transfered call */
3197                         p->options->transfer = 1;
3198                 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
3199                         /* This is the referrer */
3200                         referer = ast_var_value(current);
3201                 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
3202                         /* We're replacing a call. */
3203                         p->options->replaces = ast_var_value(current);
3204                 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
3205                         p->t38.state = T38_LOCAL_DIRECT;
3206                         ast_debug(1,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3207                 }
3208
3209         }
3210         
3211         res = 0;
3212         ast_set_flag(&p->flags[0], SIP_OUTGOING);
3213
3214         if (p->options->transfer) {
3215                 char buf[BUFSIZ/2];
3216
3217                 if (referer) {
3218                         if (sipdebug)
3219                                 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
3220                         snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
3221                 } else 
3222                         snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
3223                 ast_string_field_set(p, cid_name, buf);
3224         } 
3225         ast_debug(1, "Outgoing Call for %s\n", p->username);
3226
3227         res = update_call_counter(p, INC_CALL_RINGING);
3228
3229         if (res == -1)
3230                 return res;
3231
3232         p->callingpres = ast->cid.cid_pres;
3233         p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
3234         p->jointnoncodeccapability = p->noncodeccapability;
3235
3236         /* If there are no audio formats left to offer, punt */
3237         if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
3238                 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
3239                 res = -1;
3240         } else {
3241                 int xmitres;
3242
3243                 p->t38.jointcapability = p->t38.capability;
3244                 ast_debug(2,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
3245                 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
3246                 if (xmitres == XMIT_ERROR)
3247                         return -1;
3248                 p->invitestate = INV_CALLING;
3249         
3250                 /* Initialize auto-congest time */
3251                 p->initid = ast_sched_add(sched, SIP_TRANS_TIMEOUT, auto_congest, p);
3252         }
3253
3254         return res;
3255 }
3256
3257 /*! \brief Destroy registry object
3258         Objects created with the register= statement in static configuration */
3259 static void sip_registry_destroy(struct sip_registry *reg)
3260 {
3261         /* Really delete */
3262         ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
3263
3264         if (reg->call) {
3265                 /* Clear registry before destroying to ensure
3266                    we don't get reentered trying to grab the registry lock */
3267                 reg->call->registry = NULL;
3268                 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
3269                 sip_destroy(reg->call);
3270         }
3271         if (reg->expire > -1)
3272                 ast_sched_del(sched, reg->expire);
3273         if (reg->timeout > -1)
3274                 ast_sched_del(sched, reg->timeout);
3275         ast_string_field_free_pools(reg);
3276         regobjs--;
3277         ast_free(reg);
3278         
3279 }
3280
3281 /*! \brief Execute destruction of SIP dialog structure, release memory */
3282 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
3283 {
3284         struct sip_pvt *cur, *prev = NULL;
3285         struct sip_pkt *cp;
3286
3287         if (sip_debug_test_pvt(p))
3288                 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3289
3290         if (ast_test_flag(&p->flags[0], SIP_INC_COUNT)) {
3291                 update_call_counter(p, DEC_CALL_LIMIT);
3292                 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
3293         }
3294
3295         /* Remove link from peer to subscription of MWI */
3296         if (p->relatedpeer && p->relatedpeer->mwipvt) 
3297                 p->relatedpeer->mwipvt = NULL;
3298
3299         if (dumphistory)
3300                 sip_dump_history(p);
3301
3302         if (p->options)
3303                 ast_free(p->options);
3304
3305         if (p->stateid > -1)
3306                 ast_extension_state_del(p->stateid, NULL);
3307         if (p->initid > -1)
3308                 ast_sched_del(sched, p->initid);
3309         if (p->autokillid > -1)
3310                 ast_sched_del(sched, p->autokillid);
3311
3312         if (p->rtp)
3313                 ast_rtp_destroy(p->rtp);
3314         if (p->vrtp)
3315                 ast_rtp_destroy(p->vrtp);
3316         if (p->trtp)
3317                 ast_rtp_destroy(p->trtp);
3318         if (p->udptl)
3319                 ast_udptl_destroy(p->udptl);
3320         if (p->refer)
3321                 ast_free(p->refer);
3322         if (p->route) {
3323                 free_old_route(p->route);
3324                 p->route = NULL;
3325         }
3326         if (p->registry) {
3327                 if (p->registry->call == p)
3328                         p->registry->call = NULL;
3329                 registry_unref(p->registry);
3330         }
3331
3332         /* Unlink us from the owner if we have one */
3333         if (p->owner) {
3334                 if (lockowner)
3335                         ast_channel_lock(p->owner);
3336                 ast_debug(1, "Detaching from %s\n", p->owner->name);
3337                 p->owner->tech_pvt = NULL;
3338                 if (lockowner)
3339                         ast_channel_unlock(p->owner);
3340         }
3341         /* Clear history */
3342         if (p->history) {
3343                 struct sip_history *hist;
3344                 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
3345                         ast_free(hist);
3346                 ast_free(p->history);
3347                 p->history = NULL;
3348         }
3349
3350         /* Lock dialog list before removing ourselves from the list */
3351         if (lockdialoglist)
3352                 dialoglist_lock();
3353         for (prev = NULL, cur = dialoglist; cur; prev = cur, cur = cur->next) {
3354                 if (cur == p) {
3355                         UNLINK(cur, dialoglist, prev);
3356                         break;
3357                 }
3358         }
3359         if (lockdialoglist)
3360                 dialoglist_unlock();
3361         if (!cur) {
3362                 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
3363                 return;
3364         } 
3365
3366         /* remove all current packets in this dialog */
3367         while((cp = p->packets)) {
3368                 p->packets = p->packets->next;
3369                 if (cp->retransid > -1)
3370                         ast_sched_del(sched, cp->retransid);
3371                 ast_free(cp);
3372         }
3373         if (p->chanvars) {
3374                 ast_variables_destroy(p->chanvars);
3375                 p->chanvars = NULL;
3376         }
3377         ast_mutex_destroy(&p->pvt_lock);
3378
3379         ast_string_field_free_pools(p);
3380
3381         ast_free(p);
3382 }
3383
3384 /*! \brief  update_call_counter: Handle call_limit for SIP users 
3385  * Setting a call-limit will cause calls above the limit not to be accepted.
3386  *
3387  * Remember that for a type=friend, there's one limit for the user and
3388  * another for the peer, not a combined call limit.
3389  * This will cause unexpected behaviour in subscriptions, since a "friend"
3390  * is *two* devices in Asterisk, not one.
3391  *
3392  * Thought: For realtime, we should probably update storage with inuse counter... 
3393  *
3394  * \return 0 if call is ok (no call limit, below threshold)
3395  *      -1 on rejection of call
3396  *              
3397  */
3398 static int update_call_counter(struct sip_pvt *fup, int event)
3399 {
3400         char name[256];
3401         int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
3402         int outgoing = ast_test_flag(&fup->flags[1], SIP_PAGE2_OUTGOING_CALL);
3403         struct sip_user *u = NULL;
3404         struct sip_peer *p = NULL;
3405
3406         ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
3407
3408         /* Test if we need to check call limits, in order to avoid 
3409            realtime lookups if we do not need it */
3410         if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
3411                 return 0;
3412
3413         ast_copy_string(name, fup->username, sizeof(name));
3414
3415         /* Check the list of users only for incoming calls */
3416         if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1)))  {
3417                 inuse = &u->inUse;
3418                 call_limit = &u->call_limit;
3419                 inringing = NULL;
3420         } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1) ) ) { /* Try to find peer */
3421                 inuse = &p->inUse;
3422                 call_limit = &p->call_limit;
3423                 inringing = &p->inRinging;
3424                 ast_copy_string(name, fup->peername, sizeof(name));
3425         } 
3426         if (!p && !u) {
3427                 ast_debug(2, "%s is not a local device, no call limit\n", name);
3428                 return 0;
3429         }
3430
3431         switch(event) {
3432         /* incoming and outgoing affects the inUse counter */
3433         case DEC_CALL_LIMIT:
3434                 /* Decrement inuse count if applicable */
3435                 if (inuse && ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
3436                         ast_atomic_fetchadd_int(inuse, -1);
3437                         ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
3438                 } else
3439                         *inuse = 0;
3440                 /* Decrement ringing count if applicable */
3441                 if (inringing && ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3442                         ast_atomic_fetchadd_int(inringing, -1);
3443                         ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3444                 }
3445                 /* Decrement onhold count if applicable */
3446                 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold)
3447                         sip_peer_hold(fup, FALSE);
3448                 if (sipdebug)
3449                         ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
3450                 break;
3451
3452         case INC_CALL_RINGING:
3453         case INC_CALL_LIMIT:
3454                 /* If call limit is active and we have reached the limit, reject the call */
3455                 if (*call_limit > 0 ) {
3456                         if (*inuse >= *call_limit) {
3457                                 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);
3458                                 if (u)
3459                                         unref_user(u);
3460                                 else
3461                                         unref_peer(p);
3462                                 return -1; 
3463                         }
3464                 }
3465                 if (inringing && (event == INC_CALL_RINGING)) {
3466                         if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3467                                 ast_atomic_fetchadd_int(inringing, +1);
3468                                 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3469                         }
3470                 }
3471                 /* Continue */
3472                 ast_atomic_fetchadd_int(inuse, +1);
3473                 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
3474                 if (sipdebug) {
3475                         ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
3476                 }
3477                 break;
3478
3479         case DEC_CALL_RINGING:
3480                 if (inringing && ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3481                         ast_atomic_fetchadd_int(inringing, -1);
3482                         ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3483                 }
3484                 break;
3485
3486         default:
3487                 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
3488         }
3489         if (p) {
3490                 ast_device_state_changed("SIP/%s", p->name);
3491                 unref_peer(p);
3492         } else /* u must be set */
3493                 unref_user(u);