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