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