Thu Apr 28 2011 16:57:00

Asterisk developer's documentation


chan_sip.c File Reference

Implementation of Session Initiation Protocol. More...

#include "asterisk.h"
#include <ctype.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/signal.h>
#include <regex.h>
#include <time.h>
#include "asterisk/network.h"
#include "asterisk/paths.h"
#include "asterisk/lock.h"
#include "asterisk/channel.h"
#include "asterisk/config.h"
#include "asterisk/module.h"
#include "asterisk/pbx.h"
#include "asterisk/sched.h"
#include "asterisk/io.h"
#include "asterisk/rtp.h"
#include "asterisk/udptl.h"
#include "asterisk/acl.h"
#include "asterisk/manager.h"
#include "asterisk/callerid.h"
#include "asterisk/cli.h"
#include "asterisk/app.h"
#include "asterisk/musiconhold.h"
#include "asterisk/dsp.h"
#include "asterisk/features.h"
#include "asterisk/srv.h"
#include "asterisk/astdb.h"
#include "asterisk/causes.h"
#include "asterisk/utils.h"
#include "asterisk/file.h"
#include "asterisk/astobj.h"
#include "asterisk/astobj2.h"
#include "asterisk/dnsmgr.h"
#include "asterisk/devicestate.h"
#include "asterisk/linkedlists.h"
#include "asterisk/stringfields.h"
#include "asterisk/monitor.h"
#include "asterisk/netsock.h"
#include "asterisk/localtime.h"
#include "asterisk/abstract_jb.h"
#include "asterisk/threadstorage.h"
#include "asterisk/translate.h"
#include "asterisk/ast_version.h"
#include "asterisk/event.h"
#include "asterisk/tcptls.h"
#include "asterisk/strings.h"
Include dependency graph for chan_sip.c:

Go to the source code of this file.

Data Structures

struct  __show_chan_arg
 argument for the 'show channels|subscriptions' callback. More...
struct  _map_x_s
 generic struct to map between strings and integers. Fill it with x-s pairs, terminate with an entry with s = NULL; Then you can call map_x_s(...) to map an integer to a string, and map_s_x() for the string -> integer mapping. More...
struct  ast_register_list
 The register list: Other SIP proxies we register with and place calls to. More...
struct  ast_subscription_mwi_list
 The MWI subscription list. More...
struct  cfsip_methods
 The core structure to setup dialogs. We parse incoming messages by using structure and then route the messages according to the type. More...
struct  cfsip_options
 List of well-known SIP options. If we get this in a require, we should check the list and answer accordingly. More...
struct  cfsubscription_types
 Subscription types that we support. We support

  • dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
  • SIMPLE presence used for device status
  • Voicemail notification subscriptions.
More...
struct  domain
 Domain data structure. More...
struct  domain_list
struct  find_call_cb_arg
 argument to the helper function to identify a call More...
struct  invstate2stringtable
 Readable descriptions of device states. More...
struct  offered_media
struct  sip_pvt::request_queue
struct  sip_auth
 sip_auth: Credentials for authentication to other SIP services More...
struct  sip_dual
 structure used in transfers More...
struct  sip_history
 sip_history: Structure for saving transactions within a SIP dialog More...
struct  sip_history_head
struct  sip_invite_param
 Parameters to the transmit_invite function. More...
struct  sip_mailbox
 A peer's mailbox. More...
struct  sip_peer
 Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) More...
struct  sip_pkt
 sip packet - raw format for outbound packets that are sent or scheduled for transmission Packets are linked in a list, whose head is in the struct sip_pvt they belong to. Each packet holds a reference to the parent struct sip_pvt. This structure is allocated in __sip_reliable_xmit() and only for packets that require retransmissions. More...
struct  sip_proxy
 definition of a sip proxy server More...
struct  sip_pvt
 Structure used for each SIP dialog, ie. a call, a registration, a subscribe. Created and initialized by sip_alloc(), the descriptor goes into the list of descriptors (dialoglist). More...
struct  sip_refer
 Structure to handle SIP transfers. Dynamically allocated when needed. More...
struct  sip_registry
 Registrations with other SIP proxies. More...
struct  sip_request
 sip_request: The data grabbed from the UDP socket More...
struct  sip_route
 Structure to save routing information for a SIP session. More...
struct  sip_settings
 a place to store all global settings for the sip channel driver These are settings that will be possibly to apply on a group level later on. More...
struct  sip_socket
 The SIP socket definition. More...
struct  sip_st_cfg
 Structure that encapsulates all attributes related to configuration of SIP Session-Timers feature on a per user/peer basis. More...
struct  sip_st_dlg
 Structure that encapsulates all attributes related to running SIP Session-Timers feature on a per dialog basis. More...
struct  sip_subscription_mwi
 Definition of an MWI subscription to another server. More...
struct  sip_threadinfo
 Definition of a thread that handles a socket. More...
struct  sip_via
 Structure to store Via information. More...
struct  t38properties
 T.38 channel settings (at some point we need to make this alloc'ed. More...
struct  tcptls_packet

Defines

#define ALLOWED_METHODS   "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"
 SIP Methods we support.
#define append_history(p, event, fmt, args...)   append_history_full(p, "%-15s " fmt, event, ## args)
 Append to SIP dialog history.
#define CALLERID_UNKNOWN   "Anonymous"
#define CHECK_AUTH_BUF_INITLEN   256
#define check_request_transport(peer, tmpl)
 generic function for determining if a correct transport is being used to contact a peer
#define DEFAULT_AUTHLIMIT   100
#define DEFAULT_AUTHTIMEOUT   30
#define DEFAULT_DEFAULT_EXPIRY   120
#define DEFAULT_EXPIRY   900
#define DEFAULT_FREQ_NOTOK   10 * 1000
#define DEFAULT_MAX_EXPIRY   3600
#define DEFAULT_MAX_FORWARDS   "70"
#define DEFAULT_MAX_SE   1800
#define DEFAULT_MAXMS   2000
#define DEFAULT_MIN_EXPIRY   60
#define DEFAULT_MIN_SE   90
#define DEFAULT_MWI_EXPIRY   3600
#define DEFAULT_QUALIFY_GAP   100
#define DEFAULT_QUALIFY_PEERS   1
#define DEFAULT_QUALIFYFREQ   60 * 1000
#define DEFAULT_REGISTRATION_TIMEOUT   20
#define DEFAULT_RETRANS   1000
#define DEFAULT_TIMER_T1   500
#define DEFAULT_TRANS_TIMEOUT   -1
#define EXPIRY_GUARD_LIMIT   30
#define EXPIRY_GUARD_MIN   500
#define EXPIRY_GUARD_PCT   0.20
#define EXPIRY_GUARD_SECS   15
#define FALSE   0
#define FINDALLDEVICES   (FINDUSERS | FINDPEERS)
#define FINDPEERS   (1 << 1)
#define FINDUSERS   (1 << 0)
#define FORMAT   "%-25.25s %-15.15s %-15.15s \n"
#define FORMAT   "%-30.30s %-6d %-9.9s %-6.6s\n"
#define FORMAT   "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
#define FORMAT   "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
#define FORMAT   "%-40.40s %-20.20s %-16.16s\n"
#define FORMAT   "%-30.30s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
#define FORMAT   "%-15.15s %-11.11s %-8.8s %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.6u %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.6u\n"
#define FORMAT   "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
#define FORMAT   "%-30.30s %-12.12s %-10.10s %-10.10s\n"
#define FORMAT2   "%-25.25s %-15.15s %-15.15s \n"
#define FORMAT2   "%-30.30s %3.6s %9.9s %6.6s\n"
#define FORMAT2   "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-6.6s\n"
#define FORMAT2   "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
#define FORMAT2   "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
#define FORMAT2   "%-30.30s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
#define FORMAT3   "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
#define FORMAT4   "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
#define FROMDOMAIN_INVALID   "anonymous.invalid"
#define INITIAL_CSEQ   101
#define IS_SIP_TECH(t)   ((t) == &sip_tech || (t) == &sip_tech_info)
#define MAX_AUTHTRIES   3
#define MAX_HISTORY_ENTRIES   50
#define MAX_RETRANS   6
#define NO_RTP   0
#define NOT_SUPPORTED   0
#define PROVIS_KEEPALIVE_TIMEOUT   60000
#define RTP   1
#define SDP_MAX_RTPMAP_CODECS   32
#define SIP_MAX_HEADERS   64
#define SIP_MAX_LINES   256
#define SIP_MIN_PACKET   4096
#define SIP_OPT_100REL   (1 << 1)
#define SIP_OPT_EARLY_SESSION   (1 << 3)
#define SIP_OPT_EVENTLIST   (1 << 11)
#define SIP_OPT_FROMCHANGE   (1 << 17)
#define SIP_OPT_GRUU   (1 << 12)
#define SIP_OPT_HISTINFO   (1 << 15)
#define SIP_OPT_JOIN   (1 << 4)
#define SIP_OPT_NOREFERSUB   (1 << 14)
#define SIP_OPT_OUTBOUND   (1 << 20)
#define SIP_OPT_PATH   (1 << 5)
#define SIP_OPT_PRECONDITION   (1 << 7)
#define SIP_OPT_PREF   (1 << 6)
#define SIP_OPT_PRIVACY   (1 << 8)
#define SIP_OPT_RECLISTINV   (1 << 18)
#define SIP_OPT_RECLISTSUB   (1 << 19)
#define SIP_OPT_REPLACES   (1 << 0)
#define SIP_OPT_RESPRIORITY   (1 << 16)
#define SIP_OPT_SDP_ANAT   (1 << 9)
#define SIP_OPT_SEC_AGREE   (1 << 10)
#define SIP_OPT_TARGET_DIALOG   (1 << 13)
#define SIP_OPT_TIMER   (1 << 2)
#define SIP_OPT_UNKNOWN   (1 << 21)
#define sip_pvt_lock(x)   ao2_lock(x)
#define sip_pvt_trylock(x)   ao2_trylock(x)
#define sip_pvt_unlock(x)   ao2_unlock(x)
#define SIP_RESERVED   ";/?:@&=+$,# "
#define SIP_TRANS_TIMEOUT   64 * DEFAULT_TIMER_T1
#define SIPBUFSIZE   512
#define STANDARD_SIP_PORT   5060
 Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS.
#define STANDARD_TLS_PORT   5061
 Standard SIP TLS port from RFC 3261. DO NOT CHANGE THIS.
#define SUPPORTED   1
#define TRUE   1
#define UNLINK(element, head, prev)
#define XMIT_ERROR   -2
DefaultValues Default values, set and reset in reload_config before reading configuration
Note:
in many SIP headers, absence of a port number implies port 5060, and this is why we cannot change the above constant. There is a limited number of places in asterisk where we could, in principle, use a different "default" port number, but we do not support this feature at the moment. You can run Asterisk with SIP on a different port with a configuration option. If you change this value, the signalling will be incorrect.

These are default values in the source. There are other recommended values in the sip.conf.sample for new installations. These may differ to keep backwards compatibility, yet encouraging new behaviour on new installations

#define DEFAULT_CONTEXT   "default"
#define DEFAULT_MOHINTERPRET   "default"
#define DEFAULT_MOHSUGGEST   ""
#define DEFAULT_VMEXTEN   "asterisk"
#define DEFAULT_CALLERID   "asterisk"
#define DEFAULT_NOTIFYMIME   "application/simple-message-summary"
#define DEFAULT_ALLOWGUEST   TRUE
#define DEFAULT_RTPKEEPALIVE   0
#define DEFAULT_CALLCOUNTER   FALSE
#define DEFAULT_SRVLOOKUP   TRUE
#define DEFAULT_COMPACTHEADERS   FALSE
#define DEFAULT_TOS_SIP   0
#define DEFAULT_TOS_AUDIO   0
#define DEFAULT_TOS_VIDEO   0
#define DEFAULT_TOS_TEXT   0
#define DEFAULT_COS_SIP   4
#define DEFAULT_COS_AUDIO   5
#define DEFAULT_COS_VIDEO   6
#define DEFAULT_COS_TEXT   5
#define DEFAULT_ALLOW_EXT_DOM   TRUE
#define DEFAULT_REALM   "asterisk"
#define DEFAULT_NOTIFYRINGING   TRUE
#define DEFAULT_NOTIFYCID   DISABLED
#define DEFAULT_PEDANTIC   FALSE
#define DEFAULT_AUTOCREATEPEER   FALSE
#define DEFAULT_MATCHEXTERNIPLOCALLY   FALSE
#define DEFAULT_QUALIFY   FALSE
#define DEFAULT_CALLEVENTS   FALSE
#define DEFAULT_ALWAYSAUTHREJECT   FALSE
#define DEFAULT_REGEXTENONQUALIFY   FALSE
#define DEFAULT_T1MIN   100
#define DEFAULT_MAX_CALL_BITRATE   (384)
#define DEFAULT_USERAGENT   "Asterisk PBX"
#define DEFAULT_SDPSESSION   "Asterisk PBX"
#define DEFAULT_SDPOWNER   "root"
SIPflags

Various flags for the flags field in the pvt structure Trying to sort these up (one or more of the following): D: Dialog P: Peer/user G: Global flag When flags are used by multiple structures, it is important that they have a common layout so it is easy to copy them.

#define SIP_OUTGOING   (1 << 0)
#define SIP_RINGING   (1 << 2)
#define SIP_PROGRESS_SENT   (1 << 3)
#define SIP_NEEDREINVITE   (1 << 4)
#define SIP_PENDINGBYE   (1 << 5)
#define SIP_GOTREFER   (1 << 6)
#define SIP_CALL_LIMIT   (1 << 7)
#define SIP_INC_COUNT   (1 << 8)
#define SIP_INC_RINGING   (1 << 9)
#define SIP_DEFER_BYE_ON_TRANSFER   (1 << 10)
#define SIP_PROMISCREDIR   (1 << 11)
#define SIP_TRUSTRPID   (1 << 12)
#define SIP_USEREQPHONE   (1 << 13)
#define SIP_USECLIENTCODE   (1 << 14)
#define SIP_DTMF   (7 << 15)
#define SIP_DTMF_RFC2833   (0 << 15)
#define SIP_DTMF_INBAND   (1 << 15)
#define SIP_DTMF_INFO   (2 << 15)
#define SIP_DTMF_AUTO   (3 << 15)
#define SIP_DTMF_SHORTINFO   (4 << 15)
#define SIP_NAT   (3 << 18)
#define SIP_NAT_NEVER   (0 << 18)
#define SIP_NAT_RFC3581   (1 << 18)
#define SIP_NAT_ROUTE   (2 << 18)
#define SIP_NAT_ALWAYS   (3 << 18)
#define SIP_REINVITE   (7 << 20)
#define SIP_REINVITE_NONE   (0 << 20)
#define SIP_DIRECT_MEDIA   (1 << 20)
#define SIP_DIRECT_MEDIA_NAT   (2 << 20)
#define SIP_REINVITE_UPDATE   (4 << 20)
#define SIP_INSECURE   (3 << 23)
#define SIP_INSECURE_NONE   (0 << 23)
#define SIP_INSECURE_PORT   (1 << 23)
#define SIP_INSECURE_INVITE   (1 << 24)
#define SIP_PROG_INBAND   (3 << 25)
#define SIP_PROG_INBAND_NEVER   (0 << 25)
#define SIP_PROG_INBAND_NO   (1 << 25)
#define SIP_PROG_INBAND_YES   (2 << 25)
#define SIP_SENDRPID   (1 << 29)
#define SIP_G726_NONSTANDARD   (1 << 31)
#define SIP_FLAGS_TO_COPY
 Flags to copy from peer/user to dialog.
SIPflags2

a second page of flags (for flags[1]

#define SIP_PAGE2_RTCACHEFRIENDS   (1 << 0)
#define SIP_PAGE2_RTAUTOCLEAR   (1 << 2)
#define SIP_PAGE2_HAVEPEERCONTEXT   (1 << 3)
#define SIP_PAGE2_FORWARD_LOOP_DETECTED   (1 << 8)
#define SIP_PAGE2_STATECHANGEQUEUE   (1 << 9)
#define SIP_PAGE2_RPORT_PRESENT   (1 << 10)
#define SIP_PAGE2_VIDEOSUPPORT   (1 << 14)
#define SIP_PAGE2_TEXTSUPPORT   (1 << 15)
#define SIP_PAGE2_ALLOWSUBSCRIBE   (1 << 16)
#define SIP_PAGE2_ALLOWOVERLAP   (1 << 17)
#define SIP_PAGE2_SUBSCRIBEMWIONLY   (1 << 18)
#define SIP_PAGE2_IGNORESDPVERSION   (1 << 19)
#define SIP_PAGE2_T38SUPPORT   (3 << 20)
#define SIP_PAGE2_T38SUPPORT_UDPTL   (1 << 20)
#define SIP_PAGE2_T38SUPPORT_UDPTL_FEC   (2 << 20)
#define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY   (3 << 20)
#define SIP_PAGE2_CALL_ONHOLD   (3 << 23)
#define SIP_PAGE2_CALL_ONHOLD_ACTIVE   (1 << 23)
#define SIP_PAGE2_CALL_ONHOLD_ONEDIR   (2 << 23)
#define SIP_PAGE2_CALL_ONHOLD_INACTIVE   (3 << 23)
#define SIP_PAGE2_RFC2833_COMPENSATE   (1 << 25)
#define SIP_PAGE2_BUGGY_MWI   (1 << 26)
#define SIP_PAGE2_DIALOG_ESTABLISHED   (1 << 27)
#define SIP_PAGE2_FAX_DETECT   (3 << 28)
#define SIP_PAGE2_FAX_DETECT_CNG   (1 << 28)
#define SIP_PAGE2_FAX_DETECT_T38   (2 << 28)
#define SIP_PAGE2_FAX_DETECT_BOTH   (3 << 28)
#define SIP_PAGE2_REGISTERTRYING   (1 << 29)
#define SIP_PAGE2_UDPTL_DESTINATION   (1 << 30)
#define SIP_PAGE2_VIDEOSUPPORT_ALWAYS   (1 << 31)
#define SIP_PAGE2_FLAGS_TO_COPY

Enumerations

enum  can_create_dialog { CAN_NOT_CREATE_DIALOG, CAN_CREATE_DIALOG, CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
 

States whether a SIP message can create a dialog in Asterisk.

More...
enum  check_auth_result {
  AUTH_DONT_KNOW = -100, AUTH_SUCCESSFUL = 0, AUTH_CHALLENGE_SENT = 1, AUTH_SECRET_FAILED = -1,
  AUTH_USERNAME_MISMATCH = -2, AUTH_NOT_FOUND = -3, AUTH_FAKE_AUTH = -4, AUTH_UNKNOWN_DOMAIN = -5,
  AUTH_PEER_NOT_DYNAMIC = -6, AUTH_ACL_FAILED = -7, AUTH_BAD_TRANSPORT = -8
}
 

Authentication result from check_auth* functions.

More...
enum  invitestates {
  INV_NONE = 0, INV_CALLING = 1, INV_PROCEEDING = 2, INV_EARLY_MEDIA = 3,
  INV_COMPLETED = 4, INV_CONFIRMED = 5, INV_TERMINATED = 6, INV_CANCELLED = 7
}
 

States for the INVITE transaction, not the dialog.

More...
enum  media_type { SDP_AUDIO, SDP_VIDEO, SDP_IMAGE, SDP_TEXT }
enum  notifycid_setting { DISABLED = 0, ENABLED = 1, IGNORE_CONTEXT = 2 }
 

Settings for the 'notifycid' option, see sip.conf.sample for details.

More...
enum  parse_register_result { PARSE_REGISTER_DENIED, PARSE_REGISTER_FAILED, PARSE_REGISTER_UPDATE, PARSE_REGISTER_QUERY }
 

Results from the parse_register() function.

More...
enum  referstatus {
  REFER_IDLE, REFER_SENT, REFER_RECEIVED, REFER_CONFIRMED,
  REFER_ACCEPTED, REFER_RINGING, REFER_200OK, REFER_FAILED,
  REFER_NOAUTH
}
 

Parameters to know status of transfer.

More...
enum  sip_auth_type { PROXY_AUTH = 407, WWW_AUTH = 401 }
 

Authentication types - proxy or www authentication.

More...
enum  sip_debug_e { sip_debug_none = 0, sip_debug_config = 1, sip_debug_console = 2 }
 

debugging state We store separately the debugging requests from the config file and requests from the CLI. Debugging is enabled if either is set (which means that if sipdebug is set in the config file, we can only turn it off by reloading the config).

More...
enum  sip_peer_type { SIP_TYPE_PEER = (1 << 0), SIP_TYPE_USER = (1 << 1) }
enum  sip_result { AST_SUCCESS = 0, AST_FAILURE = -1 }
 

The result of a lot of functions.

More...
enum  sip_tcptls_alert { TCPTLS_ALERT_DATA, TCPTLS_ALERT_STOP }
enum  sip_transport { SIP_TRANSPORT_UDP = 1, SIP_TRANSPORT_TCP = 1 << 1, SIP_TRANSPORT_TLS = 1 << 2 }
 

Define some implemented SIP transports.

More...
enum  sipmethod {
  SIP_UNKNOWN, SIP_RESPONSE, SIP_REGISTER, SIP_OPTIONS,
  SIP_NOTIFY, SIP_INVITE, SIP_ACK, SIP_PRACK,
  SIP_BYE, SIP_REFER, SIP_SUBSCRIBE, SIP_MESSAGE,
  SIP_UPDATE, SIP_INFO, SIP_CANCEL, SIP_PUBLISH,
  SIP_PING
}
 

SIP Request methods known by Asterisk.

More...
enum  sipregistrystate {
  REG_STATE_UNREGISTERED = 0, REG_STATE_REGSENT, REG_STATE_AUTHSENT, REG_STATE_REGISTERED,
  REG_STATE_REJECTED, REG_STATE_TIMEOUT, REG_STATE_NOAUTH, REG_STATE_FAILED
}
 

States for outbound registrations (with register= lines in sip.conf.

More...
enum  st_mode { SESSION_TIMER_MODE_INVALID = 0, SESSION_TIMER_MODE_ACCEPT, SESSION_TIMER_MODE_ORIGINATE, SESSION_TIMER_MODE_REFUSE }
 

Modes in which Asterisk can be configured to run SIP Session-Timers.

More...
enum  st_refresher { SESSION_TIMER_REFRESHER_AUTO, SESSION_TIMER_REFRESHER_UAC, SESSION_TIMER_REFRESHER_UAS }
 

The entity playing the refresher role for Session-Timers.

More...
enum  subscriptiontype {
  NONE = 0, XPIDF_XML, DIALOG_INFO_XML, CPIM_PIDF_XML,
  PIDF_XML, MWI_NOTIFICATION
}
 

Type of subscription, based on the packages we do support, see subscription_types.

More...
enum  t38_action_flag { SDP_T38_NONE = 0, SDP_T38_INITIATE, SDP_T38_ACCEPT }
enum  t38state { T38_DISABLED = 0, T38_LOCAL_REINVITE, T38_PEER_REINVITE, T38_ENABLED }
 

T38 States for a call.

More...
enum  transfermodes { TRANSFER_OPENFORALL, TRANSFER_CLOSED }
 

Authorization scheme for call transfers.

More...
enum  xmittype { XMIT_CRITICAL = 2, XMIT_RELIABLE = 1, XMIT_UNRELIABLE = 0 }
 

When sending a SIP message, we can send with a few options, depending on type of SIP request. UNRELIABLE is moslty used for responses to repeated requests, where the original response would be sent RELIABLE in an INVITE transaction.

More...

Functions

static const char * __get_header (const struct sip_request *req, const char *name, int *start)
static void __reg_module (void)
static int __set_address_from_contact (const char *fullcontact, struct sockaddr_in *sin, int tcp)
static int __sip_ack (struct sip_pvt *p, int seqno, int resp, int sipmethod)
 Acknowledges receipt of a packet and stops retransmission called with p locked.
static int __sip_autodestruct (const void *data)
 Kill a SIP dialog (called only by the scheduler) The scheduler has a reference to this dialog when p->autokillid != -1, and we are called using that reference. So if the event is not rescheduled, we need to call dialog_unref().
static void __sip_destroy (struct sip_pvt *p, int lockowner, int lockdialoglist)
 Execute destruction of SIP dialog structure, release memory.
static int __sip_do_register (struct sip_registry *r)
 Register with SIP proxy.
static void __sip_pretend_ack (struct sip_pvt *p)
 Pretend to ack all packets called with p locked.
static int __sip_reliable_xmit (struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
 Transmit packet with retransmits.
static int __sip_semi_ack (struct sip_pvt *p, int seqno, int resp, int sipmethod)
 Acks receipt of packet, keep it around (used for provisional responses)
static int __sip_subscribe_mwi_do (struct sip_subscription_mwi *mwi)
 Actually setup an MWI subscription or resubscribe.
static int __sip_xmit (struct sip_pvt *p, struct ast_str *data, int len)
 Transmit SIP message Sends a SIP request or response on a given socket (in the pvt) Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit.
static int __transmit_response (struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
 Base transmit response function.
static void __unreg_module (void)
static char * _sip_qualify_peer (int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
 Send qualify message to peer from cli or manager. Mostly for debugging.
static char * _sip_show_peer (int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
 Show one peer in detail (main function)
static char * _sip_show_peers (int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
 Execute sip show peers command.
static void * _sip_tcp_helper_thread (struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
 SIP TCP thread management function This function reads from the socket, parses the packet into a request.
static int acf_channel_read (struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
static void add_blank (struct sip_request *req)
 add a blank line if no body
static void add_codec_to_sdp (const struct sip_pvt *p, int codec, struct ast_str **m_buf, struct ast_str **a_buf, int debug, int *min_packet_size)
 Add codec offer to SDP offer/answer body in INVITE or 200 OK.
static int add_content (struct sip_request *req, const char *line)
 Add content (not header) to SIP message.
static int add_digit (struct sip_request *req, char digit, unsigned int duration, int mode)
 Add DTMF INFO tone to sip message Mode = 0 for application/dtmf-relay (Cisco) 1 for application/dtmf.
static int add_header (struct sip_request *req, const char *var, const char *value)
 Add header to SIP message.
static void add_noncodec_to_sdp (const struct sip_pvt *p, int format, struct ast_str **m_buf, struct ast_str **a_buf, int debug)
 Add RFC 2833 DTMF offer to SDP.
static void add_peer_mailboxes (struct sip_peer *peer, const char *value)
static void add_peer_mwi_subs (struct sip_peer *peer)
static struct sip_authadd_realm_authentication (struct sip_auth *authlist, const char *configuration, int lineno)
 Add realm authentication in list.
static void add_route (struct sip_request *req, struct sip_route *route)
 Add route header into request per learned route.
static enum sip_result add_sdp (struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
 Add Session Description Protocol message.
static int add_sip_domain (const char *domain, const enum domain_mode mode, const char *context)
 Add SIP domain to list of domains we are responsible for.
static int add_supported_header (struct sip_pvt *pvt, struct sip_request *req)
 Add "Supported" header to sip message. Since some options may be disabled in the config, the sip_pvt must be inspected to determine what is supported for this dialog.
static void add_tcodec_to_sdp (const struct sip_pvt *p, int codec, struct ast_str **m_buf, struct ast_str **a_buf, int debug, int *min_packet_size)
 Add text codec offer to SDP offer/answer body in INVITE or 200 OK.
static int add_text (struct sip_request *req, const char *text)
 Add text body to SIP message.
static struct ast_variableadd_var (const char *buf, struct ast_variable *list)
 implement the setvar config line
static void add_vcodec_to_sdp (const struct sip_pvt *p, int codec, struct ast_str **m_buf, struct ast_str **a_buf, int debug, int *min_packet_size)
 Add video codec offer to SDP offer/answer body in INVITE or 200 OK.
static int add_vidupdate (struct sip_request *req)
 add XML encoded media control with update
static int addr_is_multicast (struct in_addr *addr)
 Check if an ip is an multicast IP. addr the address to check.
static void append_date (struct sip_request *req)
 Append date to SIP message.
static void append_history_full (struct sip_pvt *p, const char *fmt,...)
 Append to SIP dialog history with arg list.
static void append_history_va (struct sip_pvt *p, const char *fmt, va_list ap)
 Append to SIP dialog history with arg list.
static void ast_quiet_chan (struct ast_channel *chan)
 Turn off generator data XXX Does this function belong in the SIP channel?
static void ast_sip_ouraddrfor (struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
 NAT fix - decide which IP address to use for Asterisk server?
 AST_THREADSTORAGE_CUSTOM_SCOPE (ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup, static)
 A per-thread temporary pvt structure.
 AST_THREADSTORAGE_CUSTOM_SCOPE (check_auth_buf, NULL, ast_free_ptr, static)
static int attempt_transfer (struct sip_dual *transferer, struct sip_dual *target)
 Attempt transfer of SIP call This fix for attended transfers on a local PBX.
static void auth_headers (enum sip_auth_type code, char **header, char **respheader)
 return the request and response heade for a 401 or 407 code
static int auto_congest (const void *arg)
 Scheduled congestion on a call. Only called by the scheduler, must return the reference when done.
static void build_callid_pvt (struct sip_pvt *pvt)
 Build SIP Call-ID value for a non-REGISTER transaction.
static void build_callid_registry (struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
 Build SIP Call-ID value for a REGISTER transaction.
static void build_contact (struct sip_pvt *p)
 Build contact header - the contact header we send out.
static struct sip_peerbuild_peer (const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
 Build peer from configuration (file or realtime static/dynamic)
static int build_reply_digest (struct sip_pvt *p, int method, char *digest, int digest_len)
 Build reply digest.
static void build_route (struct sip_pvt *p, struct sip_request *req, int backwards)
 Build route list from Record-Route header.
static void build_rpid (struct sip_pvt *p)
 Build the Remote Party-ID & From using callingpres options.
static void build_via (struct sip_pvt *p)
 Build a Via header for a request.
static int cb_extensionstate (char *context, char *exten, int state, void *data)
 Callback for the devicestate notification (SUBSCRIBE) support subsystem.
static void change_hold_state (struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
 Change hold state for a call.
static void change_t38_state (struct sip_pvt *p, int state)
 Change the T38 state on a SIP dialog.
static enum check_auth_result check_auth (struct sip_pvt *p, struct sip_request *req, const char *username, const char *secret, const char *md5secret, int sipmethod, char *uri, enum xmittype reliable, int ignore)
 Check user authorization from peer definition Some actions, like REGISTER and INVITEs from peers require authentication (if peer have secret set)
static enum check_auth_result check_peer_ok (struct sip_pvt *p, char *of, struct sip_request *req, int sipmethod, struct sockaddr_in *sin, struct sip_peer **authpeer, enum xmittype reliable, char *rpid_num, char *calleridname, char *uri2)
 Validate device authentication.
static void check_pendings (struct sip_pvt *p)
 Check pending actions on SIP call.
static void check_rtp_timeout (struct sip_pvt *dialog, time_t t)
 helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked
static int check_sip_domain (const char *domain, char *context, size_t len)
 check_sip_domain: Check if domain part of uri is local to our server
static int check_user (struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
 Find user If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced.
static enum check_auth_result check_user_full (struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin, struct sip_peer **authpeer)
 Check if matching user or peer is defined Match user on From: user name and peer on IP/port This is used on first invite (not re-invites) and subscribe requests.
static void check_via (struct sip_pvt *p, struct sip_request *req)
 check Via: header for hostname, port and rport request/answer
static attribute_unused void check_via_response (struct sip_pvt *p, struct sip_request *req)
 check received= and rport= in a SIP response. If we get a response with received= and/or rport= in the Via: line, use them as 'p->ourip' (see RFC 3581 for rport, and RFC 3261 for received). Using these two fields SIP can produce the correct address and port in the SIP headers without the need for STUN. The address part is also reused for the media sessions. Note that ast_sip_ouraddrfor() still rewrites p->ourip if you specify externip/seternaddr/stunaddr.
static void cleanup_stale_contexts (char *new, char *old)
 Destroy disused contexts between reloads Only used in reload_config so the code for regcontext doesn't get ugly.
static void clear_peer_mailboxes (struct sip_peer *peer)
static int clear_realm_authentication (struct sip_auth *authlist)
 Clear realm authentication list (at reload)
static void clear_sip_domains (void)
 Clear our domain list (at reload)
static const char * cli_yesno (int x)
 return Yes or No depending on the argument. This is used in many places in CLI command, having a function to generate this helps maintaining a consistent output (and possibly emitting the output in other languages, at some point).
static char * complete_sip_peer (const char *word, int state, int flags2)
 Do completion on peer name.
static char * complete_sip_registered_peer (const char *word, int state, int flags2)
 Do completion on registered peer name.
static char * complete_sip_show_history (const char *line, const char *word, int pos, int state)
 Support routine for 'sip show history' CLI.
static char * complete_sip_show_peer (const char *line, const char *word, int pos, int state)
 Support routine for 'sip show peer' CLI.
static char * complete_sip_show_user (const char *line, const char *word, int pos, int state)
 Support routine for 'sip show user' CLI.
static char * complete_sip_unregister (const char *line, const char *word, int pos, int state)
 Support routine for 'sip unregister' CLI.
static char * complete_sip_user (const char *word, int state)
 Do completion on user name.
static char * complete_sipch (const char *line, const char *word, int pos, int state)
 Support routine for 'sip show channel' and 'sip show history' CLI This is in charge of generating all strings that match a prefix in the given position. As many functions of this kind, each invokation has O(state) time complexity so be careful in using it.
static char * complete_sipnotify (const char *line, const char *word, int pos, int state)
 Support routine for 'sip notify' CLI.
static int copy_all_header (struct sip_request *req, const struct sip_request *orig, const char *field)
 Copy all headers from one request to another.
static int copy_header (struct sip_request *req, const struct sip_request *orig, const char *field)
 Copy one header field from one request to another.
static void copy_request (struct sip_request *dst, const struct sip_request *src)
 copy SIP request (mostly used to save request for responses)
static void copy_socket_data (struct sip_socket *to_sock, const struct sip_socket *from_sock)
static struct ast_variablecopy_vars (struct ast_variable *src)
static int copy_via_headers (struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
 Copy SIP VIA Headers from the request to the response.
static int create_addr (struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
 create address structure from device name Or, if peer not found, find it in the global DNS returns TRUE (-1) on failure, FALSE on success
static int create_addr_from_peer (struct sip_pvt *dialog, struct sip_peer *peer)
 Create address structure from peer reference. This function copies data from peer to the dialog, so we don't have to look up the peer again from memory or database during the life time of the dialog.
static void deinit_req (struct sip_request *req)
 Deinitialize SIP response/request.
static void destroy_association (struct sip_peer *peer)
 Remove registration data from realtime database or AST/DB when registration expires.
static void destroy_mailbox (struct sip_mailbox *mailbox)
static int determine_firstline_parts (struct sip_request *req)
 Parse first line of incoming SIP request.
static int dialog_cmp_cb (void *obj, void *arg, int flags)
static int dialog_dump_func (void *userobj, void *arg, int flags)
static int dialog_hash_cb (const void *obj, const int flags)
static int dialog_needdestroy (void *dialogobj, void *arg, int flags)
 Match dialogs that need to be destroyed.
static struct sip_pvtdialog_ref (struct sip_pvt *p, char *tag)
 when we create or delete references, make sure to use these functions so we keep track of the refcounts. To simplify the code, we allow a NULL to be passed to dialog_unref().
static void * dialog_unlink_all (struct sip_pvt *dialog, int lockowner, int lockdialoglist)
 Unlink a dialog from the dialogs container, as well as any other places that it may be currently stored.
static struct sip_pvtdialog_unref (struct sip_pvt *p, char *tag)
static int do_magic_pickup (struct ast_channel *channel, const char *extension, const char *context)
static void * do_monitor (void *data)
 The SIP monitoring thread.
static int do_proxy_auth (struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
 Add authentication on outbound SIP packet.
static int do_register_auth (struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
 Authenticate for outbound registration.
static void do_setnat (struct sip_pvt *p, int natflags)
 Set nat mode on the various data sockets.
static const char * domain_mode_to_text (const enum domain_mode mode)
 Print domain mode to cli.
static const char * dtmfmode2str (int mode)
 Convert DTMF mode to printable string.
static int expire_register (const void *data)
 Expire registration of SIP peer.
static void extract_uri (struct sip_pvt *p, struct sip_request *req)
 Check Contact: URI of SIP message.
static const char * faxec2str (int faxec)
static int finalize_content (struct sip_request *req)
 Add 'Content-Length' header and content to SIP message.
static const char * find_alias (const char *name, const char *_default)
 Find compressed SIP alias.
static int find_by_name (void *obj, void *arg, void *data, int flags)
static struct sip_pvtfind_call (struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
 find or create a dialog structure for an incoming SIP message. Connect incoming SIP message to current dialog or create new dialog structure Returns a reference to the sip_pvt object, remember to give it back once done. Called by handle_incoming(), sipsock_read
static int find_call_cb (void *__pvt, void *__arg, int flags)
static int find_calling_channel (struct ast_channel *c, void *data)
static const char * find_closing_quote (const char *start, const char *lim)
 Locate closing quote in a string, skipping escaped quotes. optionally with a limit on the search. start must be past the first quote.
static struct sip_peerfind_peer (const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
 Locate device by name or ip address.
static struct sip_authfind_realm_authentication (struct sip_auth *authlist, const char *realm)
 Find authentication for a specific realm.
static int find_sdp (struct sip_request *req)
 Determine whether a SIP message contains an SDP in its body.
static int find_sip_method (const char *msg)
 find_sip_method: Find SIP method from header
static struct
cfsubscription_types
find_subscription_type (enum subscriptiontype subtype)
 Find subscription type in array.
static void free_old_route (struct sip_route *route)
 Remove route from route list.
static void free_via (struct sip_via *v)
static int func_check_sipdomain (struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
 Dial plan function to check if domain is local.
static int func_header_read (struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
 Read SIP header (dialplan function)
static int function_sipchaninfo_read (struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
 ${SIPCHANINFO()} Dialplan function - reads sip channel data
static int function_sippeer (struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
 ${SIPPEER()} Dialplan function - reads peer data
static char * generate_random_string (char *buf, size_t size)
 Generate 32 byte random string for callid's etc.
static int get_also_info (struct sip_pvt *p, struct sip_request *oreq)
 Call transfer support (old way, deprecated by the IETF)
static char * get_body (struct sip_request *req, char *name, char delimiter)
 Get a specific line from the message body.
static char * get_body_by_line (const char *line, const char *name, int nameLen, char delimiter)
 Reads one line of SIP message body.
static int get_cached_mwi (struct sip_peer *peer, int *new, int *old)
 Get cached MWI info.
static char * get_calleridname (const char *input, char *output, size_t outputsize)
 Get caller id name from SIP headers.
static int get_destination (struct sip_pvt *p, struct sip_request *oreq)
 Find out who the call is for. We use the request uri as a destination. This code assumes authentication has been done, so that the device (peer/user) context is already set.
static const char * get_header (const struct sip_request *req, const char *name)
 Get header from SIP request.
static char * get_in_brackets (char *tmp)
 Pick out text in brackets from character string.
static struct ast_variableget_insecure_variable_from_config (struct ast_config *config)
static int get_ip_and_port_from_sdp (struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
static int get_msg_text (char *buf, int len, struct sip_request *req, int addnewline)
 Get text out of a SIP MESSAGE packet.
static const char * get_name_from_variable (struct ast_variable *var, const char *newpeername)
static void get_our_media_address (struct sip_pvt *p, int needvideo, struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin, struct sockaddr_in *dest, struct sockaddr_in *vdest)
 Set all IP media addresses for this call.
static int get_rdnis (struct sip_pvt *p, struct sip_request *oreq)
 Get referring dnis.
static int get_refer_info (struct sip_pvt *transferer, struct sip_request *outgoing_req)
 Call transfer support (the REFER method) Extracts Refer headers into pvt dialog structure.
static int get_rpid_num (const char *input, char *output, int maxlen)
 Get caller id number from Remote-Party-ID header field Returns true if number should be restricted (privacy setting found) output is set to NULL if no number found.
static const char * get_sdp_iterate (int *start, struct sip_request *req, const char *name)
 Lookup 'name' in the SDP starting at the 'start' line. Returns the matching line, and 'start' is updated with the next line number.
static char get_sdp_line (int *start, int stop, struct sip_request *req, const char **value)
 Fetches the next valid SDP line between the 'start' line (inclusive) and the 'stop' line (exclusive). Returns the type ('a', 'c', ...) and matching line in reference 'start' is updated with the next line number.
static struct sip_pvtget_sip_pvt_byid_locked (const char *callid, const char *totag, const char *fromtag)
 Lock dialog lock and find matching pvt lock.
static const char * get_srv_protocol (enum sip_transport t)
 Return protocol string for srv dns query.
static const char * get_srv_service (enum sip_transport t)
 Return service string for srv dns query.
static const char * get_transport (enum sip_transport t)
 Return transport as string.
static const char * get_transport_list (unsigned int transports)
 Return configuration of transports for a device.
static const char * get_transport_pvt (struct sip_pvt *p)
 Return transport of dialog.
static int get_transport_str2enum (const char *transport)
 Return int representing a bit field of transport types found in const char *transport.
static const char * gettag (const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
 Get tag from packet.
static int handle_common_options (struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
 Handle flag-type options common to configuration of devices - peers.
static int handle_incoming (struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
 Handle incoming SIP requests (methods)
static int handle_invite_replaces (struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
 Handle the transfer part of INVITE with a replaces: header, meaning a target pickup or an attended transfer. Used only once. XXX 'ignore' is unused.
static int handle_request_bye (struct sip_pvt *p, struct sip_request *req)
 Handle incoming BYE request.
static int handle_request_cancel (struct sip_pvt *p, struct sip_request *req)
 Handle incoming CANCEL request.
static int handle_request_do (struct sip_request *req, struct sockaddr_in *sin)
 Handle incoming SIP message - request or response.
static void handle_request_info (struct sip_pvt *p, struct sip_request *req)
 Receive SIP INFO Message.
static int handle_request_invite (struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock)
 Handle incoming INVITE request.
static int handle_request_message (struct sip_pvt *p, struct sip_request *req)
 Handle incoming MESSAGE request.
static int handle_request_notify (struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
 Handle incoming notifications.
static int handle_request_options (struct sip_pvt *p, struct sip_request *req)
 Handle incoming OPTIONS request An OPTIONS request should be answered like an INVITE from the same UA, including SDP.
static int handle_request_refer (struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
static int handle_request_register (struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
 Handle incoming REGISTER request.
static int handle_request_subscribe (struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
 Handle incoming SUBSCRIBE request.
static void handle_response (struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
 Handle SIP response in dialogue.
static void handle_response_invite (struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
 Handle SIP response to INVITE dialogue.
static void handle_response_notify (struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
static void handle_response_peerpoke (struct sip_pvt *p, int resp, struct sip_request *req)
 Handle qualification responses (OPTIONS)
static void handle_response_refer (struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
static int handle_response_register (struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
 Handle responses on REGISTER to services.
static void handle_response_subscribe (struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
static int handle_t38_options (struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v, int *maxdatagram)
 Handle T.38 configuration options common to users and peers.
static const char * hangup_cause2sip (int cause)
 Convert Asterisk hangup causes to SIP codes.
static int hangup_sip2cause (int cause)
 Convert SIP hangup causes to Asterisk hangup causes.
static int init_req (struct sip_request *req, int sipmethod, const char *recip)
 Initialize SIP request.
static int init_resp (struct sip_request *resp, const char *msg)
 Initialize SIP response, based on SIP request.
static void initialize_initreq (struct sip_pvt *p, struct sip_request *req)
 Initialize the initital request packet in the pvt structure. This packet is used for creating replies and future requests in a dialog.
static void initreqprep (struct sip_request *req, struct sip_pvt *p, int sipmethod)
 Initiate new SIP request to peer/user.
static const char * insecure2str (int mode)
 Convert Insecure setting to printable string.
static int interpret_t38_parameters (struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
 Helper function which updates T.38 capability information and triggers a reinvite.
static void list_route (struct sip_route *route)
 List all routes - mostly for debugging.
static int load_module (void)
 PBX load module - initialization.
static int local_attended_transfer (struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
 Find all call legs and bridge transferee with target called from handle_request_refer.
static int lws2sws (char *msgbuf, int len)
 Parse multiline SIP headers into one header This is enabled if pedanticsipchecking is enabled.
static void make_our_tag (char *tagbuf, size_t len)
 Make our SIP dialog tag.
static int manager_show_registry (struct mansession *s, const struct message *m)
 Show SIP registrations in the manager API.
static int manager_sip_qualify_peer (struct mansession *s, const struct message *m)
 Qualify SIP peers in the manager API.
static int manager_sip_show_peer (struct mansession *s, const struct message *m)
 Show SIP peers in the manager API.
static int manager_sip_show_peers (struct mansession *s, const struct message *m)
 Show SIP peers in the manager API.
static int manager_sipnotify (struct mansession *s, const struct message *m)
static int map_s_x (const struct _map_x_s *table, const char *s, int errorvalue)
 map from a string to an integer value, case insensitive. If no match is found, return errorvalue.
static const char * map_x_s (const struct _map_x_s *table, int x, const char *errorstring)
 map from an integer value to a string. If no match is found, return errorstring
static int method_match (enum sipmethod id, const char *name)
 returns true if 'name' (with optional trailing whitespace) matches the sip method 'id'. Strictly speaking, SIP methods are case SENSITIVE, but we do a case-insensitive comparison to be more tolerant. following Jon Postel's rule: Be gentle in what you accept, strict with what you send
static void mwi_event_cb (const struct ast_event *event, void *userdata)
 Receive MWI events that we have subscribed to.
static const char * nat2str (int nat)
 Convert NAT setting to text string.
static struct sip_proxyobproxy_get (struct sip_pvt *dialog, struct sip_peer *peer)
 Get default outbound proxy or global proxy.
static void parse_copy (struct sip_request *dst, const struct sip_request *src)
 Copy SIP request, parse it.
static int parse_minse (const char *p_hdrval, int *const p_interval)
 Session-Timers: Function for parsing Min-SE header.
static void parse_moved_contact (struct sip_pvt *p, struct sip_request *req)
 Parse 302 Moved temporalily response.
static int parse_ok_contact (struct sip_pvt *pvt, struct sip_request *req)
 Save contact header for 200 OK on INVITE.
static enum parse_register_result parse_register_contact (struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
 Parse contact header and save registration (peer registration)
static int parse_request (struct sip_request *req)
 Parse a SIP message.
static int parse_session_expires (const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
 Session-Timers: Function for parsing Session-Expires header.
static unsigned int parse_sip_options (struct sip_pvt *pvt, const char *supported)
 Parse supported header in incoming packet.
static int parse_uri (char *uri, const char *scheme, char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
 * parses a URI in its components.
static struct sip_viaparse_via (const char *header)
 Parse a Via header.
static int peer_cmp_cb (void *obj, void *arg, int flags)
static int peer_dump_func (void *userobj, void *arg, int flags)
static int peer_hash_cb (const void *obj, const int flags)
static int peer_ipcmp_cb (void *obj, void *arg, int flags)
static int peer_iphash_cb (const void *obj, const int flags)
static int peer_is_marked (void *peerobj, void *arg, int flags)
static void peer_mailboxes_to_str (struct ast_str **mailbox_str, struct sip_peer *peer)
 list peer mailboxes to CLI
static int peer_markall_func (void *device, void *arg, int flags)
static int peer_status (struct sip_peer *peer, char *status, int statuslen)
int peercomparefunc (const void *a, const void *b)
static int port_str2int (const char *pt, unsigned int standard)
 converts ascii port to int representation. If no pt buffer is provided or the pt has errors when being converted to an int value, the port provided as the standard is used.
static void print_codec_to_cli (int fd, struct ast_codec_pref *pref)
 Print codec list from preference to CLI/manager.
static void print_group (int fd, ast_group_t group, int crlf)
 Print call group and pickup group.
static void proc_422_rsp (struct sip_pvt *p, struct sip_request *rsp)
 Handle 422 response to INVITE with session-timer requested.
static int proc_session_timer (const void *vp)
 Session-Timers: Process session refresh timeout event.
static void process_request_queue (struct sip_pvt *p, int *recount, int *nounlock)
static int process_sdp (struct sip_pvt *p, struct sip_request *req, int t38action)
 Process SIP SDP offer, select formats and activate RTP channels If offer is rejected, we will not change any properties of the call Return 0 on success, a negative value on errors. Must be called after find_sdp().
static int process_sdp_a_audio (const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
static int process_sdp_a_image (const char *a, struct sip_pvt *p)
static int process_sdp_a_sendonly (const char *a, int *sendonly)
static int process_sdp_a_text (const char *a, struct sip_pvt *p, struct ast_rtp *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec)
static int process_sdp_a_video (const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
static int process_sdp_c (const char *c, struct ast_hostent *hp)
static int process_sdp_o (const char *o, struct sip_pvt *p)
static int process_via (struct sip_pvt *p, const struct sip_request *req)
static struct sip_proxyproxy_allocate (char *name, char *port, int force)
 Allocate and initialize sip proxy.
static int proxy_update (struct sip_proxy *proxy)
static void pvt_set_needdestroy (struct sip_pvt *pvt, const char *reason)
static int queue_request (struct sip_pvt *p, const struct sip_request *req)
static struct sip_peerrealtime_peer (const char *newpeername, struct sockaddr_in *sin, int devstate_only)
 realtime_peer: Get peer from realtime storage Checks the "sippeers" realtime family from extconfig.conf Checks the "sipregs" realtime family from extconfig.conf if it's configured. This returns a pointer to a peer and because we use build_peer, we can rest assured that the refcount is bumped.
static void realtime_update_peer (const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, int deprecated_username, int lastms)
 Update peer object in realtime storage If the Asterisk system name is set in asterisk.conf, we will use that name and store that in the "regserver" field in the sippeers table to facilitate multi-server setups.
static void receive_message (struct sip_pvt *p, struct sip_request *req)
 Receive SIP MESSAGE method messages.
static struct sip_peerref_peer (struct sip_peer *peer, char *tag)
static void ref_proxy (struct sip_pvt *pvt, struct sip_proxy *proxy)
 maintain proper refcounts for a sip_pvt's outboundproxy
static const char * referstatus2str (enum referstatus rstatus)
 Convert transfer status to string.
static void reg_source_db (struct sip_peer *peer)
 Get registration details from Asterisk DB.
static void register_peer_exten (struct sip_peer *peer, int onoff)
 Automatically add peer extension to dial plan.
static enum check_auth_result register_verify (struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
 Verify registration of user

  • Registration is done in several steps, first a REGISTER without auth to get a challenge (nonce) then a second one with auth
  • Registration requests are only matched with peers that are marked as "dynamic".

static struct sip_registryregistry_addref (struct sip_registry *reg, char *tag)
 Add object reference to SIP registry.
static void * registry_unref (struct sip_registry *reg, char *tag)
static const char * regstate2str (enum sipregistrystate regstate)
 Convert registration state status to string.
static int reload (void)
 Part of Asterisk module interface.
static int reload_config (enum channelreloadreason reason)
 Re-read SIP.conf config file.
static char * remove_uri_parameters (char *uri)
static void replace_cid (struct sip_pvt *p, const char *rpid_num, const char *calleridname)
 helper function for check_{user|peer}_ok()
static int reply_digest (struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
 reply to authentication for outbound registrations
static int reqprep (struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
 Initialize a SIP request message (not the initial one in a dialog)
static int resp_needs_contact (const char *msg, enum sipmethod method)
 Test if this response needs a contact header.
static int respprep (struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
 Prepare SIP response packet.
static int restart_monitor (void)
 Start the channel monitor thread.
static void restart_session_timer (struct sip_pvt *p)
 Session-Timers: Restart session timer.
static int retrans_pkt (const void *data)
 Retransmit SIP message if no answer (Called from scheduler)
static int scheduler_process_request_queue (const void *data)
static int send_provisional_keepalive (const void *data)
static int send_provisional_keepalive_full (struct sip_pvt *pvt, int with_sdp)
static int send_provisional_keepalive_with_sdp (const void *data)
static int send_request (struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
 Send SIP Request to the other part of the dialogue.
static int send_response (struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
 Transmit response on SIP request.
static int set_address_from_contact (struct sip_pvt *pvt)
 Change the other partys IP address based on given contact.
static void set_destination (struct sip_pvt *p, char *uri)
 Set destination from SIP URI.
static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
 Parse insecure= setting in sip.conf and set flags according to setting.
static void set_nonce_randdata (struct sip_pvt *p, int forceupdate)
 builds the sip_pvt's randdata field which is used for the nonce challenge. When forceupdate is not set, the nonce is only updated if the current one is stale. In this case, a stalenonce is one which has already received a response, if a nonce has not received a response it is not always necessary or beneficial to create a new one.
static void set_peer_defaults (struct sip_peer *peer)
 Set peer defaults before configuring specific configurations.
static void set_socket_transport (struct sip_socket *socket, int transport)
static void set_t38_capabilities (struct sip_pvt *p)
 Set the global T38 capabilities on a SIP dialog structure.
static int show_channels_cb (void *__cur, void *__arg, int flags)
 callback for show channel|subscription
static int show_chanstats_cb (void *__cur, void *__arg, int flags)
 Callback for show_chanstats.
static int sip_addheader (struct ast_channel *chan, void *data)
 Add a SIP header to an outbound INVITE.
static struct sip_pvtsip_alloc (ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, struct sip_request *req)
 Allocate sip_pvt structure, set defaults and link in the container. Returns a reference to the object so whoever uses it later must remember to release the reference.
static void sip_alreadygone (struct sip_pvt *dialog)
 Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging.
static int sip_answer (struct ast_channel *ast)
 sip_answer: Answer SIP call , send 200 OK on Invite Part of PBX interface
static int sip_call (struct ast_channel *ast, char *dest, int timeout)
 Initiate SIP call from PBX used from the dial() application.
static int sip_cancel_destroy (struct sip_pvt *p)
 Cancel destruction of SIP dialog. Be careful as this also absorbs the reference - if you call it from within the scheduler, this might be the last reference.
static int sip_check_authtimeout (time_t start)
 Check if the authtimeout has expired.
static char * sip_cli_notify (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Cli command to send SIP notify to peer.
static int sip_debug_test_addr (const struct sockaddr_in *addr)
 See if we pass debug IP filter.
static int sip_debug_test_pvt (struct sip_pvt *p)
 Test PVT for debugging output.
static struct sip_pvtsip_destroy (struct sip_pvt *p)
 Destroy SIP call structure. Make it return NULL so the caller can do things like foo = sip_destroy(foo); and reduce the chance of bugs due to dangling pointers.
static void sip_destroy_fn (void *p)
static void sip_destroy_peer (struct sip_peer *peer)
 Destroy peer object from memory.
static void sip_destroy_peer_fn (void *peer)
static int sip_devicestate (void *data)
 Part of PBX channel interface.
static char * sip_do_debug (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Turn on SIP debugging (CLI command)
static char * sip_do_debug_ip (int fd, char *arg)
 Enable SIP Debugging for a single IP.
static char * sip_do_debug_peer (int fd, char *arg)
 Turn on SIP debugging for a given peer.
static int sip_do_reload (enum channelreloadreason reason)
 Reload module.
static int sip_dtmfmode (struct ast_channel *chan, void *data)
 Set the DTMFmode for an outbound SIP call (application)
static void sip_dump_history (struct sip_pvt *dialog)
 Dump SIP history to debug log file at end of lifespan for SIP dialog.
static int sip_fixup (struct ast_channel *oldchan, struct ast_channel *newchan)
 sip_fixup: Fix up a channel: If a channel is consumed, this is called. Basically update any ->owner links
static const char * sip_get_callid (struct ast_channel *chan)
 Deliver SIP call ID for the call.
static int sip_get_codec (struct ast_channel *chan)
 Return SIP UA's codec (part of the RTP interface)
static enum ast_rtp_get_result sip_get_rtp_peer (struct ast_channel *chan, struct ast_rtp **rtp)
 Returns null if we can't reinvite audio (part of RTP interface)
static enum ast_rtp_get_result sip_get_trtp_peer (struct ast_channel *chan, struct ast_rtp **rtp)
 Returns null if we can't reinvite text (part of RTP interface)
static struct ast_udptlsip_get_udptl_peer (struct ast_channel *chan)
static enum ast_rtp_get_result sip_get_vrtp_peer (struct ast_channel *chan, struct ast_rtp **rtp)
 Returns null if we can't reinvite video (part of RTP interface)
static int sip_hangup (struct ast_channel *ast)
 sip_hangup: Hangup SIP call Part of PBX interface, called from ast_hangup
static int sip_indicate (struct ast_channel *ast, int condition, const void *data, size_t datalen)
 Play indication to user With SIP a lot of indications is sent as messages, letting the device play the indication - busy signal, congestion etc.
static const char * sip_nat_mode (const struct sip_pvt *p)
 Display SIP nat mode.
static struct ast_channelsip_new (struct sip_pvt *i, int state, const char *title)
 Initiate a call in the SIP channel called from sip_request_call (calls from the pbx ) for outbound channels and from handle_request_invite for inbound channels.
static int sip_park (struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
 Park a call using the subsystem in res_features.c This is executed in a separate thread.
static void * sip_park_thread (void *stuff)
 Park SIP call support function Starts in a new thread, then parks the call XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the audio can't be heard before hangup.
static int sip_parse_host (char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
 Small function to parse a config line for a host with a transport i.e. tls://www.google.com:8056.
static void sip_peer_hold (struct sip_pvt *p, int hold)
 Change onhold state of a peer using a pvt structure.
static void sip_poke_all_peers (void)
 Send a poke to all known peers.
static int sip_poke_noanswer (const void *data)
 React to lack of answer to Qualify poke.
static int sip_poke_peer (struct sip_peer *peer, int force)
 Check availability of peer, also keep NAT open.
static int sip_poke_peer_s (const void *data)
 Poke peer (send qualify to check if peer is alive and well)
static int sip_prepare_socket (struct sip_pvt *p)
static char * sip_prune_realtime (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Remove temporary realtime objects from memory (CLI)
static char * sip_qualify_peer (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Send an OPTIONS packet to a SIP peer.
static int sip_queryoption (struct ast_channel *chan, int option, void *data, int *datalen)
 Query an option on a SIP dialog.
static struct ast_framesip_read (struct ast_channel *ast)
 Read SIP RTP from channel.
static struct sockaddr_in * sip_real_dst (const struct sip_pvt *p)
 The real destination address for a write.
static int sip_refer_allocate (struct sip_pvt *p)
 Allocate SIP refer structure.
static int sip_reg_timeout (const void *data)
 Registration timeout, register again Registered as a timeout handler during transmit_register(), to retransmit the packet if a reply does not come back. This is called by the scheduler so the event is not pending anymore when we are called.
static int sip_register (const char *value, int lineno)
 Parse register=> line in sip.conf and add to registry.
static void sip_registry_destroy (struct sip_registry *reg)
 Destroy registry object Objects created with the register= statement in static configuration.
static int sip_reinvite_retry (const void *data)
 Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite to avoid race conditions between asterisk servers. Called from the scheduler.
static char * sip_reload (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Force reload of module from cli.
static int sip_removeheader (struct ast_channel *chan, void *data)
 Remove SIP headers added previously with SipAddHeader application.
static struct ast_channelsip_request_call (const char *type, int format, void *data, int *cause)
 PBX interface function -build SIP pvt structure SIP calls initiated by the PBX arrive here.
static int sip_reregister (const void *data)
 Update registration with SIP Proxy. Called from the scheduler when the previous registration expires, so we don't have to cancel the pending event. We assume the reference so the sip_registry is valid, since it is stored in the scheduled event anyways.
static struct ast_framesip_rtp_read (struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
 Read RTP from network.
static void sip_scheddestroy (struct sip_pvt *p, int ms)
 Schedule destruction of SIP dialog.
static void sip_send_all_mwi_subscriptions (void)
 Send all MWI subscriptions.
static void sip_send_all_registers (void)
 Send all known registrations.
static int sip_send_mwi_to_peer (struct sip_peer *peer, const struct ast_event *event, int cache_only)
 Send message waiting indication to alert peer that they've got voicemail.
static int sip_senddigit_begin (struct ast_channel *ast, char digit)
static int sip_senddigit_end (struct ast_channel *ast, char digit, unsigned int duration)
 Send DTMF character on SIP channel within one call, we're able to transmit in many methods simultaneously.
static int sip_sendhtml (struct ast_channel *chan, int subclass, const char *data, int datalen)
 Send message with Access-URL header, if this is an HTML URL only!
static int sip_sendtext (struct ast_channel *ast, const char *text)
 Send SIP MESSAGE text within a call Called from PBX core sendtext() application.
static char * sip_set_history (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Enable/Disable SIP History logging (CLI)
static void sip_set_redirstr (struct sip_pvt *p, char *reason)
 Translate referring cause.
static int sip_set_rtp_peer (struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active)
 Set the RTP peer for this call.
static int sip_set_udptl_peer (struct ast_channel *chan, struct ast_udptl *udptl)
static char * sip_show_channel (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Show details of one active dialog.
static char * sip_show_channels (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 CLI for show channels or subscriptions. This is a new-style CLI handler so a single function contains the prototype for the function, the 'generator' to produce multiple entries in case it is required, and the actual handler for the command.
static char * sip_show_channelstats (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 SIP show channelstats CLI (main function)
static char * sip_show_domains (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 CLI command to list local domains.
static char * sip_show_history (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Show history details of one dialog.
static char * sip_show_inuse (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 CLI Command to show calls within limits set by call_limit.
static char * sip_show_mwi (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * sip_show_objects (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 List all allocated SIP Objects (realtime or static)
static char * sip_show_peer (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Show one peer in detail.
static char * sip_show_peers (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 CLI Show Peers command.
static char * sip_show_registry (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Show SIP Registry (registrations with other SIP proxies.
static char * sip_show_sched (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * sip_show_settings (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 List global settings for the SIP channel.
static char * sip_show_tcp (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Show active TCP connections.
static char * sip_show_user (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Show one user in detail.
static char * sip_show_users (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 CLI Command 'SIP Show Users'.
static int sip_sipredirect (struct sip_pvt *p, const char *dest)
 Transfer call before connect with a 302 redirect.
static struct sip_st_dlgsip_st_alloc (struct sip_pvt *const p)
 Allocate Session-Timers struct w/in dialog.
static int sip_standard_port (enum sip_transport type, int port)
 Returns the port to use for this socket.
static int sip_subscribe_mwi (const char *value, int lineno)
 Parse mwi=> line in sip.conf and add to list.
static void sip_subscribe_mwi_destroy (struct sip_subscription_mwi *mwi)
 Destroy MWI subscription object.
static int sip_subscribe_mwi_do (const void *data)
 Send a subscription or resubscription for MWI.
static int sip_t38_abort (const void *data)
 Called to deny a T38 reinvite if the core does not respond to our request.
static struct
ast_tcptls_session_instance
sip_tcp_locate (struct sockaddr_in *s)
 Find thread for TCP/TLS session (based on IP/Port.
static void * sip_tcp_worker_fn (void *data)
 SIP TCP connection handler.
static void sip_tcptls_client_args_destructor (void *obj)
static int sip_tcptls_write (struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
 used to indicate to a tcptls thread that data is ready to be written
static struct sip_threadinfosip_threadinfo_create (struct ast_tcptls_session_instance *tcptls_session, int transport)
 creates a sip_threadinfo object and links it into the threadt table.
static void sip_threadinfo_destructor (void *obj)
static int sip_transfer (struct ast_channel *ast, const char *dest)
 Transfer SIP call.
static char * sip_unregister (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Unregister (force expiration) a SIP peer in the registry via CLI.
static int sip_uri_cmp (const char *input1, const char *input2)
static int sip_uri_headers_cmp (const char *input1, const char *input2)
 helper routine for sip_uri_cmp
static int sip_uri_params_cmp (const char *input1, const char *input2)
 helper routine for sip_uri_cmp to compare URI parameters
static int sip_write (struct ast_channel *ast, struct ast_frame *frame)
 Send frame to media channel (rtp)
static int sipsock_read (int *id, int fd, short events, void *ignore)
 Read data from SIP UDP socket.
static enum st_mode st_get_mode (struct sip_pvt *p)
 Get the session-timer mode.
static enum st_refresher st_get_refresher (struct sip_pvt *p)
 Get the entity (UAC or UAS) that's acting as the session-timer refresher.
static int st_get_se (struct sip_pvt *p, int max)
 Get Max or Min SE (session timer expiry)
static void start_session_timer (struct sip_pvt *p)
 Session-Timers: Start session timer.
static const char * stmode2str (enum st_mode m)
static void stop_media_flows (struct sip_pvt *p)
 Immediately stop RTP, VRTP and UDPTL as applicable.
static void stop_session_timer (struct sip_pvt *p)
 Session-Timers: Stop session timer.
static int str2dtmfmode (const char *str)
 maps a string to dtmfmode, returns -1 on error
static enum st_mode str2stmode (const char *s)
static enum st_refresher str2strefresher (const char *s)
static const char * strefresher2str (enum st_refresher r)
static const char * subscription_type2str (enum subscriptiontype subtype)
 Show subscription type in string format.
static unsigned int t38_get_rate (enum ast_control_t38_rate rate)
 Get Max T.38 Transmission rate from T38 capabilities.
static void tcptls_packet_destructor (void *obj)
static struct sip_peertemp_peer (const char *name)
 Create temporary peer (used in autocreatepeer mode)
static void temp_pvt_cleanup (void *)
static int temp_pvt_init (void *)
static char * terminate_uri (char *uri)
static int threadinfo_locate_cb (void *obj, void *arg, int flags)
static int threadt_cmp_cb (void *obj, void *arg, int flags)
static int threadt_hash_cb (const void *obj, const int flags)
static char * transfermode2str (enum transfermodes mode)
 Convert transfer mode to text string.
static void transmit_fake_auth_response (struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
 Send a fake 401 Unauthorized response when the administrator wants to hide the names of local devices from fishers.
static int transmit_info_with_digit (struct sip_pvt *p, const char digit, unsigned int duration)
 Send SIP INFO dtmf message, see Cisco documentation on cisco.com.
static int transmit_info_with_vidupdate (struct sip_pvt *p)
 Send SIP INFO with video update request.
static int transmit_invite (struct sip_pvt *p, int sipmethod, int sdp, int init)
 Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it.
static int transmit_message_with_text (struct sip_pvt *p, const char *text)
 Transmit text with SIP MESSAGE method.
static int transmit_notify_custom (struct sip_pvt *p, struct ast_variable *vars)
 Notify device with custom headers from sip_notify.conf.
static int transmit_notify_with_mwi (struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
 Notify user of messages waiting in voicemail (RFC3842)
static int transmit_notify_with_sipfrag (struct sip_pvt *p, int cseq, char *message, int terminate)
 Notify a transferring party of the status of transfer (RFC3515)
static int transmit_provisional_response (struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
static int transmit_refer (struct sip_pvt *p, const char *dest)
 Transmit SIP REFER message (initiated by the transfer() dialplan application.
static int transmit_register (struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
 Transmit register to SIP proxy or UA auth = NULL on the initial registration (from sip_reregister())
static int transmit_reinvite_with_sdp (struct sip_pvt *p, int t38version, int oldsdp)
 Transmit reinvite with SDP.
static int transmit_request (struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
 Transmit generic SIP request returns XMIT_ERROR if transmit failed with a critical error (don't retry)
static int transmit_request_with_auth (struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
 Transmit SIP request, auth added.
static int transmit_response (struct sip_pvt *p, const char *msg, const struct sip_request *req)
 Transmit response, no retransmits.
static int transmit_response_reliable (struct sip_pvt *p, const char *msg, const struct sip_request *req)
 Transmit response, Make sure you get an ACK This is only used for responses to INVITEs, where we need to make sure we get an ACK.
static int transmit_response_using_temp (ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg)
 Transmit response, no retransmits, using a temporary pvt structure.
static int transmit_response_with_allow (struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
 Append Accept header, content length before transmitting response.
static int transmit_response_with_auth (struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *randdata, enum xmittype reliable, const char *header, int stale)
 Respond with authorization request.
static int transmit_response_with_date (struct sip_pvt *p, const char *msg, const struct sip_request *req)
 Append date and content length before transmitting response.
static int transmit_response_with_minse (struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
 Transmit 422 response with Min-SE header (Session-Timers)
static int transmit_response_with_sdp (struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
 Used for 200 OK and 183 early media.
static int transmit_response_with_t38_sdp (struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
 Used for 200 OK and 183 early media.
static int transmit_response_with_unsupported (struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
 Transmit response, no retransmits.
static int transmit_state_notify (struct sip_pvt *p, int state, int full, int timeout)
 Used in the SUBSCRIBE notification subsystem (RFC3265)
static void try_suggested_sip_codec (struct sip_pvt *p)
 Try setting codec suggested by the SIP_CODEC channel variable.
static void unlink_marked_peers_from_tables (void)
static void unlink_peer_from_tables (struct sip_peer *peer)
static int unload_module (void)
 PBX unload module API.
static void * unref_peer (struct sip_peer *peer, char *tag)
static int update_call_counter (struct sip_pvt *fup, int event)
 update_call_counter: Handle call_limit for SIP devices Setting a call-limit will cause calls above the limit not to be accepted.
static void update_peer (struct sip_peer *p, int expire)
 Update peer data in database (if used)
static void update_provisional_keepalive (struct sip_pvt *pvt, int with_sdp)

Variables

static struct ast_module_info
__MODULE_INFO_SECTION 
__mod_info = { __MODULE_INFO_GLOBALS .name = AST_MODULE, .flags = AST_MODFLAG_DEFAULT , .description = "Session Initiation Protocol (SIP)" , .key = ASTERISK_GPL_KEY , .buildopt_sum = AST_BUILDOPT_SUM, .load = load_module, .unload = unload_module, .reload = reload, }
static char * app_dtmfmode = "SIPDtmfMode"
static char * app_sipaddheader = "SIPAddHeader"
static char * app_sipremoveheader = "SIPRemoveHeader"
static struct ast_module_infoast_module_info = &__mod_info
static struct sip_authauthl = NULL
 Authentication list for realm authentication.
static int authlimit = DEFAULT_AUTHLIMIT
static int authtimeout = DEFAULT_AUTHTIMEOUT
static struct sockaddr_in bindaddr
static unsigned int chan_idx
static struct ast_custom_function checksipdomain_function
static struct ast_cli_entry cli_sip []
 SIP Cli commands definition.
static const char config [] = "sip.conf"
static struct sockaddr_in debugaddr
static int default_expiry = DEFAULT_DEFAULT_EXPIRY
static struct ast_jb_conf default_jbconf
 Global jitterbuffer configuration - by default, jb is disabled.
static struct ast_tls_config default_tls_cfg
 Default TLS connection configuration.
struct ao2_containerdialogs
 Here we implement the container for dialogs (sip_pvt), defining generic wrapper functions to ease the transition from the current implementation (a single linked list) to a different container. In addition to a reference to the container, we need functions to lock/unlock the container and individual items, and functions to add/remove references to the individual items.
static struct _map_x_s dtmfstr []
 mapping between dtmf flags and strings
static time_t externexpire
static char externhost [MAXHOSTNAMELEN]
static struct sockaddr_in externip
 our external IP address/port for SIP sessions. externip.sin_addr is only set when we know we might be behind a NAT, and this is done using a variety of (mutually exclusive) ways from the config file:
static int externrefresh = 10
static struct _map_x_s faxecmodes []
static struct ast_haglobal_contact_ha = NULL
 Global list of addresses dynamic peers are not allowed to use.
static struct ast_jb_conf global_jbconf
static const int HASH_DIALOG_SIZE = 563
static const int HASH_PEER_SIZE = 563
static struct _map_x_s insecurestr []
static struct sockaddr_in internip
 our (internal) default address/port to put in SIP/SDP messages internip is initialized picking a suitable address from one of the interfaces, and the same port number we bind to. It is used as the default address/port in SIP messages, and as the default address (but not port) in SDP messages.
static struct invstate2stringtable invitestate2string []
static struct ast_halocaladdr
 List of local networks We store "localnet" addresses from the config file into an access list, marked as 'DENY', so the call to ast_apply_ha() will return AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local' (i.e. presumably public) addresses.
static char mandescr_show_peer [] = " ActionID: <id> Optional action ID for this AMI transaction.\n"
static char mandescr_show_peers [] = " ActionID: <id> Action ID for this transaction. Will be returned.\n"
static char mandescr_show_registry [] = " ActionID: <id> Action ID for this transaction. Will be returned.\n"
 Manager Action SIPShowRegistry description.
static char mandescr_sipnotify [] = " ActionID: <id> Action ID for this transaction. Will be returned.\n"
static int max_expiry = DEFAULT_MAX_EXPIRY
static int min_expiry = DEFAULT_MIN_EXPIRY
static int mwi_expiry = DEFAULT_MWI_EXPIRY
static struct _map_x_s natmodes []
static const char notify_config [] = "sip_notify.conf"
static struct ast_confignotify_types = NULL
static int ourport_tcp
static int ourport_tls
struct ao2_containerpeers
 The peer list: Users, Peers and Friends.
struct ao2_containerpeers_by_ip
static struct _map_x_s referstatusstrings []
static struct ast_register_list regl
static struct _map_x_s regstatestrings []
static struct ast_custom_function sip_header_function
static struct cfsip_methods sip_methods []
static struct cfsip_options sip_options []
static struct ast_rtp_protocol sip_rtp
 Interface structure with callbacks used to connect to RTP module.
static struct
ast_tcptls_session_args 
sip_tcp_desc
 The TCP server definition.
static struct ast_channel_tech sip_tech
 Definition of this channel for PBX channel registration.
static struct ast_channel_tech sip_tech_info
 This version of the sip channel tech has no send_digit_begin callback so that the core knows that the channel does not want DTMF BEGIN frames. The struct is initialized just before registering the channel driver, and is for use with channels using SIP INFO DTMF.
static struct ast_tls_config sip_tls_cfg
 Working TLS connection configuration.
static struct
ast_tcptls_session_args 
sip_tls_desc
 The TCP/TLS server definition.
static struct ast_udptl_protocol sip_udptl
 Interface structure with callbacks used to connect to UDPTL module.
static struct ast_custom_function sipchaninfo_function
 Structure to declare a dialplan function: SIPCHANINFO.
static enum sip_debug_e sipdebug
static int sipdebug_text
 extra debugging for 'text' related events. At the moment this is set together with sip_debug_console.
static struct ast_custom_function sippeer_function
 Structure to declare a dialplan function: SIPPEER.
static int sipsock = -1
 Main socket for UDP SIP communication.
static struct _map_x_s stmodes []
 Report Peer status in character string.
static struct _map_x_s strefreshers []
static struct sockaddr_in stunaddr
static struct
ast_subscription_mwi_list 
submwil
static struct cfsubscription_types subscription_types []
static struct ao2_containerthreadt
static int unauth_sessions = 0
DefaultSettings

Default setttings are used as a channel setting and as a default when configuring devices

static char default_language [MAX_LANGUAGE]
static char default_callerid [AST_MAX_EXTENSION]
static char default_fromdomain [AST_MAX_EXTENSION]
static char default_notifymime [AST_MAX_EXTENSION]
static int default_qualify
static char default_vmexten [AST_MAX_EXTENSION]
static char default_mohinterpret [MAX_MUSICCLASS]
static char default_mohsuggest [MAX_MUSICCLASS]
static char default_parkinglot [AST_MAX_CONTEXT]
static int default_maxcallbitrate
static struct ast_codec_pref default_prefs
static unsigned int default_transports
static unsigned int default_primary_transport
GlobalSettings

Global settings apply to the channel (often settings you can change in the general section of sip.conf

static struct sip_settings sip_cfg
static int global_match_auth_username
static int global_relaxdtmf
static int global_prematuremediafilter
static int global_rtptimeout
static int global_rtpholdtimeout
static int global_rtpkeepalive
static int global_reg_timeout
static int global_regattempts_max
static int global_shrinkcallerid
static int global_callcounter
static unsigned int global_tos_sip
static unsigned int global_tos_audio
static unsigned int global_tos_video
static unsigned int global_tos_text
static unsigned int global_cos_sip
static unsigned int global_cos_audio
static unsigned int global_cos_video
static unsigned int global_cos_text
static int recordhistory
static int dumphistory
static char global_regcontext [AST_MAX_CONTEXT]
static char global_useragent [AST_MAX_EXTENSION]
static char global_sdpsession [AST_MAX_EXTENSION]
static char global_sdpowner [AST_MAX_EXTENSION]
static int global_authfailureevents
static int global_t1
static int global_t1min
static int global_timer_b
static int global_autoframing
static int global_qualifyfreq
static int global_qualify_gap
static int global_qualify_peers
static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263
 Codecs that we support by default:
static enum st_mode global_st_mode
static enum st_refresher global_st_refresher
static int global_min_se
static int global_max_se
static int global_dynamic_exclude_static = 0

Object counters @{

Bug:
These counters are not handled in a thread-safe way ast_atomic_fetchadd_int() should be used to modify these values.

#define DEC_CALL_LIMIT   0
#define INC_CALL_LIMIT   1
#define DEC_CALL_RINGING   2
#define INC_CALL_RINGING   3
#define REQ_OFFSET_TO_STR(req, offset)   (ast_str_buffer((req)->data) + ((req)->offset))
enum  domain_mode { SIP_DOMAIN_AUTO, SIP_DOMAIN_CONFIG }
 

Modes for SIP domain handling in the PBX.

More...
static int speerobjs = 0
static int rpeerobjs = 0
static int apeerobjs = 0
static int regobjs = 0
static struct ast_flags global_flags [2] = {{0}}
static int global_t38_maxdatagram
static char used_context [AST_MAX_CONTEXT]
static ast_mutex_t netlock = AST_MUTEX_INIT_VALUE
static ast_mutex_t monlock = AST_MUTEX_INIT_VALUE
 Protect the monitoring thread, so only one process can kill or start it, and not when it's doing something critical.
static ast_mutex_t sip_reload_lock = AST_MUTEX_INIT_VALUE
static pthread_t monitor_thread = AST_PTHREADT_NULL
 This is the thread for the monitor which checks for input on the channels which are not currently in use.
static int sip_reloading = FALSE
static enum channelreloadreason sip_reloadreason
static struct sched_contextsched
static struct io_contextio
static int * sipsock_read_id
static struct domain_list domain_list

Detailed Description

Implementation of Session Initiation Protocol.

Author:
Mark Spencer <markster@digium.com>

See Also:

Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support Configuration file sip.conf

********** IMPORTANT *

Note:
TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration settings, dialplan commands and dialplans apps/functions See SIP TCP and TLS support

******** General TODO:s

Todo:

Better support of forking

VIA branch tag transaction checking

Transaction support

******** Wishlist: Improvements

  • Support of SIP domains for devices, so that we match on username in the From: header
  • Connect registrations with a specific device on the incoming call. It's not done automatically in Asterisk
Overview of the handling of SIP sessions
The SIP channel handles several types of SIP sessions, or dialogs, not all of them being "telephone calls".
  • Incoming calls that will be sent to the PBX core
  • Outgoing calls, generated by the PBX
  • SIP subscriptions and notifications of states and voicemail messages
  • SIP registrations, both inbound and outbound
  • SIP peer management (peerpoke, OPTIONS)
  • SIP text messages

In the SIP channel, there's a list of active SIP dialogs, which includes all of these when they are active. "sip show channels" in the CLI will show most of these, excluding subscriptions which are shown by "sip show subscriptions"

incoming packets
Incoming packets are received in the monitoring thread, then handled by sipsock_read() for udp only. In tcp, packets are read by the tcp_helper thread. sipsock_read() function parses the packet and matches an existing dialog or starts a new SIP dialog.

sipsock_read sends the packet to handle_incoming(), that parses a bit more. If it is a response to an outbound request, the packet is sent to handle_response(). If it is a request, handle_incoming() sends it to one of a list of functions depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc sipsock_read locks the ast_channel if it exists (an active call) and unlocks it after we have processed the SIP message.

A new INVITE is sent to handle_request_invite(), that will end up starting a new channel in the PBX, the new channel after that executing in a separate channel thread. This is an incoming "call". When the call is answered, either by a bridged channel or the PBX itself the sip_answer() function is called.

The actual media - Video or Audio - is mostly handled by the RTP subsystem in rtp.c

Outbound calls
Outbound calls are set up by the PBX through the sip_request_call() function. After that, they are activated by sip_call().
Hanging up
The PBX issues a hangup on both incoming and outgoing calls through the sip_hangup() function

Definition in file chan_sip.c.


Define Documentation

#define ALLOWED_METHODS   "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"

SIP Methods we support.

Todo:
This string should be set dynamically. We only support REFER and SUBSCRIBE if we have allowsubscribe and allowrefer on in sip.conf.

Definition at line 955 of file chan_sip.c.

Referenced by respprep(), transmit_invite(), transmit_notify_with_sipfrag(), transmit_refer(), and transmit_reinvite_with_sdp().

#define CALLERID_UNKNOWN   "Anonymous"

Definition at line 528 of file chan_sip.c.

Referenced by initreqprep().

#define CHECK_AUTH_BUF_INITLEN   256

Definition at line 13096 of file chan_sip.c.

Referenced by check_auth(), and transmit_fake_auth_response().

#define check_request_transport (   peer,
  tmpl 
)

generic function for determining if a correct transport is being used to contact a peer

this is done as a macro so that the "tmpl" var can be passed either a sip_request or a sip_peer

Definition at line 2410 of file chan_sip.c.

Referenced by create_addr_from_peer(), and register_verify().

#define DEC_CALL_LIMIT   0
#define DEC_CALL_RINGING   2

Definition at line 1167 of file chan_sip.c.

Referenced by handle_response_invite(), and update_call_counter().

#define DEFAULT_ALLOW_EXT_DOM   TRUE

Allow external domains

Definition at line 997 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_ALLOWGUEST   TRUE

Definition at line 984 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_ALWAYSAUTHREJECT   FALSE

Don't reject authentication requests always

Definition at line 1006 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_AUTHLIMIT   100

Definition at line 503 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_AUTHTIMEOUT   30

Definition at line 504 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_AUTOCREATEPEER   FALSE

Don't create peers automagically

Definition at line 1002 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_CALLCOUNTER   FALSE

Definition at line 986 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_CALLERID   "asterisk"

Default caller ID

Definition at line 982 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_CALLEVENTS   FALSE

Extra manager SIP call events

Definition at line 1005 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_COMPACTHEADERS   FALSE

Send compact (one-character) SIP headers. Default off

Definition at line 988 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_CONTEXT   "default"

The default context for [general] section as well as devices

Definition at line 978 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_COS_AUDIO   5

Level 2 class of service for audio media

Definition at line 994 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_COS_SIP   4

Level 2 class of service for SIP signalling

Definition at line 993 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_COS_TEXT   5

Level 2 class of service for text media (T.140)

Definition at line 996 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_COS_VIDEO   6

Level 2 class of service for video media

Definition at line 995 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_DEFAULT_EXPIRY   120

Definition at line 497 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_EXPIRY   900

Expire slowly

Definition at line 517 of file chan_sip.c.

#define DEFAULT_FREQ_NOTOK   10 * 1000

Qualification: How often to check, if the host is down...

Definition at line 533 of file chan_sip.c.

Referenced by handle_response_peerpoke(), and sip_poke_noanswer().

#define DEFAULT_MATCHEXTERNIPLOCALLY   FALSE

Match extern IP locally default setting

Definition at line 1003 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_MAX_CALL_BITRATE   (384)

Max bitrate for video

Definition at line 1009 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_MAX_EXPIRY   3600

Definition at line 499 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_MAX_FORWARDS   "70"

Definition at line 502 of file chan_sip.c.

Referenced by initreqprep(), reqprep(), and transmit_register().

#define DEFAULT_MAX_SE   1800

Session-Timer Default Session-Expires period (RFC 4028)

Definition at line 552 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_MAXMS   2000

Qualification: Must be faster than 2 seconds by default

Definition at line 531 of file chan_sip.c.

Referenced by build_peer(), and reload_config().

#define DEFAULT_MIN_EXPIRY   60

Definition at line 498 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_MIN_SE   90

Session-Timer Default Min-SE period (RFC 4028)

Definition at line 553 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_MOHINTERPRET   "default"

The default music class

Definition at line 979 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_MOHSUGGEST   ""

Definition at line 980 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_MWI_EXPIRY   3600

Definition at line 500 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_NOTIFYCID   DISABLED

Include CID with ringing notifications

Definition at line 1000 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_NOTIFYMIME   "application/simple-message-summary"

Definition at line 983 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_NOTIFYRINGING   TRUE

Notify devicestate system on ringing state

Definition at line 999 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_PEDANTIC   FALSE

Avoid following SIP standards for dialog matching

Definition at line 1001 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_QUALIFY   FALSE

Don't monitor devices

Definition at line 1004 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_QUALIFY_GAP   100

Definition at line 524 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_QUALIFY_PEERS   1

Definition at line 525 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_QUALIFYFREQ   60 * 1000

Qualification: How often to check for the host to be up

Definition at line 532 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_REALM   "asterisk"

Realm for HTTP digest authentication

Definition at line 998 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_REGEXTENONQUALIFY   FALSE

Definition at line 1007 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_REGISTRATION_TIMEOUT   20

Definition at line 501 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_RETRANS   1000

How frequently to retransmit Default: 2 * 500 ms in RFC 3261

Definition at line 535 of file chan_sip.c.

Referenced by __sip_reliable_xmit(), and retrans_pkt().

#define DEFAULT_RTPKEEPALIVE   0

Default RTPkeepalive setting

Definition at line 985 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_SDPOWNER   "root"

Default SDP username field in (o=) header unless re-defined in sip.conf

Definition at line 1013 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_SDPSESSION   "Asterisk PBX"

Default SDP session name, (s=) header unless re-defined in sip.conf

Definition at line 1012 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_SRVLOOKUP   TRUE

Recommended setting is ON

Definition at line 987 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_T1MIN   100

100 MS for minimal roundtrip time

Definition at line 1008 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_TIMER_T1   500

SIP timer T1 (according to RFC 3261)

Definition at line 537 of file chan_sip.c.

Referenced by reload_config().

#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.

Definition at line 990 of file chan_sip.c.

Referenced by reload_config().

#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.

Definition at line 989 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_TOS_TEXT   0

Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions.

Definition at line 992 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_TOS_VIDEO   0

Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions.

Definition at line 991 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_USERAGENT   "Asterisk PBX"

Default Useragent: header unless re-defined in sip.conf

Definition at line 1011 of file chan_sip.c.

Referenced by reload_config().

#define DEFAULT_VMEXTEN   "asterisk"

Default voicemail extension

Definition at line 981 of file chan_sip.c.

Referenced by reload_config().

#define EXPIRY_GUARD_LIMIT   30

Below here, we use EXPIRY_GUARD_PCT instead of EXPIRY_GUARD_SECS

Definition at line 509 of file chan_sip.c.

Referenced by handle_response_register().

#define EXPIRY_GUARD_MIN   500

This is the minimum guard time applied. If GUARD_PCT turns out to be lower than this, it will use this time instead. This is in milliseconds.

Definition at line 511 of file chan_sip.c.

Referenced by handle_response_register().

#define EXPIRY_GUARD_PCT   0.20

Percentage of expires timeout to use when below EXPIRY_GUARD_LIMIT

Definition at line 515 of file chan_sip.c.

Referenced by handle_response_register().

#define EXPIRY_GUARD_SECS   15

How long before expiry do we reregister

Definition at line 508 of file chan_sip.c.

Referenced by handle_response_register().

#define FALSE   0

Definition at line 477 of file chan_sip.c.

Referenced by __sip_ack(), __sip_semi_ack(), _sip_qualify_peer(), _sip_show_peer(), _sip_show_peers(), add_sdp(), build_peer(), build_rpid(), cb_extensionstate(), check_auth(), check_peer_ok(), check_pendings(), create_addr(), dialog_needdestroy(), do_monitor(), expire_register(), find_call_cb(), find_sdp(), function_sippeer(), handle_invite_replaces(), handle_request_invite(), handle_request_notify(), handle_request_refer(), handle_request_subscribe(), handle_response(), handle_response_invite(), interpret_t38_parameters(), parse_register_contact(), parse_sip_options(), proc_session_timer(), process_sdp(), process_sdp_a_audio(), process_sdp_a_image(), process_sdp_a_sendonly(), process_sdp_a_text(), process_sdp_a_video(), process_sdp_c(), process_sdp_o(), proxy_update(), receive_message(), register_verify(), reload_config(), reqprep(), send_provisional_keepalive_full(), set_destination(), sip_addheader(), sip_answer(), sip_destroy_peer(), sip_devicestate(), sip_do_debug_peer(), sip_hangup(), sip_peer_hold(), sip_poke_noanswer(), sip_prune_realtime(), sip_read(), sip_register(), sip_sendhtml(), sip_set_history(), sip_set_rtp_peer(), sip_set_udptl_peer(), sip_show_inuse(), sip_show_settings(), sip_show_user(), sip_show_users(), st_get_mode(), st_get_refresher(), st_get_se(), stop_session_timer(), transmit_fake_auth_response(), transmit_invite(), transmit_provisional_response(), transmit_refer(), transmit_register(), transmit_reinvite_with_sdp(), transmit_response_with_sdp(), and update_call_counter().

#define FINDALLDEVICES   (FINDUSERS | FINDPEERS)
#define FINDUSERS   (1 << 0)

Definition at line 485 of file chan_sip.c.

Referenced by check_peer_ok(), find_by_name(), find_peer(), and sip_show_user().

#define FORMAT   "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"

Definition at line 16763 of file chan_sip.c.

#define FORMAT   "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"

Definition at line 16763 of file chan_sip.c.

#define FORMAT   "%-25.25s %-15.15s %-15.15s \n"

Definition at line 16763 of file chan_sip.c.

#define FORMAT   "%-30.30s %-6d %-9.9s %-6.6s\n"

Definition at line 16763 of file chan_sip.c.

#define FORMAT   "%-40.40s %-20.20s %-16.16s\n"

Definition at line 16763 of file chan_sip.c.

#define FORMAT   "%-30.30s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"

Definition at line 16763 of file chan_sip.c.

#define FORMAT   "%-15.15s %-11.11s %-8.8s %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.6u %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.6u\n"

Definition at line 16763 of file chan_sip.c.

#define FORMAT   "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"

Definition at line 16763 of file chan_sip.c.

#define FORMAT   "%-30.30s %-12.12s %-10.10s %-10.10s\n"

Definition at line 16763 of file chan_sip.c.

#define FORMAT2   "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"

Definition at line 16762 of file chan_sip.c.

#define FORMAT2   "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-6.6s\n"

Definition at line 16762 of file chan_sip.c.

#define FORMAT2   "%-25.25s %-15.15s %-15.15s \n"

Definition at line 16762 of file chan_sip.c.

#define FORMAT2   "%-30.30s %3.6s %9.9s %6.6s\n"

Definition at line 16762 of file chan_sip.c.

#define FORMAT2   "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"

Definition at line 16762 of file chan_sip.c.

#define FORMAT2   "%-30.30s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"

Definition at line 16762 of file chan_sip.c.

#define FORMAT3   "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"

Definition at line 16761 of file chan_sip.c.

Referenced by sip_show_channels().

#define FORMAT4   "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"

Definition at line 16760 of file chan_sip.c.

Referenced by show_channels_cb().

#define FROMDOMAIN_INVALID   "anonymous.invalid"

Definition at line 529 of file chan_sip.c.

Referenced by initreqprep().

#define INC_CALL_LIMIT   1

Definition at line 1166 of file chan_sip.c.

Referenced by handle_request_invite(), and update_call_counter().

#define INC_CALL_RINGING   3

Definition at line 1168 of file chan_sip.c.

Referenced by sip_call(), and update_call_counter().

#define INITIAL_CSEQ   101

Our initial sip sequence number

Definition at line 550 of file chan_sip.c.

Referenced by sip_alloc(), sip_register(), and transmit_response_using_temp().

#define IS_SIP_TECH (   t)    ((t) == &sip_tech || (t) == &sip_tech_info)
#define MAX_AUTHTRIES   3

Try authentication three times, then fail

Definition at line 543 of file chan_sip.c.

Referenced by handle_response(), handle_response_invite(), and handle_response_register().

#define MAX_HISTORY_ENTRIES   50

Max entires in the history list for a sip_pvt

Definition at line 548 of file chan_sip.c.

Referenced by append_history_va().

#define MAX_RETRANS   6

Try only 6 times for retransmissions, a total of 7 transmissions

Definition at line 536 of file chan_sip.c.

Referenced by retrans_pkt().

#define NO_RTP   0

Definition at line 576 of file chan_sip.c.

#define NOT_SUPPORTED   0

Definition at line 870 of file chan_sip.c.

#define PROVIS_KEEPALIVE_TIMEOUT   60000

How long to wait before retransmitting a provisional response (rfc 3261 13.3.1.1)

Definition at line 542 of file chan_sip.c.

Referenced by send_provisional_keepalive_full(), and update_provisional_keepalive().

#define REQ_OFFSET_TO_STR (   req,
  offset 
)    (ast_str_buffer((req)->data) + ((req)->offset))
#define RTP   1

Definition at line 575 of file chan_sip.c.

#define SDP_MAX_RTPMAP_CODECS   32

Maximum number of codecs allowed in received SDP

Definition at line 555 of file chan_sip.c.

Referenced by process_sdp_a_audio(), process_sdp_a_text(), and process_sdp_a_video().

#define SIP_CALL_LIMIT   (1 << 7)

D: Call limit enforced for this call

Definition at line 1327 of file chan_sip.c.

Referenced by check_peer_ok(), create_addr_from_peer(), and update_call_counter().

#define SIP_DEFER_BYE_ON_TRANSFER   (1 << 10)

D: Do not hangup at first ast_hangup

Definition at line 1330 of file chan_sip.c.

Referenced by handle_invite_replaces(), handle_request_refer(), local_attended_transfer(), sip_hangup(), and sip_set_rtp_peer().

#define SIP_DIRECT_MEDIA   (1 << 20)

DP: allow peers to be reinvited to send media directly p2p

Definition at line 1355 of file chan_sip.c.

Referenced by _sip_show_peer(), handle_common_options(), reload_config(), sip_get_rtp_peer(), sip_get_trtp_peer(), sip_get_udptl_peer(), and sip_get_vrtp_peer().

#define SIP_DIRECT_MEDIA_NAT   (2 << 20)

DP: allow media reinvite when new peer is behind NAT

Definition at line 1356 of file chan_sip.c.

Referenced by handle_common_options(), sip_get_rtp_peer(), and sip_set_rtp_peer().

#define SIP_DTMF_AUTO   (3 << 15)

DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF

Definition at line 1342 of file chan_sip.c.

Referenced by check_peer_ok(), create_addr_from_peer(), handle_common_options(), process_sdp(), sip_alloc(), and sip_new().

#define SIP_DTMF_INBAND   (1 << 15)

DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband"

Definition at line 1340 of file chan_sip.c.

Referenced by handle_common_options(), process_sdp(), sip_dtmfmode(), sip_new(), sip_rtp_read(), sip_senddigit_begin(), and sip_senddigit_end().

#define SIP_DTMF_INFO   (2 << 15)

DP: DTMF Support: SIP Info messages - "info"

Definition at line 1341 of file chan_sip.c.

Referenced by handle_common_options(), sip_dtmfmode(), sip_new(), and sip_senddigit_end().

#define SIP_DTMF_RFC2833   (0 << 15)
#define SIP_DTMF_SHORTINFO   (4 << 15)

DP: DTMF Support: SIP Info messages - "info" - short variant

Definition at line 1343 of file chan_sip.c.

Referenced by handle_common_options(), sip_dtmfmode(), sip_new(), sip_senddigit_end(), and transmit_info_with_digit().

#define SIP_FLAGS_TO_COPY
#define SIP_G726_NONSTANDARD   (1 << 31)

DP: Use non-standard packing for G726-32 data

Definition at line 1372 of file chan_sip.c.

Referenced by add_codec_to_sdp(), handle_common_options(), and process_sdp_a_audio().

#define SIP_GOTREFER   (1 << 6)

D: Got a refer?

Definition at line 1326 of file chan_sip.c.

Referenced by handle_request_refer(), local_attended_transfer(), sip_set_rtp_peer(), and sip_set_udptl_peer().

#define SIP_INC_COUNT   (1 << 8)

D: Did this dialog increment the counter of in-use calls?

Definition at line 1328 of file chan_sip.c.

Referenced by __sip_destroy(), handle_request_cancel(), sip_hangup(), and update_call_counter().

#define SIP_INC_RINGING   (1 << 9)

D: Did this connection increment the counter of in-use calls?

Definition at line 1329 of file chan_sip.c.

Referenced by update_call_counter().

#define SIP_INSECURE   (3 << 23)

DP: three settings, uses two bits

Definition at line 1360 of file chan_sip.c.

Referenced by _sip_show_peer(), and handle_common_options().

#define SIP_INSECURE_INVITE   (1 << 24)

DP: don't require authentication for incoming INVITEs

Definition at line 1363 of file chan_sip.c.

Referenced by check_peer_ok(), and set_insecure_flags().

#define SIP_INSECURE_NONE   (0 << 23)

DP: secure mode

Definition at line 1361 of file chan_sip.c.

#define SIP_INSECURE_PORT   (1 << 23)

DP: don't require matching port for incoming requests

Definition at line 1362 of file chan_sip.c.

Referenced by find_peer(), get_insecure_variable_from_config(), peer_ipcmp_cb(), and set_insecure_flags().

#define SIP_MAX_HEADERS   64

Max amount of SIP headers to read

Definition at line 545 of file chan_sip.c.

Referenced by add_header(), and parse_request().

#define SIP_MAX_LINES   256

Max amount of lines in SIP attachment (like SDP)

Definition at line 546 of file chan_sip.c.

Referenced by parse_request().

#define SIP_MIN_PACKET   4096

Initialize size of memory to allocate for packets

Definition at line 547 of file chan_sip.c.

Referenced by _sip_tcp_helper_thread(), init_req(), init_resp(), and sipsock_read().

#define SIP_NAT_ALWAYS   (3 << 18)

DP: NAT Both ROUTE and RFC3581

Definition at line 1350 of file chan_sip.c.

Referenced by copy_via_headers(), and handle_common_options().

#define SIP_NAT_NEVER   (0 << 18)

DP: No nat support

Definition at line 1347 of file chan_sip.c.

Referenced by handle_common_options().

#define SIP_NAT_RFC3581   (1 << 18)

DP: NAT RFC3581

Definition at line 1348 of file chan_sip.c.

Referenced by build_via(), copy_via_headers(), handle_common_options(), and reload_config().

#define SIP_NEEDREINVITE   (1 << 4)

D: Do we need to send another reinvite?

Definition at line 1324 of file chan_sip.c.

Referenced by check_pendings(), interpret_t38_parameters(), sip_hangup(), sip_reinvite_retry(), sip_sendhtml(), sip_set_rtp_peer(), and sip_set_udptl_peer().

#define SIP_OPT_100REL   (1 << 1)

Definition at line 874 of file chan_sip.c.

#define SIP_OPT_EARLY_SESSION   (1 << 3)

Definition at line 876 of file chan_sip.c.

#define SIP_OPT_EVENTLIST   (1 << 11)

Definition at line 884 of file chan_sip.c.

#define SIP_OPT_FROMCHANGE   (1 << 17)

Definition at line 890 of file chan_sip.c.

#define SIP_OPT_GRUU   (1 << 12)

Definition at line 885 of file chan_sip.c.

#define SIP_OPT_HISTINFO   (1 << 15)

Definition at line 888 of file chan_sip.c.

#define SIP_OPT_JOIN   (1 << 4)

Definition at line 877 of file chan_sip.c.

#define SIP_OPT_NOREFERSUB   (1 << 14)

Definition at line 887 of file chan_sip.c.

#define SIP_OPT_OUTBOUND   (1 << 20)

Definition at line 893 of file chan_sip.c.

#define SIP_OPT_PATH   (1 << 5)

Definition at line 878 of file chan_sip.c.

#define SIP_OPT_PRECONDITION   (1 << 7)

Definition at line 880 of file chan_sip.c.

#define SIP_OPT_PREF   (1 << 6)

Definition at line 879 of file chan_sip.c.

#define SIP_OPT_PRIVACY   (1 << 8)

Definition at line 881 of file chan_sip.c.

#define SIP_OPT_RECLISTINV   (1 << 18)

Definition at line 891 of file chan_sip.c.

#define SIP_OPT_RECLISTSUB   (1 << 19)

Definition at line 892 of file chan_sip.c.

#define SIP_OPT_REPLACES   (1 << 0)

Definition at line 873 of file chan_sip.c.

Referenced by handle_request_invite().

#define SIP_OPT_RESPRIORITY   (1 << 16)

Definition at line 889 of file chan_sip.c.

#define SIP_OPT_SDP_ANAT   (1 << 9)

Definition at line 882 of file chan_sip.c.

#define SIP_OPT_SEC_AGREE   (1 << 10)

Definition at line 883 of file chan_sip.c.

#define SIP_OPT_TARGET_DIALOG   (1 << 13)

Definition at line 886 of file chan_sip.c.

#define SIP_OPT_TIMER   (1 << 2)

Definition at line 875 of file chan_sip.c.

Referenced by handle_request_invite().

#define SIP_OPT_UNKNOWN   (1 << 21)

Definition at line 894 of file chan_sip.c.

Referenced by parse_sip_options().

#define SIP_PAGE2_ALLOWOVERLAP   (1 << 17)

DP: Allow overlap dialing ?

Definition at line 1396 of file chan_sip.c.

Referenced by _sip_show_peer(), get_destination(), handle_common_options(), handle_request_invite(), reload_config(), and sip_show_settings().

#define SIP_PAGE2_ALLOWSUBSCRIBE   (1 << 16)

GP: Allow subscriptions from this peer?

Definition at line 1395 of file chan_sip.c.

Referenced by _sip_show_peer(), build_peer(), handle_common_options(), handle_request_subscribe(), reload_config(), and sip_show_settings().

#define SIP_PAGE2_BUGGY_MWI   (1 << 26)

DP: Buggy CISCO MWI fix

Definition at line 1411 of file chan_sip.c.

Referenced by handle_common_options(), and transmit_notify_with_mwi().

#define SIP_PAGE2_CALL_ONHOLD   (3 << 23)
#define SIP_PAGE2_CALL_ONHOLD_ACTIVE   (1 << 23)

D: Active hold

Definition at line 1406 of file chan_sip.c.

Referenced by change_hold_state().

#define SIP_PAGE2_CALL_ONHOLD_INACTIVE   (3 << 23)

D: Inactive hold

Definition at line 1408 of file chan_sip.c.

Referenced by add_sdp(), and change_hold_state().

#define SIP_PAGE2_CALL_ONHOLD_ONEDIR   (2 << 23)

D: One directional hold

Definition at line 1407 of file chan_sip.c.

Referenced by add_sdp(), and change_hold_state().

#define SIP_PAGE2_DIALOG_ESTABLISHED   (1 << 27)
#define SIP_PAGE2_FAX_DETECT   (3 << 28)

DP: Fax Detection support

Definition at line 1413 of file chan_sip.c.

Referenced by handle_common_options(), reload_config(), sip_new(), and sip_rtp_read().

#define SIP_PAGE2_FAX_DETECT_BOTH   (3 << 28)

DP: Fax Detection support - detect both

Definition at line 1416 of file chan_sip.c.

Referenced by handle_common_options().

#define SIP_PAGE2_FAX_DETECT_CNG   (1 << 28)

DP: Fax Detection support - detect CNG in audio

Definition at line 1414 of file chan_sip.c.

Referenced by handle_common_options(), and sip_read().

#define SIP_PAGE2_FAX_DETECT_T38   (2 << 28)

DP: Fax Detection support - detect T.38 reinvite from peer

Definition at line 1415 of file chan_sip.c.

Referenced by handle_common_options(), process_sdp(), and sip_call().

#define SIP_PAGE2_FORWARD_LOOP_DETECTED   (1 << 8)

31: Do call forward when receiving 482 Loop Detected

Definition at line 1389 of file chan_sip.c.

Referenced by _sip_show_peer(), handle_response(), handle_t38_options(), reload_config(), and sip_show_settings().

#define SIP_PAGE2_HAVEPEERCONTEXT   (1 << 3)

Definition at line 1387 of file chan_sip.c.

Referenced by build_peer(), and get_destination().

#define SIP_PAGE2_IGNORESDPVERSION   (1 << 19)

GDP: Ignore the SDP session version number we receive and treat all sessions as new

Definition at line 1398 of file chan_sip.c.

Referenced by _sip_show_peer(), handle_common_options(), process_sdp_o(), reload_config(), and sip_show_settings().

#define SIP_PAGE2_REGISTERTRYING   (1 << 29)

DP: Send 100 Trying on REGISTER attempts

Definition at line 1417 of file chan_sip.c.

Referenced by _sip_show_peer(), build_peer(), and register_verify().

#define SIP_PAGE2_RFC2833_COMPENSATE   (1 << 25)

DP: Compensate for buggy RFC2833 implementations

Definition at line 1410 of file chan_sip.c.

Referenced by create_addr_from_peer(), handle_common_options(), handle_request_invite(), process_sdp(), sip_alloc(), and sip_show_settings().

#define SIP_PAGE2_RPORT_PRESENT   (1 << 10)

Was rport received in the Via header?

Definition at line 1392 of file chan_sip.c.

Referenced by check_user_full(), and check_via().

#define SIP_PAGE2_RTAUTOCLEAR   (1 << 2)

GP: Should we clean memory from peers after expiry?

Definition at line 1386 of file chan_sip.c.

Referenced by expire_register(), realtime_peer(), reload_config(), and sip_show_settings().

#define SIP_PAGE2_RTCACHEFRIENDS   (1 << 0)

GP: Should we keep RT objects in memory for extended time?

Definition at line 1385 of file chan_sip.c.

Referenced by build_peer(), parse_register_contact(), realtime_peer(), reload_config(), sip_prune_realtime(), sip_show_settings(), and update_peer().

#define SIP_PAGE2_STATECHANGEQUEUE   (1 << 9)

D: Unsent state pending change exists

Definition at line 1390 of file chan_sip.c.

Referenced by cb_extensionstate(), handle_response(), and handle_response_notify().

#define SIP_PAGE2_SUBSCRIBEMWIONLY   (1 << 18)

GP: Only issue MWI notification if subscribed to

Definition at line 1397 of file chan_sip.c.

Referenced by build_peer(), handle_request_subscribe(), register_verify(), and sip_send_mwi_to_peer().

#define SIP_PAGE2_T38SUPPORT_UDPTL   (1 << 20)

GDP: T.38 Fax Support (no error correction)

Definition at line 1401 of file chan_sip.c.

Referenced by handle_t38_options(), and set_t38_capabilities().

#define SIP_PAGE2_T38SUPPORT_UDPTL_FEC   (2 << 20)

GDP: T.38 Fax Support (FEC error correction)

Definition at line 1402 of file chan_sip.c.

Referenced by handle_t38_options(), and set_t38_capabilities().

#define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY   (3 << 20)

GDP: T.38 Fax Support (redundancy error correction)

Definition at line 1403 of file chan_sip.c.

Referenced by handle_t38_options(), and set_t38_capabilities().

#define SIP_PAGE2_TEXTSUPPORT   (1 << 15)
#define SIP_PAGE2_UDPTL_DESTINATION   (1 << 30)

DP: Use source IP of RTP as destination if NAT is enabled

Definition at line 1418 of file chan_sip.c.

Referenced by handle_t38_options(), and process_sdp().

#define SIP_PAGE2_VIDEOSUPPORT   (1 << 14)
#define SIP_PAGE2_VIDEOSUPPORT_ALWAYS   (1 << 31)

DP: Always set up video, even if endpoints don't support it

Definition at line 1419 of file chan_sip.c.

Referenced by _sip_show_peer(), check_peer_ok(), create_addr_from_peer(), handle_common_options(), reload_config(), and sip_alloc().

#define SIP_PENDINGBYE   (1 << 5)
#define SIP_PROG_INBAND   (3 << 25)

DP: three settings, uses two bits

Definition at line 1366 of file chan_sip.c.

Referenced by handle_common_options(), sip_indicate(), and sip_show_settings().

#define SIP_PROG_INBAND_NEVER   (0 << 25)

Definition at line 1367 of file chan_sip.c.

Referenced by sip_indicate(), and sip_show_settings().

#define SIP_PROG_INBAND_NO   (1 << 25)

Definition at line 1368 of file chan_sip.c.

Referenced by handle_common_options(), and sip_show_settings().

#define SIP_PROG_INBAND_YES   (2 << 25)

Definition at line 1369 of file chan_sip.c.

Referenced by handle_common_options(), and sip_indicate().

#define SIP_PROGRESS_SENT   (1 << 3)

D: Have sent 183 message progress

Definition at line 1323 of file chan_sip.c.

Referenced by sip_indicate(), and sip_write().

#define SIP_PROMISCREDIR   (1 << 11)

DP: Promiscuous redirection

Definition at line 1332 of file chan_sip.c.

Referenced by _sip_show_peer(), handle_common_options(), parse_moved_contact(), sip_show_channel(), and sip_show_settings().

#define sip_pvt_trylock (   x)    ao2_trylock(x)

Definition at line 1748 of file chan_sip.c.

Referenced by dialog_needdestroy(), find_call(), and sip_hangup().

#define SIP_REINVITE   (7 << 20)

DP: four settings, uses three bits

Definition at line 1353 of file chan_sip.c.

Referenced by handle_common_options().

#define SIP_REINVITE_NONE   (0 << 20)

DP: no reinvite allowed

Definition at line 1354 of file chan_sip.c.

#define SIP_REINVITE_UPDATE   (4 << 20)

DP: use UPDATE (RFC3311) when reinviting this peer

Definition at line 1357 of file chan_sip.c.

Referenced by handle_common_options(), and transmit_reinvite_with_sdp().

#define SIP_RESERVED   ";/?:@&=+$,# "

Reserved characters in the username part of the URI

Definition at line 493 of file chan_sip.c.

#define SIP_RINGING   (1 << 2)

D: Have sent 180 ringing

Definition at line 1322 of file chan_sip.c.

Referenced by sip_indicate().

#define SIP_SENDRPID   (1 << 29)

DP: Remote Party-ID Support

Definition at line 1371 of file chan_sip.c.

Referenced by _sip_show_peer(), handle_common_options(), and initreqprep().

#define SIP_TRANS_TIMEOUT   64 * DEFAULT_TIMER_T1

SIP request timeout (rfc 3261) 64*T1

Todo:
Use known T1 for timeout (peerpoke)

Definition at line 538 of file chan_sip.c.

Referenced by manager_sipnotify(), sip_cli_notify(), and sip_sipredirect().

#define SIP_TRUSTRPID   (1 << 12)

DP: Trust RPID headers?

Definition at line 1333 of file chan_sip.c.

Referenced by _sip_show_peer(), handle_common_options(), and replace_cid().

#define SIP_USECLIENTCODE   (1 << 14)

DP: Trust X-ClientCode info message

Definition at line 1335 of file chan_sip.c.

Referenced by handle_common_options(), handle_request_info(), and sip_show_settings().

#define SIP_USEREQPHONE   (1 << 13)

DP: Add user=phone to numeric URI. Default off

Definition at line 1334 of file chan_sip.c.

Referenced by _sip_show_peer(), build_peer(), initreqprep(), reload_config(), and sip_show_settings().

#define STANDARD_TLS_PORT   5061

Standard SIP TLS port from RFC 3261. DO NOT CHANGE THIS.

Definition at line 960 of file chan_sip.c.

Referenced by __set_address_from_contact(), build_peer(), create_addr(), parse_register_contact(), reload_config(), set_destination(), sip_parse_host(), sip_register(), and sip_standard_port().

#define SUPPORTED   1

Define SIP option tags, used in Require: and Supported: headers We need to be aware of these properties in the phones to use the replace: header. We should not do that without knowing that the other end supports it... This is nothing we can configure, we learn by the dialog Supported: header on the REGISTER (peer) or the INVITE (other devices) We are not using many of these today, but will in the future. This is documented in RFC 3261

Definition at line 869 of file chan_sip.c.

#define TRUE   1

Definition at line 481 of file chan_sip.c.

Referenced by __sip_ack(), __sip_autodestruct(), __sip_destroy(), __sip_semi_ack(), __sip_subscribe_mwi_do(), _sip_qualify_peer(), _sip_show_peer(), _sip_show_peers(), add_sdp(), build_peer(), build_rpid(), check_auth(), check_peer_ok(), check_pendings(), create_addr(), dialog_needdestroy(), find_sdp(), function_sippeer(), get_sip_pvt_byid_locked(), handle_request_info(), handle_request_invite(), handle_request_notify(), handle_request_refer(), handle_request_subscribe(), handle_response_invite(), handle_response_peerpoke(), interpret_t38_parameters(), local_attended_transfer(), manager_sipnotify(), parse_ok_contact(), parse_register_contact(), parse_sip_options(), proc_session_timer(), process_sdp(), process_sdp_a_audio(), process_sdp_a_image(), process_sdp_a_sendonly(), process_sdp_a_text(), process_sdp_a_video(), process_sdp_c(), process_sdp_o(), proxy_update(), realtime_peer(), reg_source_db(), register_verify(), reload_config(), reqprep(), respprep(), restart_session_timer(), set_destination(), sip_addheader(), sip_alloc(), sip_cli_notify(), sip_destroy(), sip_destroy_peer(), sip_devicestate(), sip_do_debug_peer(), sip_hangup(), sip_indicate(), sip_park_thread(), sip_poke_noanswer(), sip_poke_peer(), sip_prune_realtime(), sip_registry_destroy(), sip_reload(), sip_request_call(), sip_scheddestroy(), sip_send_mwi_to_peer(), sip_set_history(), sip_set_udptl_peer(), sip_show_channel(), sip_show_inuse(), sip_show_user(), sip_show_users(), sip_unregister(), sip_write(), st_get_mode(), st_get_refresher(), st_get_se(), stop_session_timer(), temp_peer(), transmit_invite(), transmit_refer(), transmit_register(), transmit_reinvite_with_sdp(), transmit_response_with_sdp(), unload_module(), and update_call_counter().

#define UNLINK (   element,
  head,
  prev 
)

some list management macros.

Definition at line 2240 of file chan_sip.c.

Referenced by __sip_ack(), handle_request_cancel(), and retrans_pkt().

#define XMIT_ERROR   -2

Enumeration Type Documentation

States whether a SIP message can create a dialog in Asterisk.

Enumerator:
CAN_NOT_CREATE_DIALOG 
CAN_CREATE_DIALOG 
CAN_CREATE_DIALOG_UNSUPPORTED_METHOD 

Definition at line 785 of file chan_sip.c.

Authentication result from check_auth* functions.

Enumerator:
AUTH_DONT_KNOW 

no result, need to check further

AUTH_SUCCESSFUL 
AUTH_CHALLENGE_SENT 
AUTH_SECRET_FAILED 
AUTH_USERNAME_MISMATCH 
AUTH_NOT_FOUND 

returned by register_verify

AUTH_FAKE_AUTH 
AUTH_UNKNOWN_DOMAIN 
AUTH_PEER_NOT_DYNAMIC 
AUTH_ACL_FAILED 
AUTH_BAD_TRANSPORT 

Definition at line 685 of file chan_sip.c.

                       {
   AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
      /* XXX maybe this is the same as AUTH_NOT_FOUND */

   AUTH_SUCCESSFUL = 0,
   AUTH_CHALLENGE_SENT = 1,
   AUTH_SECRET_FAILED = -1,
   AUTH_USERNAME_MISMATCH = -2,
   AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
   AUTH_FAKE_AUTH = -4,
   AUTH_UNKNOWN_DOMAIN = -5,
   AUTH_PEER_NOT_DYNAMIC = -6,
   AUTH_ACL_FAILED = -7,
   AUTH_BAD_TRANSPORT = -8,
};

Modes for SIP domain handling in the PBX.

Enumerator:
SIP_DOMAIN_AUTO 

This domain is auto-configured

SIP_DOMAIN_CONFIG 

This domain is from configuration

Definition at line 1275 of file chan_sip.c.

                 {
   SIP_DOMAIN_AUTO,     /*!< This domain is auto-configured */
   SIP_DOMAIN_CONFIG,      /*!< This domain is from configuration */
};

States for the INVITE transaction, not the dialog.

Note:
this is for the INVITE that sets up the dialog
Enumerator:
INV_NONE 

No state at all, maybe not an INVITE dialog

INV_CALLING 

Invite sent, no answer

INV_PROCEEDING 

We got/sent 1xx message

INV_EARLY_MEDIA 

We got 18x message with to-tag back

INV_COMPLETED 

Got final response with error. Wait for ACK, then CONFIRMED

INV_CONFIRMED 

Confirmed response - we've got an ack (Incoming calls only)

INV_TERMINATED 

Transaction done - either successful (AST_STATE_UP) or failed, but done The only way out of this is a BYE from one side

INV_CANCELLED 

Transaction cancelled by client or server in non-terminated state

Definition at line 597 of file chan_sip.c.

                  {
   INV_NONE = 0,          /*!< No state at all, maybe not an INVITE dialog */
   INV_CALLING = 1,  /*!< Invite sent, no answer */
   INV_PROCEEDING = 2,  /*!< We got/sent 1xx message */
   INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
   INV_COMPLETED = 4,   /*!< Got final response with error. Wait for ACK, then CONFIRMED */
   INV_CONFIRMED = 5,   /*!< Confirmed response - we've got an ack (Incoming calls only) */
   INV_TERMINATED = 6,  /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
                 The only way out of this is a BYE from one side */
   INV_CANCELLED = 7,   /*!< Transaction cancelled by client or server in non-terminated state */
};
enum media_type
Enumerator:
SDP_AUDIO 
SDP_VIDEO 
SDP_IMAGE 
SDP_TEXT 

Definition at line 8427 of file chan_sip.c.

Settings for the 'notifycid' option, see sip.conf.sample for details.

Enumerator:
DISABLED 
ENABLED 
IGNORE_CONTEXT 

Definition at line 822 of file chan_sip.c.

                       {
   DISABLED       = 0,
   ENABLED        = 1,
   IGNORE_CONTEXT = 2,
};

Results from the parse_register() function.

Enumerator:
PARSE_REGISTER_DENIED 
PARSE_REGISTER_FAILED 
PARSE_REGISTER_UPDATE 
PARSE_REGISTER_QUERY 

Definition at line 636 of file chan_sip.c.

Parameters to know status of transfer.

Enumerator:
REFER_IDLE 

No REFER is in progress

REFER_SENT 

Sent REFER to transferee

REFER_RECEIVED 

Received REFER from transferrer

REFER_CONFIRMED 

Refer confirmed with a 100 TRYING (unused)

REFER_ACCEPTED 

Accepted by transferee

REFER_RINGING 

Target Ringing

REFER_200OK 

Answered by transfer target

REFER_FAILED 

REFER declined - go on

REFER_NOAUTH 

We had no auth for REFER

Definition at line 1466 of file chan_sip.c.

                 {
   REFER_IDLE,                    /*!< No REFER is in progress */
   REFER_SENT,                    /*!< Sent REFER to transferee */
   REFER_RECEIVED,                /*!< Received REFER from transferrer */
   REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
   REFER_ACCEPTED,                /*!< Accepted by transferee */
   REFER_RINGING,                 /*!< Target Ringing */
   REFER_200OK,                   /*!< Answered by transfer target */
   REFER_FAILED,                  /*!< REFER declined - go on */
   REFER_NOAUTH                   /*!< We had no auth for REFER */
};

Authentication types - proxy or www authentication.

Note:
Endpoints, like Asterisk, should always use WWW authentication to allow multiple authentications in the same call - to the proxy and to the end point.
Enumerator:
PROXY_AUTH 
WWW_AUTH 

Definition at line 679 of file chan_sip.c.

                   {
   PROXY_AUTH = 407,
   WWW_AUTH = 401,
};

debugging state We store separately the debugging requests from the config file and requests from the CLI. Debugging is enabled if either is set (which means that if sipdebug is set in the config file, we can only turn it off by reloading the config).

Enumerator:
sip_debug_none 
sip_debug_config 
sip_debug_console 

Definition at line 1436 of file chan_sip.c.

Enumerator:
SIP_TYPE_PEER 
SIP_TYPE_USER 

Definition at line 1830 of file chan_sip.c.

                   {
   SIP_TYPE_PEER = (1 << 0),
   SIP_TYPE_USER = (1 << 1),
};
enum sip_result

The result of a lot of functions.

Enumerator:
AST_SUCCESS 

FALSE means success, funny enough

AST_FAILURE 

Failure code

Definition at line 589 of file chan_sip.c.

                {
   AST_SUCCESS = 0,     /*!< FALSE means success, funny enough */
   AST_FAILURE = -1,    /*!< Failure code */
};
Enumerator:
TCPTLS_ALERT_DATA 

There is new data to be sent out.

TCPTLS_ALERT_STOP 

A request to stop the tcp_handler thread.

Definition at line 1976 of file chan_sip.c.

                      {
   /*! \brief There is new data to be sent out */
   TCPTLS_ALERT_DATA,
   /*! \brief A request to stop the tcp_handler thread */
   TCPTLS_ALERT_STOP,
};

Define some implemented SIP transports.

Note:
Asterisk does not support SCTP or UDP/DTLS
Enumerator:
SIP_TRANSPORT_UDP 

Unreliable transport for SIP, needs retransmissions

SIP_TRANSPORT_TCP 

Reliable, but unsecure

SIP_TRANSPORT_TLS 

TCP/TLS - reliable and secure transport for signalling

Definition at line 754 of file chan_sip.c.

                   {
   SIP_TRANSPORT_UDP = 1,     /*!< Unreliable transport for SIP, needs retransmissions */
   SIP_TRANSPORT_TCP = 1 << 1,   /*!< Reliable, but unsecure */
   SIP_TRANSPORT_TLS = 1 << 2,   /*!< TCP/TLS - reliable and secure transport for signalling */
};
enum sipmethod

SIP Request methods known by Asterisk.

Note:
Do _NOT_ make any changes to this enum, or the array following it; if you think you are doing the right thing, you are probably not doing the right thing. If you think there are changes needed, get someone else to review them first _before_ submitting a patch. If these two lists do not match properly bad things will happen.
Enumerator:
SIP_UNKNOWN 

Unknown response

SIP_RESPONSE 

Not request, response to outbound request

SIP_REGISTER 

Registration to the mothership, tell us where you are located

SIP_OPTIONS 

Check capabilities of a device, used for "ping" too

SIP_NOTIFY 

Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER

SIP_INVITE 

Set up a session

SIP_ACK 

End of a three-way handshake started with INVITE.

SIP_PRACK 

Reliable pre-call signalling. Not supported in Asterisk.

SIP_BYE 

End of a session

SIP_REFER 

Refer to another URI (transfer)

SIP_SUBSCRIBE 

Subscribe for updates (voicemail, session status, device status, presence)

SIP_MESSAGE 

Text messaging

SIP_UPDATE 

Update a dialog. We can send UPDATE; but not accept it

SIP_INFO 

Information updates during a session

SIP_CANCEL 

Cancel an INVITE

SIP_PUBLISH 

Not supported in Asterisk

SIP_PING 

Not supported at all, no standard but still implemented out there

Definition at line 801 of file chan_sip.c.

               {
   SIP_UNKNOWN,      /*!< Unknown response */
   SIP_RESPONSE,     /*!< Not request, response to outbound request */
   SIP_REGISTER,     /*!< Registration to the mothership, tell us where you are located */
   SIP_OPTIONS,      /*!< Check capabilities of a device, used for "ping" too */
   SIP_NOTIFY,    /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
   SIP_INVITE,    /*!< Set up a session */
   SIP_ACK,    /*!< End of a three-way handshake started with INVITE. */
   SIP_PRACK,     /*!< Reliable pre-call signalling. Not supported in Asterisk. */
   SIP_BYE,    /*!< End of a session */
   SIP_REFER,     /*!< Refer to another URI (transfer) */
   SIP_SUBSCRIBE,    /*!< Subscribe for updates (voicemail, session status, device status, presence) */
   SIP_MESSAGE,      /*!< Text messaging */
   SIP_UPDATE,    /*!< Update a dialog. We can send UPDATE; but not accept it */
   SIP_INFO,      /*!< Information updates during a session */
   SIP_CANCEL,    /*!< Cancel an INVITE */
   SIP_PUBLISH,      /*!< Not supported in Asterisk */
   SIP_PING,      /*!< Not supported at all, no standard but still implemented out there */
};

States for outbound registrations (with register= lines in sip.conf.

Enumerator:
REG_STATE_UNREGISTERED 

We are not registered

Note:
Initial state. We should have a timeout scheduled for the initial (or next) registration transmission, calling sip_reregister
REG_STATE_REGSENT 

Registration request sent

Note:
sent initial request, waiting for an ack or a timeout to retransmit the initial request.
REG_STATE_AUTHSENT 

We have tried to authenticate

Note:
entered after transmit_register with auth info, waiting for an ack.
REG_STATE_REGISTERED 

Registered and done

REG_STATE_REJECTED 

Registration rejected *

Note:
only used when the remote party has an expire larger than our max-expire. This is a final state from which we do not recover (not sure how correctly).
REG_STATE_TIMEOUT 

Registration timed out *

Note:
XXX unused
REG_STATE_NOAUTH 

We have no accepted credentials

Note:
fatal - no chance to proceed
REG_STATE_FAILED 

Registration failed after several tries

Note:
fatal - no chance to proceed

Definition at line 702 of file chan_sip.c.

                      {
   REG_STATE_UNREGISTERED = 0,   /*!< We are not registered 
       *  \note Initial state. We should have a timeout scheduled for the initial
       * (or next) registration transmission, calling sip_reregister
       */

   REG_STATE_REGSENT,   /*!< Registration request sent 
       * \note sent initial request, waiting for an ack or a timeout to
       * retransmit the initial request.
      */

   REG_STATE_AUTHSENT,  /*!< We have tried to authenticate 
       * \note entered after transmit_register with auth info,
       * waiting for an ack.
       */

   REG_STATE_REGISTERED,   /*!< Registered and done */

   REG_STATE_REJECTED,  /*!< Registration rejected *
       * \note only used when the remote party has an expire larger than
       * our max-expire. This is a final state from which we do not
       * recover (not sure how correctly).
       */

   REG_STATE_TIMEOUT,   /*!< Registration timed out *
      * \note XXX unused */

   REG_STATE_NOAUTH, /*!< We have no accepted credentials
       * \note fatal - no chance to proceed */

   REG_STATE_FAILED, /*!< Registration failed after several tries
       * \note fatal - no chance to proceed */
};
enum st_mode

Modes in which Asterisk can be configured to run SIP Session-Timers.

Enumerator:
SESSION_TIMER_MODE_INVALID 

Invalid value

SESSION_TIMER_MODE_ACCEPT 

Honor inbound Session-Timer requests

SESSION_TIMER_MODE_ORIGINATE 

Originate outbound and honor inbound requests

SESSION_TIMER_MODE_REFUSE 

Ignore inbound Session-Timers requests

Definition at line 737 of file chan_sip.c.

             {
        SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */ 
        SESSION_TIMER_MODE_ACCEPT,      /*!< Honor inbound Session-Timer requests */
        SESSION_TIMER_MODE_ORIGINATE,   /*!< Originate outbound and honor inbound requests */
        SESSION_TIMER_MODE_REFUSE       /*!< Ignore inbound Session-Timers requests */
};

The entity playing the refresher role for Session-Timers.

Enumerator:
SESSION_TIMER_REFRESHER_AUTO 

Negotiated

SESSION_TIMER_REFRESHER_UAC 

Session is refreshed by the UAC

SESSION_TIMER_REFRESHER_UAS 

Session is refreshed by the UAS

Definition at line 745 of file chan_sip.c.

                  {
        SESSION_TIMER_REFRESHER_AUTO,    /*!< Negotiated                      */
        SESSION_TIMER_REFRESHER_UAC,     /*!< Session is refreshed by the UAC */
        SESSION_TIMER_REFRESHER_UAS      /*!< Session is refreshed by the UAS */
};

Type of subscription, based on the packages we do support, see subscription_types.

Enumerator:
NONE 
XPIDF_XML 
DIALOG_INFO_XML 
CPIM_PIDF_XML 
PIDF_XML 
MWI_NOTIFICATION 

Definition at line 644 of file chan_sip.c.

Enumerator:
SDP_T38_NONE 

Do not modify T38 information at all

SDP_T38_INITIATE 

Remote side has requested T38 with us

SDP_T38_ACCEPT 

Remote side accepted our T38 request

Definition at line 2247 of file chan_sip.c.

                     {
   SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
   SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
   SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
};
enum t38state

T38 States for a call.

Enumerator:
T38_DISABLED 

Not enabled

T38_LOCAL_REINVITE 

Offered from local - REINVITE

T38_PEER_REINVITE 

Offered from peer - REINVITE

T38_ENABLED 

Negotiated (enabled)

Definition at line 1451 of file chan_sip.c.

              {
   T38_DISABLED = 0,                /*!< Not enabled */
   T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
   T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
   T38_ENABLED                      /*!< Negotiated (enabled) */
};

Authorization scheme for call transfers.

Note:
Not a bitfield flag, since there are plans for other modes, like "only allow transfers for authenticated devices"
Enumerator:
TRANSFER_OPENFORALL 

Allow all SIP transfers

TRANSFER_CLOSED 

Allow no SIP transfers

Definition at line 582 of file chan_sip.c.

                   {
   TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
   TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
};
enum xmittype

When sending a SIP message, we can send with a few options, depending on type of SIP request. UNRELIABLE is moslty used for responses to repeated requests, where the original response would be sent RELIABLE in an INVITE transaction.

Enumerator:
XMIT_CRITICAL 

Transmit critical SIP message reliably, with re-transmits. If it fails, it's critical and will cause a teardown of the session

XMIT_RELIABLE 

Transmit SIP message reliably, with re-transmits

XMIT_UNRELIABLE 

Transmit SIP message without bothering with re-transmits

Definition at line 628 of file chan_sip.c.

              {
   XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
                                              If it fails, it's critical and will cause a teardown of the session */
   XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
   XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
};

Function Documentation

static const char * __get_header ( const struct sip_request req,
const char *  name,
int *  start 
) [static]

Definition at line 7154 of file chan_sip.c.

References ast_skip_blanks(), find_alias(), sip_request::header, sip_request::headers, sip_request::len, pass, sip_settings::pedanticsipchecking, REQ_OFFSET_TO_STR, and sip_cfg.

Referenced by build_route(), copy_all_header(), copy_via_headers(), func_header_read(), get_header(), handle_incoming(), handle_request_subscribe(), handle_response_register(), and parse_register_contact().

{
   int pass;

   /*
    * Technically you can place arbitrary whitespace both before and after the ':' in
    * a header, although RFC3261 clearly says you shouldn't before, and place just
    * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
    * a good idea to say you can do it, and if you can do it, why in the hell would.
    * you say you shouldn't.
    * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
    * and we always allow spaces after that for compatibility.
    */
   for (pass = 0; name && pass < 2;pass++) {
      int x, len = strlen(name);
      for (x = *start; x < req->headers; x++) {
         char *header = REQ_OFFSET_TO_STR(req, header[x]);
         if (!strncasecmp(header, name, len)) {
            char *r = header + len; /* skip name */
            if (sip_cfg.pedanticsipchecking)
               r = ast_skip_blanks(r);

            if (*r == ':') {
               *start = x+1;
               return ast_skip_blanks(r+1);
            }
         }
      }
      if (pass == 0) /* Try aliases */
         name = find_alias(name, NULL);
   }

   /* Don't return NULL, so get_header is always a valid pointer */
   return "";
}
static void __reg_module ( void  ) [static]

Definition at line 26679 of file chan_sip.c.

static int __set_address_from_contact ( const char *  fullcontact,
struct sockaddr_in *  sin,
int  tcp 
) [static]

Definition at line 12663 of file chan_sip.c.

References ast_copy_string(), ast_gethostbyname(), ast_log(), get_transport_str2enum(), hp, LOG_WARNING, parse_uri(), port_str2int(), SIP_TRANSPORT_TLS, STANDARD_SIP_PORT, and STANDARD_TLS_PORT.

Referenced by build_peer(), and set_address_from_contact().

{
   struct hostent *hp;
   struct ast_hostent ahp;
   int port = STANDARD_SIP_PORT;
   char *host, *pt, *transport;
   char contact_buf[256];
   char *contact;

   /* Work on a copy */
   ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
   contact = contact_buf;

   /* 
    * We have only the part in <brackets> here so we just need to parse a SIP URI.
    *
    * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
    * We still need to be able to send to the remote agent through the proxy.
    */

   if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
      ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
   }

   /* set port */
   if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
      port = port_str2int(pt, STANDARD_TLS_PORT);
   } else {
      port = port_str2int(pt, STANDARD_SIP_PORT);
   }


   /* XXX This could block for a long time XXX */
   /* We should only do this if it's a name, not an IP */
   /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
      to find transport, port address and hostname. If there's a port number, we have to
      assume that the domain part is a host name and only look for an A/AAAA record in DNS.
   */
   hp = ast_gethostbyname(host, &ahp);
   if (!hp)  {
      ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
      return -1;
   }
   sin->sin_family = AF_INET;
   memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
   sin->sin_port = htons(port);

   return 0;
}
static int __sip_ack ( struct sip_pvt p,
int  seqno,
int  resp,
int  sipmethod 
) [static]

Acknowledges receipt of a packet and stops retransmission called with p locked.

Definition at line 4235 of file chan_sip.c.

References ast_debug, ast_free, ast_sched_del(), sip_pvt::callid, sip_pkt::data, dialog_unref(), FALSE, sip_proxy::force, sip_pkt::is_resp, sip_pkt::method, msg, sip_pkt::next, sip_pvt::outboundproxy, sip_pkt::owner, sip_pvt::packets, sip_pvt::pendinginvite, ref_proxy(), sip_pkt::retransid, sip_pkt::seqno, sip_pvt_lock, sip_pvt_unlock, TRUE, and UNLINK.

Referenced by __sip_pretend_ack(), handle_incoming(), handle_request_invite(), and handle_response().

{
   struct sip_pkt *cur, *prev = NULL;
   const char *msg = "Not Found";   /* used only for debugging */
   int res = FALSE;

   /* If we have an outbound proxy for this dialog, then delete it now since
     the rest of the requests in this dialog needs to follow the routing.
     If obforcing is set, we will keep the outbound proxy during the whole
     dialog, regardless of what the SIP rfc says
   */
   if (p->outboundproxy && !p->outboundproxy->force){
      ref_proxy(p, NULL);
   }

   for (cur = p->packets; cur; prev = cur, cur = cur->next) {
      if (cur->seqno != seqno || cur->is_resp != resp)
         continue;
      if (cur->is_resp || cur->method == sipmethod) {
         res = TRUE;
         msg = "Found";
         if (!resp && (seqno == p->pendinginvite)) {
            ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
            p->pendinginvite = 0;
         }
         if (cur->retransid > -1) {
            if (sipdebug)
               ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
         }
         /* This odd section is designed to thwart a 
          * race condition in the packet scheduler. There are
          * two conditions under which deleting the packet from the
          * scheduler can fail.
          *
          * 1. The packet has been removed from the scheduler because retransmission
          * is being attempted. The problem is that if the packet is currently attempting
          * retransmission and we are at this point in the code, then that MUST mean
          * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
          * lock temporarily to allow retransmission.
          *
          * 2. The packet has reached its maximum number of retransmissions and has
          * been permanently removed from the packet scheduler. If this is the case, then
          * the packet's retransid will be set to -1. The atomicity of the setting and checking
          * of the retransid to -1 is ensured since in both cases p's lock is held.
          */
         while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
            sip_pvt_unlock(p);
            usleep(1);
            sip_pvt_lock(p);
         }
         UNLINK(cur, p->packets, prev);
         dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
         if (cur->data)
            ast_free(cur->data);
         ast_free(cur);
         break;
      }
   }
   ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
      p->callid, resp ? "Response" : "Request", seqno, msg);
   return res;
}
static int __sip_autodestruct ( const void *  data) [static]

Kill a SIP dialog (called only by the scheduler) The scheduler has a reference to this dialog when p->autokillid != -1, and we are called using that reference. So if the event is not rescheduled, we need to call dialog_unref().

Definition at line 4121 of file chan_sip.c.

References __sip_pretend_ack(), sip_pvt::alreadygone, append_history, AST_CAUSE_PROTOCOL_ERROR, ast_channel_trylock, ast_channel_unlock, ast_debug, AST_EXTENSION_DEACTIVATED, ast_log(), ast_queue_hangup_with_cause(), sip_pvt::autokillid, sip_pvt::callid, DEFAULT_TRANS_TIMEOUT, dialog_unlink_all(), dialog_unref(), sip_pvt::lastmsg, LOG_WARNING, sip_pvt::method, method_match(), sip_pvt::needdestroy, NONE, sip_pvt::owner, sip_pvt::packets, pvt_set_needdestroy(), sip_pvt::refer, SIP_BYE, SIP_CANCEL, sip_methods, sip_pvt_lock, sip_pvt_unlock, sip_scheddestroy(), sip_pvt::subscribed, cfsip_methods::text, transmit_request_with_auth(), transmit_state_notify(), TRUE, and XMIT_RELIABLE.

Referenced by sip_scheddestroy(), and sip_show_sched().

{
   struct sip_pvt *p = (struct sip_pvt *)data;

   /* If this is a subscription, tell the phone that we got a timeout */
   if (p->subscribed) {
      transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
      p->subscribed = NONE;
      append_history(p, "Subscribestatus", "timeout");
      ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
      return 10000;  /* Reschedule this destruction so that we know that it's gone */
   }

   /* If there are packets still waiting for delivery, delay the destruction */
   if (p->packets) {
      if (!p->needdestroy) {
         char method_str[31];
         ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
         append_history(p, "ReliableXmit", "timeout");
         if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
            if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
               pvt_set_needdestroy(p, "autodestruct");
            }
         }
         return 10000;
      } else {
         /* They've had their chance to respond. Time to bail */
         __sip_pretend_ack(p);
      }
   }

   /* Reset schedule ID */
   p->autokillid = -1;


   /*
    * Lock both the pvt and the channel safely so that we can queue up a frame.
    */
   sip_pvt_lock(p);
   while (p->owner && ast_channel_trylock(p->owner)) {
      sip_pvt_unlock(p);
      sched_yield();
      sip_pvt_lock(p);
   }

   if (p->owner) {
      ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
      ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
      ast_channel_unlock(p->owner);
   } else if (p->refer && !p->alreadygone) {
      ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
      transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
      append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
   } else {
      append_history(p, "AutoDestroy", "%s", p->callid);
      ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
      dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
      /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
      /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
      /* sip_destroy also absorbs the reference */
   }

   sip_pvt_unlock(p);

   dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");

   return 0;
}
static void __sip_destroy ( struct sip_pvt p,
int  lockowner,
int  lockdialoglist 
) [static]

Execute destruction of SIP dialog structure, release memory.

Definition at line 5714 of file chan_sip.c.

References ast_channel::_softhangup, ao2_ref, ast_channel_lock, ast_channel_unlock, ast_debug, ast_free, AST_LIST_REMOVE_HEAD, ast_log(), ast_rtp_destroy(), ast_rtp_get_bridged(), AST_SCHED_DEL_UNREF, AST_SOFTHANGUP_DEV, ast_string_field_free_memory, ast_test_flag, ast_udptl_destroy(), ast_variables_destroy(), ast_verbose(), sip_subscription_mwi::call, sip_registry::call, sip_peer::call, sip_pvt::callid, sip_pvt::chanvars, DEC_CALL_LIMIT, deinit_req(), dialog_unref(), sip_pvt::flags, free_old_route(), sip_pvt::history, sip_pvt::history_entries, sip_pvt::initreq, LOG_DEBUG, sip_pvt::method, sip_pvt::mwi, sip_peer::mwipvt, ast_channel::name, sip_pvt::notify_headers, option_debug, sip_pvt::options, sip_pvt::owner, sip_st_dlg::quit_flag, sip_pvt::refer, sip_pvt::registry, registry_unref(), sip_pvt::relatedpeer, sip_pvt::request_queue, sip_pvt::route, sip_pvt::rtp, sip_debug_test_pvt(), sip_dump_history(), SIP_INC_COUNT, sip_methods, SIP_PAGE2_CALL_ONHOLD, sip_pvt::socket, sip_st_dlg::st_active, sip_st_dlg::st_schedid, sip_pvt::stimer, sip_socket::tcptls_session, ast_channel::tech_pvt, cfsip_methods::text, sip_pvt::trtp, TRUE, sip_pvt::udptl, unref_peer(), update_call_counter(), and sip_pvt::vrtp.

Referenced by sip_destroy().

{
   struct sip_request *req;

   if (p->stimer) {
      ast_free(p->stimer);
      p->stimer = NULL;
   }

   if (sip_debug_test_pvt(p))
      ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);

   if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
      update_call_counter(p, DEC_CALL_LIMIT);
      ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
   }

   /* Unlink us from the owner if we have one */
   if (p->owner) {
      if (lockowner)
         ast_channel_lock(p->owner);
      if (option_debug)
         ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
      p->owner->tech_pvt = NULL;
      /* Make sure that the channel knows its backend is going away */
      p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
      if (lockowner)
         ast_channel_unlock(p->owner);
      /* Give the channel a chance to react before deallocation */
      usleep(1);
   }

   /* Remove link from peer to subscription of MWI */
   if (p->relatedpeer && p->relatedpeer->mwipvt)
      p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
   if (p->relatedpeer && p->relatedpeer->call == p)
      p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
   
   if (p->relatedpeer)
      p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
   
   if (p->registry) {
      if (p->registry->call == p)
         p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
      p->registry = registry_unref(p->registry, "delete p->registry");
   }
   
   if (p->mwi) {
      p->mwi->call = NULL;
   }

   if (dumphistory)
      sip_dump_history(p);

   if (p->options)
      ast_free(p->options);

   if (p->notify_headers) {
      ast_variables_destroy(p->notify_headers);
      p->notify_headers = NULL;
   }
   if (p->rtp) {
      ast_rtp_destroy(p->rtp);
   }
   if (p->vrtp) {
      ast_rtp_destroy(p->vrtp);
   }
   if (p->trtp) {
      while (ast_rtp_get_bridged(p->trtp))
         usleep(1);
      ast_rtp_destroy(p->trtp);
   }
   if (p->udptl)
      ast_udptl_destroy(p->udptl);
   if (p->refer)
      ast_free(p->refer);
   if (p->route) {
      free_old_route(p->route);
      p->route = NULL;
   }
   deinit_req(&p->initreq);

   /* Destroy Session-Timers if allocated */
   if (p->stimer) {
      p->stimer->quit_flag = 1;
      if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
         AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
               dialog_unref(p, "removing session timer ref"));
      }
      ast_free(p->stimer);
      p->stimer = NULL;
   }

   /* Clear history */
   if (p->history) {
      struct sip_history *hist;
      while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
         ast_free(hist);
         p->history_entries--;
      }
      ast_free(p->history);
      p->history = NULL;
   }

   while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
      ast_free(req);
   }

   if (p->chanvars) {
      ast_variables_destroy(p->chanvars);
      p->chanvars = NULL;
   }

   ast_string_field_free_memory(p);

   if (p->socket.tcptls_session) {
      ao2_ref(p->socket.tcptls_session, -1);
      p->socket.tcptls_session = NULL;
   }
}
static int __sip_do_register ( struct sip_registry r) [static]

Register with SIP proxy.

Definition at line 11982 of file chan_sip.c.

References SIP_REGISTER, and transmit_register().

Referenced by sip_reregister().

{
   int res;

   res = transmit_register(r, SIP_REGISTER, NULL, NULL);
   return res;
}
static void __sip_pretend_ack ( struct sip_pvt p) [static]

Pretend to ack all packets called with p locked.

Definition at line 4300 of file chan_sip.c.

References __sip_ack(), ast_log(), sip_pkt::data, find_sip_method(), sip_pkt::is_resp, LOG_WARNING, sip_pkt::method, sip_request::method, sip_pvt::packets, sip_pkt::seqno, sip_methods, and cfsip_methods::text.

Referenced by __sip_autodestruct(), handle_request_bye(), handle_request_cancel(), and sip_reg_timeout().

{
   struct sip_pkt *cur = NULL;

   while (p->packets) {
      int method;
      if (cur == p->packets) {
         ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
         return;
      }
      cur = p->packets;
      method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
      __sip_ack(p, cur->seqno, cur->is_resp, method);
   }
}
static enum sip_result __sip_reliable_xmit ( struct sip_pvt p,
int  seqno,
int  resp,
struct ast_str data,
int  len,
int  fatal,
int  sipmethod 
) [static]

Transmit packet with retransmits.

Returns:
0 on success, -1 on failure to allocate packet

Todo:
According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited

Definition at line 4042 of file chan_sip.c.

References __sip_xmit(), append_history, ast_calloc, ast_debug, AST_FAILURE, ast_free, ast_log(), AST_SCHED_DEL, AST_SCHED_REPLACE_VARIABLE, ast_str_buffer(), ast_str_create(), ast_str_set(), AST_SUCCESS, sip_pkt::data, DEFAULT_RETRANS, dialog_ref(), dialog_unref(), sip_pkt::is_fatal, sip_pkt::is_resp, sip_request::len, LOG_ERROR, sip_pkt::method, sip_pkt::next, sip_pkt::owner, sip_pkt::packetlen, sip_pvt::packets, sip_pvt::pendinginvite, sip_pkt::response_code, retrans_pkt(), sip_pkt::retransid, sip_pkt::seqno, SIP_INVITE, SIP_TRANSPORT_UDP, sip_pvt::socket, sip_pvt::timer_t1, sip_pkt::timer_t1, sip_socket::type, and XMIT_ERROR.

Referenced by send_request(), and send_response().

{
   struct sip_pkt *pkt = NULL;
   int siptimer_a = DEFAULT_RETRANS;
   int xmitres = 0;
   int respid;

   if (sipmethod == SIP_INVITE) {
      /* Note this is a pending invite */
      p->pendinginvite = seqno;
   }

   /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
   /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
   /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
   if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
      xmitres = __sip_xmit(p, data, len); /* Send packet */
      if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
         append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
         return AST_FAILURE;
      } else {
         return AST_SUCCESS;
      }
   }

   if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
      return AST_FAILURE;
   /* copy data, add a terminator and save length */
   if (!(pkt->data = ast_str_create(len))) {
      ast_free(pkt);
      return AST_FAILURE;
   }
   ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
   pkt->packetlen = len;
   /* copy other parameters from the caller */
   pkt->method = sipmethod;
   pkt->seqno = seqno;
   pkt->is_resp = resp;
   pkt->is_fatal = fatal;
   pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
   pkt->next = p->packets;
   p->packets = pkt; /* Add it to the queue */
   if (resp) {
      /* Parse out the response code */
      if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
         pkt->response_code = respid;
      }
   }
   pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
   pkt->retransid = -1;
   if (pkt->timer_t1)
      siptimer_a = pkt->timer_t1 * 2;

   /* Schedule retransmission */
   AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
   if (sipdebug)
      ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);

   xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);   /* Send packet */

   if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
      append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
      ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
      AST_SCHED_DEL(sched, pkt->retransid);
      p->packets = pkt->next;
      pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
      ast_free(pkt->data);
      ast_free(pkt);
      return AST_FAILURE;
   } else {
      return AST_SUCCESS;
   }
}
static int __sip_semi_ack ( struct sip_pvt p,
int  seqno,
int  resp,
int  sipmethod 
) [static]

Acks receipt of packet, keep it around (used for provisional responses)

Definition at line 4317 of file chan_sip.c.

References ast_debug, AST_SCHED_DEL, sip_pvt::callid, sip_pkt::data, FALSE, sip_pkt::is_resp, method_match(), sip_pkt::next, sip_pvt::packets, sip_pkt::retransid, sip_pkt::seqno, sip_methods, cfsip_methods::text, and TRUE.

Referenced by handle_response(), and sip_hangup().

{
   struct sip_pkt *cur;
   int res = FALSE;

   for (cur = p->packets; cur; cur = cur->next) {
      if (cur->seqno == seqno && cur->is_resp == resp &&
         (cur->is_resp || method_match(sipmethod, cur->data->str))) {
         /* this is our baby */
         if (cur->retransid > -1) {
            if (sipdebug)
               ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
         }
         AST_SCHED_DEL(sched, cur->retransid);
         res = TRUE;
         break;
      }
   }
   ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
   return res;
}
static int __sip_subscribe_mwi_do ( struct sip_subscription_mwi mwi) [static]

Actually setup an MWI subscription or resubscribe.

Definition at line 11463 of file chan_sip.c.

References ast_dnsmgr_lookup(), ast_set_flag, ast_sip_ouraddrfor(), ast_string_field_set, ast_strlen_zero(), ASTOBJ_REF, sip_subscription_mwi::authuser, build_callid_pvt(), build_contact(), build_via(), sip_subscription_mwi::call, create_addr(), dialog_unlink_all(), dialog_unref(), sip_subscription_mwi::dnsmgr, sip_pvt::flags, get_srv_protocol(), get_srv_service(), sip_subscription_mwi::hostname, MAXHOSTNAMELEN, sip_pvt::mwi, obproxy_get(), sip_pvt::ourip, sip_socket::port, sip_subscription_mwi::portno, sip_pvt::recv, ref_proxy(), sip_pvt::sa, sip_subscription_mwi::secret, set_socket_transport(), sip_alloc(), sip_cfg, SIP_OUTGOING, SIP_SUBSCRIBE, sip_pvt::socket, sip_settings::srvlookup, transmit_invite(), sip_subscription_mwi::transport, TRUE, sip_subscription_mwi::us, and sip_subscription_mwi::username.

Referenced by sip_subscribe_mwi_do().

{
   /* If we have no DNS manager let's do a lookup */
   if (!mwi->dnsmgr) {
      char transport[MAXHOSTNAMELEN];
      snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
      ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
   }

   /* If we already have a subscription up simply send a resubscription */
   if (mwi->call) {
      transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
      return 0;
   }
   
   /* Create a dialog that we will use for the subscription */
   if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
      return -1;
   }

   ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));

   if (!mwi->us.sin_port && mwi->portno) {
      mwi->us.sin_port = htons(mwi->portno);
   }
   
   /* Setup the destination of our subscription */
   if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
      dialog_unlink_all(mwi->call, TRUE, TRUE);
      mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
      return 0;
   }
   
   if (!mwi->dnsmgr && mwi->portno) {
      mwi->call->sa.sin_port = htons(mwi->portno);
      mwi->call->recv.sin_port = htons(mwi->portno);
   } else {
      mwi->portno = ntohs(mwi->call->sa.sin_port);
   }
   
   /* Set various other information */
   if (!ast_strlen_zero(mwi->authuser)) {
      ast_string_field_set(mwi->call, peername, mwi->authuser);
      ast_string_field_set(mwi->call, authname, mwi->authuser);
      ast_string_field_set(mwi->call, fromuser, mwi->authuser);
   } else {
      ast_string_field_set(mwi->call, peername, mwi->username);
      ast_string_field_set(mwi->call, authname, mwi->username);
      ast_string_field_set(mwi->call, fromuser, mwi->username);
   }
   ast_string_field_set(mwi->call, username, mwi->username);
   if (!ast_strlen_zero(mwi->secret)) {
      ast_string_field_set(mwi->call, peersecret, mwi->secret);
   }
   set_socket_transport(&mwi->call->socket, mwi->transport);
   mwi->call->socket.port = htons(mwi->portno);
   ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
   build_contact(mwi->call);
   build_via(mwi->call);
   build_callid_pvt(mwi->call);
   ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
   
   /* Associate the call with us */
   mwi->call->mwi = ASTOBJ_REF(mwi);
   
   /* Actually send the packet */
   transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);

   return 0;
}
static int __sip_xmit ( struct sip_pvt p,
struct ast_str data,
int  len 
) [static]

Transmit SIP message Sends a SIP request or response on a given socket (in the pvt) Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit.

Definition at line 3739 of file chan_sip.c.

References ast_debug, ast_inet_ntoa(), ast_log(), errno, sip_socket::fd, get_transport_pvt(), LOG_WARNING, sip_prepare_socket(), sip_real_dst(), sip_tcptls_write(), SIP_TRANSPORT_UDP, sip_pvt::socket, sip_socket::tcptls_session, sip_socket::type, and XMIT_ERROR.

Referenced by __sip_reliable_xmit(), retrans_pkt(), send_request(), and send_response().

{
   int res = 0;
   const struct sockaddr_in *dst = sip_real_dst(p);

   ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));

   if (sip_prepare_socket(p) < 0)
      return XMIT_ERROR;

   if (p->socket.type == SIP_TRANSPORT_UDP) {
      res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
   } else if (p->socket.tcptls_session) {
      res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
   } else {
      ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
      return XMIT_ERROR;
   }

   if (res == -1) {
      switch (errno) {
      case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
      case EHOSTUNREACH:   /* Host can't be reached */
      case ENETDOWN:       /* Inteface down */
      case ENETUNREACH: /* Network failure */
      case ECONNREFUSED:      /* ICMP port unreachable */ 
         res = XMIT_ERROR; /* Don't bother with trying to transmit again */
      }
   }
   if (res != len)
      ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));

   return res;
}
static int __transmit_response ( struct sip_pvt p,
const char *  msg,
const struct sip_request req,
enum xmittype  reliable 
) [static]

Base transmit response function.

Definition at line 10068 of file chan_sip.c.

References add_header(), ast_cause2str(), ast_log(), buf, get_header(), ast_channel::hangupcause, LOG_WARNING, sip_pvt::method, sip_pvt::owner, respprep(), send_response(), and SIP_INVITE.

Referenced by transmit_response(), transmit_response_reliable(), and transmit_response_using_temp().

{
   struct sip_request resp;
   int seqno = 0;

   if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
      ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
      return -1;
   }
   respprep(&resp, p, msg, req);
   /* If we are cancelling an incoming invite for some reason, add information
      about the reason why we are doing this in clear text */
   if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
      char buf[10];

      add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
      snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
      add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
   }
   return send_response(p, &resp, reliable, seqno);
}
static void __unreg_module ( void  ) [static]

Definition at line 26679 of file chan_sip.c.

static char * _sip_qualify_peer ( int  type,
int  fd,
struct mansession s,
const struct message m,
int  argc,
const char *  argv[] 
) [static]

Send qualify message to peer from cli or manager. Mostly for debugging.

Definition at line 15838 of file chan_sip.c.

References ast_cli(), astman_send_error(), CLI_SHOWUSAGE, CLI_SUCCESS, FALSE, find_peer(), FINDPEERS, sip_poke_peer(), TRUE, and unref_peer().

Referenced by manager_sip_qualify_peer(), and sip_qualify_peer().

{
   struct sip_peer *peer;
   int load_realtime;

   if (argc < 4)
      return CLI_SHOWUSAGE;

   load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
   if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
      sip_poke_peer(peer, 1);
      unref_peer(peer, "qualify: done with peer");
   } else if (type == 0) {
      ast_cli(fd, "Peer '%s' not found\n", argv[3]);
   } else {
      astman_send_error(s, m, "Peer not found");
   }
   return CLI_SUCCESS;
}
static char * _sip_show_peer ( int  type,
int  fd,
struct mansession s,
const struct message m,
int  argc,
const char *  argv[] 
) [static]

Show one peer in detail (main function)

Definition at line 15923 of file chan_sip.c.

References sip_peer::accountcode, sip_peer::addr, sip_peer::allowtransfer, sip_peer::amaflags, ARRAY_LEN, ast_callerid_merge(), ast_cdr_flags2str(), ast_check_realtime(), ast_cli(), ast_codec_pref_index(), ast_describe_caller_presentation(), ast_getformatname(), ast_getformatname_multiple(), ast_inet_ntoa(), ast_print_group(), ast_sched_when(), ast_str_alloca, ast_strlen_zero(), ast_test_flag, astman_append(), astman_get_header(), astman_send_error(), sip_peer::auth, sip_peer::autoframing, sip_peer::busy_level, sip_peer::call_limit, sip_peer::callgroup, sip_peer::callingpres, sip_peer::capability, sip_peer::chanvars, sip_peer::cid_name, sip_peer::cid_num, CLI_SHOWUSAGE, CLI_SUCCESS, cli_yesno(), sip_peer::context, sip_peer::defaddr, dtmfmode2str(), sip_peer::expire, FALSE, faxec2str(), find_peer(), FINDPEERS, sip_peer::flags, sip_proxy::force, sip_peer::fromdomain, sip_peer::fromuser, sip_peer::fullcontact, get_transport(), get_transport_list(), sip_peer::ha, sip_peer::host_dynamic, cfsip_options::id, insecure2str(), sip_peer::is_realtime, sip_peer::language, sip_peer::lastmsgssent, sip_peer::maxcallbitrate, sip_auth::md5secret, sip_peer::md5secret, ast_variable::name, sip_proxy::name, sip_peer::name, nat2str(), ast_variable::next, sip_auth::next, sip_peer::outboundproxy, sip_peer::parkinglot, peer_mailboxes_to_str(), peer_status(), sip_peer::pickupgroup, sip_peer::prefs, print_codec_to_cli(), print_group(), sip_peer::qualifyfreq, sip_auth::realm, sip_peer::regexten, sip_peer::remotesecret, S_OR, sip_auth::secret, sip_peer::secret, SIP_DIRECT_MEDIA, SIP_DTMF, SIP_INSECURE, SIP_NAT, sip_options, SIP_PAGE2_ALLOWOVERLAP, SIP_PAGE2_ALLOWSUBSCRIBE, SIP_PAGE2_FORWARD_LOOP_DETECTED, SIP_PAGE2_IGNORESDPVERSION, SIP_PAGE2_REGISTERTRYING, SIP_PAGE2_T38SUPPORT, SIP_PAGE2_TEXTSUPPORT, SIP_PAGE2_VIDEOSUPPORT, SIP_PAGE2_VIDEOSUPPORT_ALWAYS, SIP_PROMISCREDIR, SIP_SENDRPID, SIP_TRUSTRPID, SIP_USEREQPHONE, sip_peer::sipoptions, sip_peer::socket, sip_st_cfg::st_max_se, sip_st_cfg::st_min_se, sip_st_cfg::st_mode_oper, sip_st_cfg::st_ref, status, sip_peer::stimer, stmode2str(), strefresher2str(), sip_peer::subscribecontext, sip_peer::t38_maxdatagram, text, sip_peer::timer_b, sip_peer::timer_t1, sip_peer::tohost, transfermode2str(), sip_peer::transports, TRUE, sip_socket::type, unref_peer(), sip_peer::useragent, sip_peer::username, sip_auth::username, ast_variable::value, and sip_peer::vmexten.

Referenced by manager_sip_show_peer(), and sip_show_peer().

{
   char status[30] = "";
   char cbuf[256];
   struct sip_peer *peer;
   char codec_buf[512];
   struct ast_codec_pref *pref;
   struct ast_variable *v;
   struct sip_auth *auth;
   int x = 0, codec = 0, load_realtime;
   int realtimepeers;

   realtimepeers = ast_check_realtime("sippeers");

   if (argc < 4)
      return CLI_SHOWUSAGE;

   load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
   peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);

   if (s) {    /* Manager */
      if (peer) {
         const char *id = astman_get_header(m, "ActionID");

         astman_append(s, "Response: Success\r\n");
         if (!ast_strlen_zero(id))
            astman_append(s, "ActionID: %s\r\n", id);
      } else {
         snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
         astman_send_error(s, m, cbuf);
         return CLI_SUCCESS;
      }
   }
   if (peer && type==0 ) { /* Normal listing */
      struct ast_str *mailbox_str = ast_str_alloca(512);
      ast_cli(fd, "\n\n");
      ast_cli(fd, "  * Name       : %s\n", peer->name);
      if (realtimepeers) { /* Realtime is enabled */
         ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
      }
      ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
      ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
      ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
      for (auth = peer->auth; auth; auth = auth->next) {
         ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
         ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
      }
      ast_cli(fd, "  Context      : %s\n", peer->context);
      ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
      ast_cli(fd, "  Language     : %s\n", peer->language);
      if (!ast_strlen_zero(peer->accountcode))
         ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
      ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
      ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
      ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
      if (!ast_strlen_zero(peer->fromuser))
         ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
      if (!ast_strlen_zero(peer->fromdomain))
         ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
      ast_cli(fd, "  Callgroup    : ");
      print_group(fd, peer->callgroup, 0);
      ast_cli(fd, "  Pickupgroup  : ");
      print_group(fd, peer->pickupgroup, 0);
      peer_mailboxes_to_str(&mailbox_str, peer);
      ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
      ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
      ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
      ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
      if (peer->busy_level)
         ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
      ast_cli(fd, "  Dynamic      : %s\n", cli_yesno(peer->host_dynamic));
      ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
      ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
      ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
      ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
      ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
      ast_cli(fd, "  ACL          : %s\n", cli_yesno(peer->ha != NULL));
      ast_cli(fd, "  T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
      ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
      ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
      ast_cli(fd, "  DirectMedia  : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
      ast_cli(fd, "  PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
      ast_cli(fd, "  User=Phone   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
      ast_cli(fd, "  Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) || ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS)));
      ast_cli(fd, "  Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
      ast_cli(fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
      ast_cli(fd, "  Trust RPID   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
      ast_cli(fd, "  Send RPID    : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
      ast_cli(fd, "  Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
      ast_cli(fd, "  Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
      ast_cli(fd, "  Forward Loop : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
      if (peer->outboundproxy)
         ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
                     peer->outboundproxy->force ? "(forced)" : "");

      /* - is enumerated */
      ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
      ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
      ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
      ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
      ast_cli(fd, "  Addr->IP     : %s Port %d\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
      ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
      ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
      ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports)); 
      if (!ast_strlen_zero(global_regcontext))
         ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
      ast_cli(fd, "  Def. Username: %s\n", peer->username);
      ast_cli(fd, "  SIP Options  : ");
      if (peer->sipoptions) {
         int lastoption = -1;
         for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
            if (sip_options[x].id != lastoption) {
               if (peer->sipoptions & sip_options[x].id)
                  ast_cli(fd, "%s ", sip_options[x].text);
               lastoption = x;
            }
         }
      } else
         ast_cli(fd, "(none)");

      ast_cli(fd, "\n");
      ast_cli(fd, "  Codecs       : ");
      ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
      ast_cli(fd, "%s\n", codec_buf);
      ast_cli(fd, "  Codec Order  : (");
      print_codec_to_cli(fd, &peer->prefs);
      ast_cli(fd, ")\n");

      ast_cli(fd, "  Auto-Framing :  %s \n", cli_yesno(peer->autoframing));
      ast_cli(fd, "  100 on REG   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
      ast_cli(fd, "  Status       : ");
      peer_status(peer, status, sizeof(status));
      ast_cli(fd, "%s\n", status);
      ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
      ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
      ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
      if (peer->chanvars) {
         ast_cli(fd, "  Variables    :\n");
         for (v = peer->chanvars ; v ; v = v->next)
            ast_cli(fd, "                 %s = %s\n", v->name, v->value);
      }

      ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
      ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
      ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
      ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
      ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
      ast_cli(fd, "\n");
      peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
   } else  if (peer && type == 1) { /* manager listing */
      char buffer[256];
      struct ast_str *mailbox_str = ast_str_alloca(512);
      astman_append(s, "Channeltype: SIP\r\n");
      astman_append(s, "ObjectName: %s\r\n", peer->name);
      astman_append(s, "ChanObjectType: peer\r\n");
      astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
      astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
      astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
      astman_append(s, "Context: %s\r\n", peer->context);
      astman_append(s, "Language: %s\r\n", peer->language);
      if (!ast_strlen_zero(peer->accountcode))
         astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
      astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
      astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
      if (!ast_strlen_zero(peer->fromuser))
         astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
      if (!ast_strlen_zero(peer->fromdomain))
         astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
      astman_append(s, "Callgroup: ");
      astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
      astman_append(s, "Pickupgroup: ");
      astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
      peer_mailboxes_to_str(&mailbox_str, peer);
      astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
      astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
      astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
      astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
      astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
      astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
      astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
      astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
      astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
      astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
      astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
      astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
      astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
      astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
      astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
      astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
      astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
      astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
      astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
      astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
      astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
      astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
      astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
      astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
      astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);

      /* - is enumerated */
      astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
      astman_append(s, "ToHost: %s\r\n", peer->tohost);
      astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", ntohs(peer->addr.sin_port));
      astman_append(s, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
      astman_append(s, "Default-Username: %s\r\n", peer->username);
      if (!ast_strlen_zero(global_regcontext))
         astman_append(s, "RegExtension: %s\r\n", peer->regexten);
      astman_append(s, "Codecs: ");
      ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
      astman_append(s, "%s\r\n", codec_buf);
      astman_append(s, "CodecOrder: ");
      pref = &peer->prefs;
      for(x = 0; x < 32 ; x++) {
         codec = ast_codec_pref_index(pref, x);
         if (!codec)
            break;
         astman_append(s, "%s", ast_getformatname(codec));
         if (x < 31 && ast_codec_pref_index(pref, x+1))
            astman_append(s, ",");
      }

      astman_append(s, "\r\n");
      astman_append(s, "Status: ");
      peer_status(peer, status, sizeof(status));
      astman_append(s, "%s\r\n", status);
      astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
      astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
      astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
      astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
      if (peer->chanvars) {
         for (v = peer->chanvars ; v ; v = v->next) {
            astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
         }
      }

      peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");

   } else {
      ast_cli(fd, "Peer %s not found.\n", argv[3]);
      ast_cli(fd, "\n");
   }

   return CLI_SUCCESS;
}
static char * _sip_show_peers ( int  fd,
int *  total,
struct mansession s,
const struct message m,
int  argc,
const char *  argv[] 
) [static]

Execute sip show peers command.

Definition at line 15249 of file chan_sip.c.

References sip_peer::addr, ao2_container_count(), ao2_iterator_destroy(), ao2_iterator_init(), ao2_lock(), ao2_t_iterator_next, ao2_unlock(), ast_calloc, ast_check_realtime(), ast_cli(), ast_copy_string(), ast_free, ast_inet_ntoa(), ast_strlen_zero(), ast_test_flag, astman_append(), astman_get_header(), CLI_SHOWUSAGE, CLI_SUCCESS, FALSE, sip_peer::flags, FORMAT, FORMAT2, sip_peer::ha, sip_peer::host_dynamic, id, sip_peer::is_realtime, sip_peer::name, name, peer_status(), peercomparefunc(), SIP_NAT_ROUTE, SIP_PAGE2_TEXTSUPPORT, SIP_PAGE2_VIDEOSUPPORT, SIP_TYPE_PEER, status, TRUE, sip_peer::type, unref_peer(), and sip_peer::username.

Referenced by manager_sip_show_peers(), and sip_show_peers().

{
   regex_t regexbuf;
   int havepattern = FALSE;
   struct sip_peer *peer;
   struct ao2_iterator i;
   
/* the last argument is left-aligned, so we don't need a size anyways */
#define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
#define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"

   char name[256];
   int total_peers = 0;
   int peers_mon_online = 0;
   int peers_mon_offline = 0;
   int peers_unmon_offline = 0;
   int peers_unmon_online = 0;
   const char *id;
   char idtext[256] = "";
   int realtimepeers;
   int objcount = ao2_container_count(peers);
   struct sip_peer **peerarray;
   int k;
   
   
   realtimepeers = ast_check_realtime("sippeers");
   peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);

   if (s) { /* Manager - get ActionID */
      id = astman_get_header(m, "ActionID");
      if (!ast_strlen_zero(id))
         snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
   }

   switch (argc) {
   case 5:
      if (!strcasecmp(argv[3], "like")) {
         if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
            return CLI_SHOWUSAGE;
         havepattern = TRUE;
      } else
         return CLI_SHOWUSAGE;
   case 3:
      break;
   default:
      return CLI_SHOWUSAGE;
   }

   if (!s) /* Normal list */
      ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
   

   i = ao2_iterator_init(peers, 0);
   while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
      ao2_lock(peer);

      if (!(peer->type & SIP_TYPE_PEER)) {
         ao2_unlock(peer);
         unref_peer(peer, "unref peer because it's actually a user");
         continue;
      }

      if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
         objcount--;
         ao2_unlock(peer);
         unref_peer(peer, "toss iterator peer ptr before continue");
         continue;
      }

      peerarray[total_peers++] = peer;
      ao2_unlock(peer);
   }
   ao2_iterator_destroy(&i);
   
   qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);

   for(k=0; k < total_peers; k++) {
      char status[20] = "";
      char srch[2000];
      char pstatus;
      peer = peerarray[k];
      
      ao2_lock(peer);
      if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
         ao2_unlock(peer);
         unref_peer(peer, "toss iterator peer ptr before continue");
         continue;
      }

      if (!ast_strlen_zero(peer->username) && !s)
         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
      else
         ast_copy_string(name, peer->name, sizeof(name));
      
      pstatus = peer_status(peer, status, sizeof(status));
      if (pstatus == 1)
         peers_mon_online++;
      else if (pstatus == 0)
         peers_mon_offline++;
      else {
         if (peer->addr.sin_port == 0)
            peers_unmon_offline++;
         else
            peers_unmon_online++;
      }

      snprintf(srch, sizeof(srch), FORMAT, name,
         peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
         peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
         ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
         peer->ha ? " A " : "   ",  /* permit/deny */
         ntohs(peer->addr.sin_port), status,
         realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");

      if (!s)  {/* Normal CLI list */
         ast_cli(fd, FORMAT, name, 
         peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
         peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
         ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
         peer->ha ? " A " : "   ",       /* permit/deny */
         
         ntohs(peer->addr.sin_port), status,
         realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
      } else { /* Manager format */
         /* The names here need to be the same as other channels */
         astman_append(s, 
         "Event: PeerEntry\r\n%s"
         "Channeltype: SIP\r\n"
         "ObjectName: %s\r\n"
         "ChanObjectType: peer\r\n" /* "peer" or "user" */
         "IPaddress: %s\r\n"
         "IPport: %d\r\n"
         "Dynamic: %s\r\n"
         "Natsupport: %s\r\n"
         "VideoSupport: %s\r\n"
         "TextSupport: %s\r\n"
         "ACL: %s\r\n"
         "Status: %s\r\n"
         "RealtimeDevice: %s\r\n\r\n", 
         idtext,
         peer->name, 
         peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
         ntohs(peer->addr.sin_port), 
         peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
         ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",  /* NAT=yes? */
         ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
         ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
         peer->ha ? "yes" : "no",       /* permit/deny */
         status,
         realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
      }
      ao2_unlock(peer);
      unref_peer(peer, "toss iterator peer ptr");
   }
   
   if (!s)
      ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
              total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);

   if (havepattern)
      regfree(&regexbuf);

   if (total)
      *total = total_peers;
   
   ast_free(peerarray);
   
   return CLI_SUCCESS;
#undef FORMAT
#undef FORMAT2
}
static void * _sip_tcp_helper_thread ( struct sip_pvt pvt,
struct ast_tcptls_session_instance tcptls_session 
) [static]

SIP TCP thread management function This function reads from the socket, parses the packet into a request.

Todo:
XXX If there's no Content-Length or if the content-length and what we receive is not the same - we should generate an error

Definition at line 2951 of file chan_sip.c.

References sip_threadinfo::alert_pipe, ao2_lock(), ao2_ref, ao2_t_find, ao2_t_ref, ao2_t_unlink, ao2_unlock(), ast_atomic_fetchadd_int(), ast_debug, AST_LIST_REMOVE_HEAD, ast_log(), ast_mutex_lock(), ast_mutex_unlock(), ast_poll, ast_str_append(), ast_str_buffer(), ast_str_create(), ast_str_reset(), ast_tcptls_client_start(), ast_tcptls_server_write(), ast_wait_for_input(), sip_request::authenticated, buf, cleanup(), ast_tcptls_session_instance::client, copy_request(), tcptls_packet::data, sip_request::data, deinit_req(), errno, ast_tcptls_session_instance::f, sip_socket::fd, ast_tcptls_session_instance::fd, get_header(), handle_request_do(), tcptls_packet::len, sip_request::len, ast_tcptls_session_instance::lock, LOG_ERROR, LOG_WARNING, me, MIN, OBJ_POINTER, sip_threadinfo::packet_q, ast_tcptls_session_instance::parent, parse_request(), sip_socket::port, ast_tcptls_session_instance::remote_address, REQ_OFFSET_TO_STR, set_socket_transport(), sip_check_authtimeout(), SIP_MIN_PACKET, sip_threadinfo_create(), SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, sip_request::socket, ast_tcptls_session_instance::ssl, sip_threadinfo::stop, TCPTLS_ALERT_DATA, TCPTLS_ALERT_STOP, sip_socket::tcptls_session, sip_threadinfo::tcptls_session, and sip_threadinfo::threadid.

Referenced by sip_tcp_worker_fn().

{
   int res, cl, timeout = -1, authenticated = 0, flags;
   time_t start;
   struct sip_request req = { 0, } , reqcpy = { 0, };
   struct sip_threadinfo *me = NULL;
   char buf[1024] = "";
   struct pollfd fds[2] = { { 0 }, { 0 }, };
   struct ast_tcptls_session_args *ca = NULL;

   /* If this is a server session, then the connection has already been
    * setup. Check if the authlimit has been reached and if not create the
    * threadinfo object so we can access this thread for writing.
    *
    * if this is a client connection more work must be done.
    * 1. We own the parent session args for a client connection.  This pointer needs
    *    to be held on to so we can decrement it's ref count on thread destruction.
    * 2. The threadinfo object was created before this thread was launched, however
    *    it must be found within the threadt table.
    * 3. Last, the tcptls_session must be started.
    */
   if (!tcptls_session->client) {
      if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
         /* unauth_sessions is decremented in the cleanup code */
         goto cleanup;
      }

      if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
         ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
         goto cleanup;
      }

      flags |= O_NONBLOCK;
      if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
         ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
         goto cleanup;
      }

      if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
         goto cleanup;
      }
      ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
   } else {
      struct sip_threadinfo tmp = {
         .tcptls_session = tcptls_session,
      };

      if ((!(ca = tcptls_session->parent)) ||
         (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
         (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
         goto cleanup;
      }
   }

   me->threadid = pthread_self();
   ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");

   /* set up pollfd to watch for reads on both the socket and the alert_pipe */
   fds[0].fd = tcptls_session->fd;
   fds[1].fd = me->alert_pipe[0];
   fds[0].events = fds[1].events = POLLIN | POLLPRI;

   if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
      goto cleanup;
   if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
      goto cleanup;

   if(time(&start) == -1) {
      ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
      goto cleanup;
   }

   for (;;) {
      struct ast_str *str_save;

      if (!tcptls_session->client && req.authenticated && !authenticated) {
         authenticated = 1;
         ast_atomic_fetchadd_int(&unauth_sessions, -1);
      }

      /* calculate the timeout for unauthenticated server sessions */
      if (!tcptls_session->client && !authenticated ) {
         if ((timeout = sip_check_authtimeout(start)) < 0) {
            goto cleanup;
         }

         if (timeout == 0) {
            ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
            goto cleanup;
         }
      } else {
         timeout = -1;
      }

      res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
      if (res < 0) {
         ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
         goto cleanup;
      } else if (res == 0) {
         /* timeout */
         ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
         goto cleanup;
      }

      /* handle the socket event, check for both reads from the socket fd,
       * and writes from alert_pipe fd */
      if (fds[0].revents) { /* there is data on the socket to be read */

         fds[0].revents = 0;

         /* clear request structure */
         str_save = req.data;
         memset(&req, 0, sizeof(req));
         req.data = str_save;
         ast_str_reset(req.data);

         str_save = reqcpy.data;
         memset(&reqcpy, 0, sizeof(reqcpy));
         reqcpy.data = str_save;
         ast_str_reset(reqcpy.data);

         memset(buf, 0, sizeof(buf));

         if (tcptls_session->ssl) {
            set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
            req.socket.port = htons(ourport_tls);
         } else {
            set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
            req.socket.port = htons(ourport_tcp);
         }
         req.socket.fd = tcptls_session->fd;

         /* Read in headers one line at a time */
         while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
            if (!tcptls_session->client && !authenticated ) {
               if ((timeout = sip_check_authtimeout(start)) < 0) {
                  goto cleanup;
               }

               if (timeout == 0) {
                  ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
                  goto cleanup;
               }
            } else {
               timeout = -1;
            }

            res = ast_wait_for_input(tcptls_session->fd, timeout);
            if (res < 0) {
               ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
               goto cleanup;
            } else if (res == 0) {
               /* timeout */
               ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
               goto cleanup;
            }

            ast_mutex_lock(&tcptls_session->lock);
            if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
               ast_mutex_unlock(&tcptls_session->lock);
               goto cleanup;
            }
            ast_mutex_unlock(&tcptls_session->lock);
            if (me->stop)
                goto cleanup;
            ast_str_append(&req.data, 0, "%s", buf);
            req.len = req.data->used;
         }
         copy_request(&reqcpy, &req);
         parse_request(&reqcpy);
         /* In order to know how much to read, we need the content-length header */
         if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
            while (cl > 0) {
               size_t bytes_read;
               if (!tcptls_session->client && !authenticated ) {
                  if ((timeout = sip_check_authtimeout(start)) < 0) {
                     goto cleanup;
                  }

                  if (timeout == 0) {
                     ast_debug(2, "SIP %s server timed out", tcptls_session->ssl ? "SSL": "TCP");
                     goto cleanup;
                  }
               } else {
                  timeout = -1;
               }

               res = ast_wait_for_input(tcptls_session->fd, timeout);
               if (res < 0) {
                  ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
                  goto cleanup;
               } else if (res == 0) {
                  /* timeout */
                  ast_debug(2, "SIP %s server timed out", tcptls_session->ssl ? "SSL": "TCP");
                  goto cleanup;
               }

               ast_mutex_lock(&tcptls_session->lock);
               if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
                  ast_mutex_unlock(&tcptls_session->lock);
                  goto cleanup;
               }
               buf[bytes_read] = '\0';
               ast_mutex_unlock(&tcptls_session->lock);
               if (me->stop)
                  goto cleanup;
               cl -= strlen(buf);
               ast_str_append(&req.data, 0, "%s", buf);
               req.len = req.data->used;
            }
         }
         /*! \todo XXX If there's no Content-Length or if the content-length and what
               we receive is not the same - we should generate an error */

         req.socket.tcptls_session = tcptls_session;
         handle_request_do(&req, &tcptls_session->remote_address);
      }

      if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
         enum sip_tcptls_alert alert;
         struct tcptls_packet *packet;

         fds[1].revents = 0;

         if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
            ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
            continue;
         }

         switch (alert) {
         case TCPTLS_ALERT_STOP:
            goto cleanup;
         case TCPTLS_ALERT_DATA:
            ao2_lock(me);
            if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
               ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
            } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
               ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
            }

            if (packet) {
               ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
            }
            ao2_unlock(me);
            break;
         default:
            ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
         }
      }
   }

   ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");

cleanup:
   if (!tcptls_session->client && !authenticated) {
      ast_atomic_fetchadd_int(&unauth_sessions, -1);
   }

   if (me) {
      ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
      ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
   }
   deinit_req(&reqcpy);
   deinit_req(&req);

   /* if client, we own the parent session arguments and must decrement ref */
   if (ca) {
      ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
   }

   if (tcptls_session) {
      ast_mutex_lock(&tcptls_session->lock);
      if (tcptls_session->f) {
         fclose(tcptls_session->f);
         tcptls_session->f = NULL;
      }
      if (tcptls_session->fd != -1) {
         close(tcptls_session->fd);
         tcptls_session->fd = -1;
      }
      tcptls_session->parent = NULL;
      ast_mutex_unlock(&tcptls_session->lock);

      ao2_ref(tcptls_session, -1);
      tcptls_session = NULL;
   }
   return NULL;
}
static int acf_channel_read ( struct ast_channel chan,
const char *  funcname,
char *  preparse,
char *  buf,
size_t  buflen 
) [static]

Definition at line 21521 of file chan_sip.c.

References AST_APP_ARG, ast_copy_string(), AST_DECLARE_APP_ARGS, ast_inet_ntoa(), ast_log(), ast_rtp_get_peer(), ast_rtp_get_qos(), ast_rtp_get_quality(), AST_STANDARD_APP_ARGS, ast_strdupa, ast_strlen_zero(), sip_pvt::from, IS_SIP_TECH, ast_rtp_quality::local_count, ast_rtp_quality::local_jitter, ast_rtp_quality::local_lostpackets, ast_rtp_quality::local_ssrc, LOG_ERROR, LOG_WARNING, parse(), sip_pvt::peername, sip_pvt::recv, ast_rtp_quality::remote_count, ast_rtp_quality::remote_jitter, ast_rtp_quality::remote_lostpackets, ast_rtp_quality::remote_ssrc, sip_pvt::rtp, RTPQOS_SUMMARY, ast_rtp_quality::rtt, sip_pvt::sa, t38properties::state, sip_pvt::t38, T38_DISABLED, ast_channel::tech, ast_channel::tech_pvt, sip_pvt::trtp, sip_pvt::uri, sip_pvt::useragent, and sip_pvt::vrtp.

{
   struct sip_pvt *p = chan->tech_pvt;
   char *all = "", *parse = ast_strdupa(preparse);
   int res = 0;
   AST_DECLARE_APP_ARGS(args,
      AST_APP_ARG(param);
      AST_APP_ARG(type);
      AST_APP_ARG(field);
   );
   AST_STANDARD_APP_ARGS(args, parse);

   /* Sanity check */
   if (!IS_SIP_TECH(chan->tech)) {
      ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
      return 0;
   }

   memset(buf, 0, buflen);

   if (p == NULL) {
      return -1;
   }

   if (!strcasecmp(args.param, "peerip")) {
      ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
   } else if (!strcasecmp(args.param, "recvip")) {
      ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
   } else if (!strcasecmp(args.param, "from")) {
      ast_copy_string(buf, p->from, buflen);
   } else if (!strcasecmp(args.param, "uri")) {
      ast_copy_string(buf, p->uri, buflen);
   } else if (!strcasecmp(args.param, "useragent")) {
      ast_copy_string(buf, p->useragent, buflen);
   } else if (!strcasecmp(args.param, "peername")) {
      ast_copy_string(buf, p->peername, buflen);
   } else if (!strcasecmp(args.param, "t38passthrough")) {
      ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
   } else if (!strcasecmp(args.param, "rtpdest")) {
      struct sockaddr_in sin;
      struct ast_rtp *stream = NULL;

      if (ast_strlen_zero(args.type))
         args.type = "audio";

      if (!strcasecmp(args.type, "audio")) {
         stream = p->rtp;
      } else if (!strcasecmp(args.type, "video")) {
         stream = p->vrtp;
      } else if (!strcasecmp(args.type, "text")) {
         stream = p->trtp;
      } else {
         return -1;
      }

      if (!stream) {
         return -1;
      }

      ast_rtp_get_peer(stream, &sin);
      snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
   } else if (!strcasecmp(args.param, "rtpqos")) {
      struct ast_rtp_quality qos;
      struct ast_rtp *rtp = p->rtp;
      
      memset(&qos, 0, sizeof(qos));

      if (ast_strlen_zero(args.type))
         args.type = "audio";
      if (ast_strlen_zero(args.field))
         args.field = "all";
      
      if (!strcasecmp(args.type, "AUDIO")) {
         all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
      } else if (!strcasecmp(args.type, "VIDEO")) {
         all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
      } else if (!strcasecmp(args.type, "TEXT")) {
         all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
      } else {
         return -1;
      }
      
      if (!strcasecmp(args.field, "local_ssrc"))
         snprintf(buf, buflen, "%u", qos.local_ssrc);
      else if (!strcasecmp(args.field, "local_lostpackets"))
         snprintf(buf, buflen, "%u", qos.local_lostpackets);
      else if (!strcasecmp(args.field, "local_jitter"))
         snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
      else if (!strcasecmp(args.field, "local_count"))
         snprintf(buf, buflen, "%u", qos.local_count);
      else if (!strcasecmp(args.field, "remote_ssrc"))
         snprintf(buf, buflen, "%u", qos.remote_ssrc);
      else if (!strcasecmp(args.field, "remote_lostpackets"))
         snprintf(buf, buflen, "%u", qos.remote_lostpackets);
      else if (!strcasecmp(args.field, "remote_jitter"))
         snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
      else if (!strcasecmp(args.field, "remote_count"))
         snprintf(buf, buflen, "%u", qos.remote_count);
      else if (!strcasecmp(args.field, "rtt"))
         snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
      else if (!strcasecmp(args.field, "all"))
         ast_copy_string(buf, all, buflen);
      else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
          ;
      else {
         ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
         return -1;
      }
   } else {
      res = -1;
   }
   return res;
}
static void add_blank ( struct sip_request req) [static]

add a blank line if no body

Definition at line 4348 of file chan_sip.c.

References ast_str_append(), ast_str_strlen(), sip_request::data, sip_request::len, and sip_request::lines.

Referenced by send_request(), and send_response().

{
   if (!req->lines) {
      /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
      ast_str_append(&req->data, 0, "\r\n");
      req->len = ast_str_strlen(req->data);
   }
}
static void add_codec_to_sdp ( const struct sip_pvt p,
int  codec,
struct ast_str **  m_buf,
struct ast_str **  a_buf,
int  debug,
int *  min_packet_size 
) [static]

Add codec offer to SDP offer/answer body in INVITE or 200 OK.

Definition at line 10320 of file chan_sip.c.

References ast_codec_pref_getsize(), AST_FORMAT_G723_1, AST_FORMAT_G729A, AST_FORMAT_ILBC, AST_FORMAT_SIREN14, AST_FORMAT_SIREN7, ast_getformatname(), ast_rtp_codec_getpref(), ast_rtp_lookup_code(), ast_rtp_lookup_mime_subtype(), ast_rtp_lookup_sample_rate(), AST_RTP_OPT_G726_NONSTANDARD, ast_str_append(), ast_test_flag, ast_verbose(), ast_format_list::cur_ms, sip_pvt::flags, sip_pvt::rtp, and SIP_G726_NONSTANDARD.

Referenced by add_sdp().

{
   int rtp_code;
   struct ast_format_list fmt;


   if (debug)
      ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
   if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
      return;

   if (p->rtp) {
      struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
      fmt = ast_codec_pref_getsize(pref, codec);
   } else /* I dont see how you couldn't have p->rtp, but good to check for and error out if not there like earlier code */
      return;
   ast_str_append(m_buf, 0, " %d", rtp_code);
   ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
             ast_rtp_lookup_mime_subtype(1, codec,
                     ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
             ast_rtp_lookup_sample_rate(1, codec));

   switch (codec) {
   case AST_FORMAT_G729A:
      /* Indicate that we don't support VAD (G.729 annex B) */
      ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
      break;
   case AST_FORMAT_G723_1:
      /* Indicate that we don't support VAD (G.723.1 annex A) */
      ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
      break;
   case AST_FORMAT_ILBC:
      /* Add information about us using only 20/30 ms packetization */
      ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
      break;
   case AST_FORMAT_SIREN7:
      /* Indicate that we only expect 32Kbps */
      ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
      break;
   case AST_FORMAT_SIREN14:
      /* Indicate that we only expect 48Kbps */
      ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
      break;
   }

   if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
      *min_packet_size = fmt.cur_ms;

   /* Our first codec packetization processed cannot be zero */
   if ((*min_packet_size)==0 && fmt.cur_ms)
      *min_packet_size = fmt.cur_ms;
}
static int add_content ( struct sip_request req,
const char *  line 
) [static]

Add content (not header) to SIP message.

Definition at line 9523 of file chan_sip.c.

References ast_log(), ast_str_append(), sip_request::content, sip_request::lines, and LOG_WARNING.

Referenced by add_digit(), add_sdp(), add_text(), add_vidupdate(), transmit_notify_with_mwi(), transmit_notify_with_sipfrag(), and transmit_state_notify().

{
   if (req->lines) {
      ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
      return -1;
   }

   ast_str_append(&req->content, 0, "%s", line);
   return 0;
}
static int add_digit ( struct sip_request req,
char  digit,
unsigned int  duration,
int  mode 
) [static]

Add DTMF INFO tone to sip message Mode = 0 for application/dtmf-relay (Cisco) 1 for application/dtmf.

Definition at line 10274 of file chan_sip.c.

References add_content(), and add_header().

Referenced by transmit_info_with_digit().

{
   char tmp[256];
   int event;
   if (mode) {
      /* Application/dtmf short version used by some implementations */
      if (digit == '*')
         event = 10;
      else if (digit == '#')
         event = 11;
      else if ((digit >= 'A') && (digit <= 'D'))
         event = 12 + digit - 'A';
      else
         event = atoi(&digit);
      snprintf(tmp, sizeof(tmp), "%d\r\n", event);
      add_header(req, "Content-Type", "application/dtmf");
      add_content(req, tmp);
   } else {
      /* Application/dtmf-relay as documented by Cisco */
      snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
      add_header(req, "Content-Type", "application/dtmf-relay");
      add_content(req, tmp);
   }
   return 0;
}
static void add_noncodec_to_sdp ( const struct sip_pvt p,
int  format,
struct ast_str **  m_buf,
struct ast_str **  a_buf,
int  debug 
) [static]

Add RFC 2833 DTMF offer to SDP.

Definition at line 10453 of file chan_sip.c.

References AST_RTP_DTMF, ast_rtp_lookup_code(), ast_rtp_lookup_mime_subtype(), ast_rtp_lookup_sample_rate(), ast_str_append(), ast_verbose(), and sip_pvt::rtp.

Referenced by add_sdp().

{
   int rtp_code;

   if (debug)
      ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
   if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
      return;

   ast_str_append(m_buf, 0, " %d", rtp_code);
   ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
             ast_rtp_lookup_mime_subtype(0, format, 0),
             ast_rtp_lookup_sample_rate(0, format));
   if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
      ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
}
static void add_peer_mailboxes ( struct sip_peer peer,
const char *  value 
) [static]
Todo:
document this function

Definition at line 24352 of file chan_sip.c.

References ast_calloc, AST_LIST_INSERT_TAIL, AST_LIST_TRAVERSE, ast_strdup, ast_strdupa, ast_strlen_zero(), sip_mailbox::context, context, sip_mailbox::delme, sip_mailbox::mailbox, mailbox, sip_peer::mailboxes, mbox(), sip_request::next, S_OR, and strsep().

Referenced by build_peer().

{
   char *next, *mbox, *context;

   next = ast_strdupa(value);

   while ((mbox = context = strsep(&next, ","))) {
      struct sip_mailbox *mailbox;
      int duplicate = 0;

      strsep(&context, "@");

      if (ast_strlen_zero(mbox)) {
         continue;
      }

      /* Check whether the mailbox is already in the list */
      AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
         if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
            duplicate = 1;
            mailbox->delme = 1;
            break;
         }
      }
      if (duplicate) {
         continue;
      }

      if (!(mailbox = ast_calloc(1, sizeof(*mailbox)))) {
         continue;
      }

      mailbox->mailbox = ast_strdup(mbox);
      mailbox->context = ast_strdup(context);

      AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
   }
}
static struct sip_auth * add_realm_authentication ( struct sip_auth authlist,
const char *  configuration,
int  lineno 
) [static, read]

Add realm authentication in list.

Definition at line 24168 of file chan_sip.c.

References ast_calloc, ast_copy_string(), ast_debug, ast_log(), ast_strlen_zero(), ast_verb, LOG_WARNING, sip_auth::md5secret, sip_auth::next, sip_auth::realm, sip_auth::secret, secret, and sip_auth::username.

Referenced by build_peer(), and reload_config().

{
   char authcopy[256];
   char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
   struct sip_auth *a, *b, *auth;

   if (ast_strlen_zero(configuration))
      return authlist;

   ast_debug(1, "Auth config ::  %s\n", configuration);

   ast_copy_string(authcopy, configuration, sizeof(authcopy));
   username = authcopy;

   /* split user[:secret] and relm */
   realm = strrchr(username, '@');
   if (realm)
      *realm++ = '\0';
   if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
      ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
      return authlist;
   }

   /* parse username at ':' for secret, or '#" for md5secret */
   if ((secret = strchr(username, ':'))) {
      *secret++ = '\0';
   } else if ((md5secret = strchr(username, '#'))) {
      *md5secret++ = '\0';
   }

   if (!(auth = ast_calloc(1, sizeof(*auth))))
      return authlist;

   ast_copy_string(auth->realm, realm, sizeof(auth->realm));
   ast_copy_string(auth->username, username, sizeof(auth->username));
   if (secret)
      ast_copy_string(auth->secret, secret, sizeof(auth->secret));
   if (md5secret)
      ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));

   /* find the end of the list */
   for (b = NULL, a = authlist; a ; b = a, a = a->next)
      ;
   if (b)
      b->next = auth;   /* Add structure add end of list */
   else
      authlist = auth;

   ast_verb(3, "Added authentication for realm %s\n", realm);

   return authlist;

}
static void add_route ( struct sip_request req,
struct sip_route route 
) [static]

Add route header into request per learned route.

Definition at line 9635 of file chan_sip.c.

References add_header(), ast_copy_string(), sip_route::hop, sip_route::next, and SIPBUFSIZE.

Referenced by initreqprep(), and reqprep().

{
   char r[SIPBUFSIZE*2], *p;
   int n, rem = sizeof(r);

   if (!route)
      return;

   p = r;
   for (;route ; route = route->next) {
      n = strlen(route->hop);
      if (rem < n+3) /* we need room for ",<route>" */
         break;
      if (p != r) {  /* add a separator after fist route */
         *p++ = ',';
         --rem;
      }
      *p++ = '<';
      ast_copy_string(p, route->hop, rem); /* cannot fail */
      p += n;
      *p++ = '>';
      rem -= (n+2);
   }
   *p = '\0';
   add_header(req, "Route", r);
}
static enum sip_result add_sdp ( struct sip_request resp,
struct sip_pvt p,
int  oldsdp,
int  add_audio,
int  add_t38 
) [static]

Add Session Description Protocol message.

If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions without modifying the media session in any way.

Definition at line 10514 of file chan_sip.c.

References add_codec_to_sdp(), add_content(), add_header(), add_noncodec_to_sdp(), add_tcodec_to_sdp(), add_vcodec_to_sdp(), ast_codec_pref_index(), ast_debug, AST_FAILURE, AST_FORMAT_AUDIO_MASK, AST_FORMAT_TEXT_MASK, AST_FORMAT_VIDEO_MASK, ast_getformatname_multiple(), ast_inet_ntoa(), ast_internal_timing_enabled(), ast_log(), ast_random(), AST_RTP_MAX, ast_str_alloca, ast_str_append(), ast_strlen_zero(), AST_SUCCESS, AST_T38_RATE_MANAGEMENT_LOCAL_TCF, AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF, ast_test_flag, ast_udptl_get_error_correction_scheme(), ast_udptl_get_local_max_datagram(), ast_udptl_get_us(), ast_verbose(), buf, sip_request::debug, FALSE, ast_control_t38_parameters::fill_bit_removal, sip_pvt::flags, get_our_media_address(), sip_pvt::jointcapability, sip_pvt::jointnoncodeccapability, sip_pvt::lastrtprx, sip_pvt::lastrtptx, LOG_WARNING, sip_pvt::maxcallbitrate, sip_pvt::notext, sip_pvt::novideo, offered_media::offered, sip_pvt::offered_media, t38properties::our_parms, sip_pvt::ourip, sip_pvt::owner, sip_pvt::prefcodec, sip_pvt::prefs, ast_control_t38_parameters::rate, ast_control_t38_parameters::rate_management, sip_pvt::redircodecs, sip_pvt::redirip, sip_pvt::rtp, SDP_AUDIO, SDP_IMAGE, SDP_TEXT, SDP_VIDEO, sip_pvt::sessionid, sip_pvt::sessionversion, sip_debug_test_pvt(), SIP_PAGE2_CALL_ONHOLD, SIP_PAGE2_CALL_ONHOLD_INACTIVE, SIP_PAGE2_CALL_ONHOLD_ONEDIR, SIPBUFSIZE, sip_pvt::t38, t38_get_rate(), offered_media::text, ast_control_t38_parameters::transcoding_jbig, ast_control_t38_parameters::transcoding_mmr, sip_pvt::tredirip, sip_pvt::trtp, TRUE, sip_pvt::udptl, UDPTL_ERROR_CORRECTION_FEC, UDPTL_ERROR_CORRECTION_NONE, UDPTL_ERROR_CORRECTION_REDUNDANCY, sip_pvt::udptlredirip, ast_control_t38_parameters::version, version, and sip_pvt::vrtp.

Referenced by transmit_invite(), transmit_reinvite_with_sdp(), transmit_response_with_sdp(), and transmit_response_with_t38_sdp().

{
   int alreadysent = 0;
   int doing_directmedia = FALSE;

   struct sockaddr_in sin;
   struct sockaddr_in vsin;
   struct sockaddr_in tsin;
   struct sockaddr_in dest;
   struct sockaddr_in udptlsin;
   struct sockaddr_in vdest = { 0, };
   struct sockaddr_in tdest = { 0, };
   struct sockaddr_in udptldest = { 0, };

   /* SDP fields */
   char *version =   "v=0\r\n";     /* Protocol version */
   char subject[256];            /* Subject of the session */
   char owner[256];           /* Session owner/creator */
   char connection[256];            /* Connection data */
   char *session_time = "t=0 0\r\n";         /* Time the session is active */
   char bandwidth[256] = "";        /* Max bitrate */
   char *hold = "";
   struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
   struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
   struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
   struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
   struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
   struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
   struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
   struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */

   int x;
   int capability = 0;
   int needaudio = FALSE;
   int needvideo = FALSE;
   int needtext = FALSE;
   int debug = sip_debug_test_pvt(p);
   int min_audio_packet_size = 0;
   int min_video_packet_size = 0;
   int min_text_packet_size = 0;

   char codecbuf[SIPBUFSIZE];
   char buf[SIPBUFSIZE];
   char dummy_answer[256];

   /* Set the SDP session name */
   snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);

   if (!p->rtp) {
      ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
      return AST_FAILURE;
   }
   /* XXX We should not change properties in the SIP dialog until 
      we have acceptance of the offer if this is a re-invite */

   /* Set RTP Session ID and version */
   if (!p->sessionid) {
      p->sessionid = (int)ast_random();
      p->sessionversion = p->sessionid;
   } else {
      if (oldsdp == FALSE)
         p->sessionversion++;
   }

   if (add_audio) {
      doing_directmedia = (p->redirip.sin_addr.s_addr && p->redircodecs) ? TRUE : FALSE;
      /* Check if we need video in this call */
      if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
         if (p->vrtp) {
            needvideo = TRUE;
            ast_debug(2, "This call needs video offers!\n");
         } else
            ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
      }
      /* Check if we need text in this call */
      if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
         if (sipdebug_text)
            ast_verbose("We think we can do text\n");
         if (p->trtp) {
            if (sipdebug_text) {
               ast_verbose("And we have a text rtp object\n");
            }
            needtext = TRUE;
            ast_debug(2, "This call needs text offers! \n");
         } else {
            ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
         }
      }
   }

   get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);

   snprintf(owner, sizeof(owner), "o=%s %d %d IN IP4 %s\r\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner, p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
   snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));

   if (add_audio) {
      if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
         hold = "a=recvonly\r\n";
         doing_directmedia = FALSE;
      } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
         hold = "a=inactive\r\n";
         doing_directmedia = FALSE;
      } else {
         hold = "a=sendrecv\r\n";
      }

      capability = p->jointcapability;

      /* XXX note, Video and Text are negated - 'true' means 'no' */
      ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), 
           p->novideo ? "True" : "False", p->notext ? "True" : "False");
      ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));

      if (doing_directmedia) {
         capability &= p->redircodecs;
         ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
      }

      /* Check if we need audio */
      if (capability & AST_FORMAT_AUDIO_MASK)
         needaudio = TRUE;

      if (debug) 
         ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port)); 

      /* Ok, we need video. Let's add what we need for video and set codecs.
         Video is handled differently than audio since we can not transcode. */
      if (needvideo) {
         ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));

         /* Build max bitrate string */
         if (p->maxcallbitrate)
            snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
         if (debug) 
            ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));  
      }

      /* Ok, we need text. Let's add what we need for text and set codecs.
         Text is handled differently than audio since we can not transcode. */
      if (needtext) {
         if (sipdebug_text)
            ast_verbose("Lets set up the text sdp\n");
         /* Determine text destination */
         if (p->tredirip.sin_addr.s_addr) {
            tdest.sin_addr = p->tredirip.sin_addr;
            tdest.sin_port = p->tredirip.sin_port;
         } else {
            tdest.sin_addr = p->ourip.sin_addr;
            tdest.sin_port = tsin.sin_port;
         }
         ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
         if (debug) /* XXX should I use tdest below ? */
            ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port)); 

      }

      /* Start building generic SDP headers */

      /* We break with the "recommendation" and send our IP, in order that our
         peer doesn't have to ast_gethostbyname() us */

      ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));

      /* Now, start adding audio codecs. These are added in this order:
         - First what was requested by the calling channel
         - Then preferences in order from sip.conf device config for this peer/user
         - Then other codecs in capabilities, including video
      */

      /* Prefer the audio codec we were requested to use, first, no matter what 
         Note that p->prefcodec can include video codecs, so mask them out
      */
      if (capability & p->prefcodec) {
         int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;

         add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
         alreadysent |= codec;
      }

      /* Start by sending our preferred audio/video codecs */
      for (x = 0; x < 32; x++) {
         int codec;

         if (!(codec = ast_codec_pref_index(&p->prefs, x)))
            break; 

         if (!(capability & codec))
            continue;

         if (alreadysent & codec)
            continue;

         add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
         alreadysent |= codec;
      }

      /* Now send any other common audio and video codecs, and non-codec formats: */
      for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
         if (!(capability & x))  /* Codec not requested */
            continue;

         if (alreadysent & x) /* Already added to SDP */
            continue;

         if (x & AST_FORMAT_AUDIO_MASK)
            add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
         else if (x & AST_FORMAT_VIDEO_MASK)
            add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
         else if (x & AST_FORMAT_TEXT_MASK)
            add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
      }

      /* Now add DTMF RFC2833 telephony-event as a codec */
      for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
         if (!(p->jointnoncodeccapability & x))
            continue;

         add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
      }

      ast_debug(3, "-- Done with adding codecs to SDP\n");

      if (!p->owner || !ast_internal_timing_enabled(p->owner))
         ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");

      if (min_audio_packet_size)
         ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);

      /* XXX don't think you can have ptime for video */
      if (min_video_packet_size)
         ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);

      /* XXX don't think you can have ptime for text */
      if (min_text_packet_size)
         ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
 
      if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
          m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
          a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
         ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
   }

   if (add_t38) {
      /* Our T.38 end is */
      ast_udptl_get_us(p->udptl, &udptlsin);

      /* Determine T.38 UDPTL destination */
      if (p->udptlredirip.sin_addr.s_addr) {
         udptldest.sin_port = p->udptlredirip.sin_port;
         udptldest.sin_addr = p->udptlredirip.sin_addr;
      } else {
         udptldest.sin_addr = p->ourip.sin_addr;
         udptldest.sin_port = udptlsin.sin_port;
      }

      if (debug)
         ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));

      /* We break with the "recommendation" and send our IP, in order that our
         peer doesn't have to ast_gethostbyname() us */

      ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));

      ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
      ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
      if (p->t38.our_parms.fill_bit_removal) {
         ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
      }
      if (p->t38.our_parms.transcoding_mmr) {
         ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
      }
      if (p->t38.our_parms.transcoding_jbig) {
         ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
      }
      switch (p->t38.our_parms.rate_management) {
      case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
         ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
         break;
      case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
         ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
         break;
      }
      ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
      switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
      case UDPTL_ERROR_CORRECTION_NONE:
         break;
      case UDPTL_ERROR_CORRECTION_FEC:
         ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
         break;
      case UDPTL_ERROR_CORRECTION_REDUNDANCY:
         ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
         break;
      }
   }

   if (needaudio)
      ast_str_append(&m_audio, 0, "\r\n");
   if (needvideo)
      ast_str_append(&m_video, 0, "\r\n");
   if (needtext)
      ast_str_append(&m_text, 0, "\r\n");

   add_header(resp, "Content-Type", "application/sdp");
   add_content(resp, version);
   add_content(resp, owner);
   add_content(resp, subject);
   add_content(resp, connection);
   if (needvideo)    /* only if video response is appropriate */
      add_content(resp, bandwidth);
   add_content(resp, session_time);
   if (needaudio) {
      add_content(resp, m_audio->str);
      add_content(resp, a_audio->str);
      add_content(resp, hold);
   } else if (p->offered_media[SDP_AUDIO].offered) {
      snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
      add_content(resp, dummy_answer);
   }
   if (needvideo) { /* only if video response is appropriate */
      add_content(resp, m_video->str);
      add_content(resp, a_video->str);
      add_content(resp, hold);   /* Repeat hold for the video stream */
   } else if (p->offered_media[SDP_VIDEO].offered) {
      snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
      add_content(resp, dummy_answer);
   }
   if (needtext) { /* only if text response is appropriate */
      add_content(resp, m_text->str);
      add_content(resp, a_text->str);
      add_content(resp, hold);   /* Repeat hold for the text stream */
   } else if (p->offered_media[SDP_TEXT].offered) {
      snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
      add_content(resp, dummy_answer);
   }
   if (add_t38) {
      add_content(resp, m_modem->str);
      add_content(resp, a_modem->str);
   } else if (p->offered_media[SDP_IMAGE].offered) {
      add_content(resp, "m=image 0 udptl t38\r\n");
   }

   /* Update lastrtprx when we send our SDP */
   p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */

   ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));

   return AST_SUCCESS;
}
static int add_sip_domain ( const char *  domain,
const enum domain_mode  mode,
const char *  context 
) [static]

Add SIP domain to list of domains we are responsible for.

Definition at line 24104 of file chan_sip.c.

References ast_calloc, ast_copy_string(), ast_debug, AST_LIST_INSERT_TAIL, AST_LIST_LOCK, AST_LIST_UNLOCK, ast_log(), ast_strlen_zero(), domain::context, domain::domain, LOG_WARNING, and domain::mode.

Referenced by reload_config().

{
   struct domain *d;

   if (ast_strlen_zero(domain)) {
      ast_log(LOG_WARNING, "Zero length domain.\n");
      return 1;
   }

   if (!(d = ast_calloc(1, sizeof(*d))))
      return 0;

   ast_copy_string(d->domain, domain, sizeof(d->domain));

   if (!ast_strlen_zero(context))
      ast_copy_string(d->context, context, sizeof(d->context));

   d->mode = mode;

   AST_LIST_LOCK(&domain_list);
   AST_LIST_INSERT_TAIL(&domain_list, d, list);
   AST_LIST_UNLOCK(&domain_list);

   if (sipdebug)  
      ast_debug(1, "Added local SIP domain '%s'\n", domain);

   return 1;
}
static int add_supported_header ( struct sip_pvt pvt,
struct sip_request req 
) [static]

Add "Supported" header to sip message. Since some options may be disabled in the config, the sip_pvt must be inspected to determine what is supported for this dialog.

Definition at line 9464 of file chan_sip.c.

References add_header(), SESSION_TIMER_MODE_REFUSE, and st_get_mode().

Referenced by respprep(), transmit_invite(), transmit_notify_with_sipfrag(), transmit_refer(), and transmit_reinvite_with_sdp().

{
   int res;
   if (st_get_mode(pvt) != SESSION_TIMER_MODE_REFUSE) {
      res = add_header(req, "Supported", "replaces, timer");
   } else {
      res = add_header(req, "Supported", "replaces");
   }
   return res;
}
static void add_tcodec_to_sdp ( const struct sip_pvt p,
int  codec,
struct ast_str **  m_buf,
struct ast_str **  a_buf,
int  debug,
int *  min_packet_size 
) [static]

Add text codec offer to SDP offer/answer body in INVITE or 200 OK.

Definition at line 10400 of file chan_sip.c.

References AST_FORMAT_T140, AST_FORMAT_T140RED, ast_getformatname(), ast_rtp_lookup_code(), ast_rtp_lookup_mime_subtype(), ast_rtp_lookup_sample_rate(), ast_str_append(), ast_verbose(), and sip_pvt::trtp.

Referenced by add_sdp().

{
   int rtp_code;

   if (!p->trtp)
      return;

   if (debug)
      ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));

   if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
      return;

   ast_str_append(m_buf, 0, " %d", rtp_code);
   ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
             ast_rtp_lookup_mime_subtype(1, codec, 0),
             ast_rtp_lookup_sample_rate(1, codec));
   /* Add fmtp code here */

   if (codec == AST_FORMAT_T140RED) {
      ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
          ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
          ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
          ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));

   }
}
static int add_text ( struct sip_request req,
const char *  text 
) [static]

Add text body to SIP message.

Definition at line 10262 of file chan_sip.c.

References add_content(), and add_header().

Referenced by transmit_message_with_text().

{
   /* XXX Convert \n's to \r\n's XXX */
   add_header(req, "Content-Type", "text/plain;charset=UTF-8");
   add_content(req, text);
   return 0;
}
static struct ast_variable* add_var ( const char *  buf,
struct ast_variable list 
) [static, read]

implement the setvar config line

Definition at line 24253 of file chan_sip.c.

References ast_strdupa, ast_variable_new(), and ast_variable::next.

Referenced by build_peer().

{
   struct ast_variable *tmpvar = NULL;
   char *varname = ast_strdupa(buf), *varval = NULL;
   
   if ((varval = strchr(varname, '='))) {
      *varval++ = '\0';
      if ((tmpvar = ast_variable_new(varname, varval, ""))) {
         tmpvar->next = list;
         list = tmpvar;
      }
   }
   return list;
}
static void add_vcodec_to_sdp ( const struct sip_pvt p,
int  codec,
struct ast_str **  m_buf,
struct ast_str **  a_buf,
int  debug,
int *  min_packet_size 
) [static]

Add video codec offer to SDP offer/answer body in INVITE or 200 OK.

Definition at line 10377 of file chan_sip.c.

References ast_getformatname(), ast_rtp_lookup_code(), ast_rtp_lookup_mime_subtype(), ast_rtp_lookup_sample_rate(), ast_str_append(), ast_verbose(), and sip_pvt::vrtp.

Referenced by add_sdp().

{
   int rtp_code;

   if (!p->vrtp)
      return;

   if (debug)
      ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));

   if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
      return;

   ast_str_append(m_buf, 0, " %d", rtp_code);
   ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
             ast_rtp_lookup_mime_subtype(1, codec, 0),
             ast_rtp_lookup_sample_rate(1, codec));
   /* Add fmtp code here */
}
static int add_vidupdate ( struct sip_request req) [static]

add XML encoded media control with update

Note:
XML: The only way to turn 0 bits of information into a few hundred. (markster)

Definition at line 10302 of file chan_sip.c.

References add_content(), and add_header().

Referenced by transmit_info_with_vidupdate().

{
   const char *xml_is_a_huge_waste_of_space =
      "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
      " <media_control>\r\n"
      "  <vc_primitive>\r\n"
      "   <to_encoder>\r\n"
      "    <picture_fast_update>\r\n"
      "    </picture_fast_update>\r\n"
      "   </to_encoder>\r\n"
      "  </vc_primitive>\r\n"
      " </media_control>\r\n";
   add_header(req, "Content-Type", "application/media_control+xml");
   add_content(req, xml_is_a_huge_waste_of_space);
   return 0;
}
static int addr_is_multicast ( struct in_addr *  addr) [static]

Check if an ip is an multicast IP. addr the address to check.

This function checks if an address is in the 224.0.0.0/4 network block.

Returns:
non-zero if this is a multicast address

Definition at line 7672 of file chan_sip.c.

Referenced by process_via().

{
   return ((ntohl(addr->s_addr) & 0xf0000000) == 0xe0000000);
}
static void append_date ( struct sip_request req) [static]

Append date to SIP message.

Definition at line 10199 of file chan_sip.c.

References add_header().

Referenced by transmit_invite(), transmit_response_with_date(), transmit_response_with_minse(), and transmit_response_with_unsupported().

{
   char tmpdat[256];
   struct tm tm;
   time_t t = time(NULL);

   gmtime_r(&t, &tm);
   strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
   add_header(req, "Date", tmpdat);
}
static void append_history_full ( struct sip_pvt p,
const char *  fmt,
  ... 
) [static]

Append to SIP dialog history with arg list.

Definition at line 3896 of file chan_sip.c.

References append_history_va(), and sip_pvt::do_history.

{
   va_list ap;

   if (!p)
      return;

   if (!p->do_history && !recordhistory && !dumphistory)
      return;

   va_start(ap, fmt);
   append_history_va(p, fmt, ap);
   va_end(ap);

   return;
}
static void append_history_va ( struct sip_pvt p,
const char *  fmt,
va_list  ap 
) [static]

Append to SIP dialog history with arg list.

Definition at line 3869 of file chan_sip.c.

References ast_calloc, ast_free, AST_LIST_INSERT_TAIL, AST_LIST_REMOVE_HEAD, buf, sip_history::event, MAX_HISTORY_ENTRIES, and strsep().

Referenced by append_history_full().

{
   char buf[80], *c = buf; /* max history length */
   struct sip_history *hist;
   int l;

   vsnprintf(buf, sizeof(buf), fmt, ap);
   strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
   l = strlen(buf) + 1;
   if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
      return;
   if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
      ast_free(hist);
      return;
   }
   memcpy(hist->event, buf, l);
   if (p->history_entries == MAX_HISTORY_ENTRIES) {
      struct sip_history *oldest;
      oldest = AST_LIST_REMOVE_HEAD(p->history, list);
      p->history_entries--;
      ast_free(oldest);
   }
   AST_LIST_INSERT_TAIL(p->history, hist, list);
   p->history_entries++;
}
static void ast_quiet_chan ( struct ast_channel chan) [static]

Turn off generator data XXX Does this function belong in the SIP channel?

Definition at line 19474 of file chan_sip.c.

References ast_channel::_state, ast_deactivate_generator(), AST_FLAG_MOH, ast_moh_stop(), AST_STATE_UP, ast_test_flag, and ast_channel::generatordata.

Referenced by attempt_transfer(), and handle_invite_replaces().

{
   if (chan && chan->_state == AST_STATE_UP) {
      if (ast_test_flag(chan, AST_FLAG_MOH))
         ast_moh_stop(chan);
      else if (chan->generatordata)
         ast_deactivate_generator(chan);
   }
}
static void ast_sip_ouraddrfor ( struct in_addr *  them,
struct sockaddr_in *  us,
struct sip_pvt p 
) [static]

NAT fix - decide which IP address to use for Asterisk server?

Using the localaddr structure built up with localnet statements in sip.conf apply it to their address to see if we need to substitute our externip or can get away with our internal bindaddr 'us' is always overwritten.

Definition at line 3794 of file chan_sip.c.

References ast_apply_ha(), ast_debug, ast_inet_ntoa(), ast_log(), ast_ouraddrfor(), ast_parse_arg(), AST_SENSE_ALLOW, ast_stun_request(), bindaddr, externexpire, externip, externrefresh, get_transport(), internip, ast_tcptls_session_args::local_address, LOG_NOTICE, LOG_WARNING, sip_settings::matchexterniplocally, PARSE_INADDR, sip_cfg, SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, SIP_TRANSPORT_UDP, sip_pvt::socket, stunaddr, and sip_socket::type.

Referenced by __sip_subscribe_mwi_do(), manager_sipnotify(), sip_alloc(), sip_cli_notify(), sip_poke_peer(), sip_request_call(), sip_send_mwi_to_peer(), transmit_register(), and transmit_response_using_temp().

{
   struct sockaddr_in theirs;
   /* Set want_remap to non-zero if we want to remap 'us' to an externally
    * reachable IP address and port. This is done if:
    * 1. we have a localaddr list (containing 'internal' addresses marked
    *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
    *    and AST_SENSE_ALLOW on 'external' ones);
    * 2. either stunaddr or externip is set, so we know what to use as the
    *    externally visible address;
    * 3. the remote address, 'them', is external;
    * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
    *    when passed to ast_apply_ha() so it does need to be remapped.
    *    This fourth condition is checked later.
    */
   int want_remap;

   *us = internip;      /* starting guess for the internal address */
   /* now ask the system what would it use to talk to 'them' */
   ast_ouraddrfor(them, &us->sin_addr);
   theirs.sin_addr = *them;

   want_remap = localaddr &&
      (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
      ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;

   if (want_remap &&
       (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
      /* if we used externhost or stun, see if it is time to refresh the info */
      if (externexpire && time(NULL) >= externexpire) {
         if (stunaddr.sin_addr.s_addr) {
            ast_stun_request(sipsock, &stunaddr, NULL, &externip);
         } else {
            if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
               ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
         }
         externexpire = time(NULL) + externrefresh;
      }
      if (externip.sin_addr.s_addr)
         *us = externip;
      else
         ast_log(LOG_WARNING, "stun failed\n");
      ast_debug(1, "Target address %s is not local, substituting externip\n", 
         ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
   } else if (p) {
      /* no remapping, but we bind to a specific address, so use it. */
      switch (p->socket.type) {
      case SIP_TRANSPORT_TCP:
         if (sip_tcp_desc.local_address.sin_addr.s_addr) {
            *us = sip_tcp_desc.local_address;
         } else {
            us->sin_port = sip_tcp_desc.local_address.sin_port;
         }
         break;
      case SIP_TRANSPORT_TLS:
         if (sip_tls_desc.local_address.sin_addr.s_addr) {
            *us = sip_tls_desc.local_address;
         } else {
            us->sin_port = sip_tls_desc.local_address.sin_port;
         }
            break;
      case SIP_TRANSPORT_UDP:
         /* fall through on purpose */
      default:
         if (bindaddr.sin_addr.s_addr) {
            *us = bindaddr;
         }
      }
   } else if (bindaddr.sin_addr.s_addr) {
      *us = bindaddr;
   }
   ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s:%d\n", get_transport(p->socket.type), ast_inet_ntoa(us->sin_addr), ntohs(us->sin_port));
}
AST_THREADSTORAGE_CUSTOM_SCOPE ( ts_temp_pvt  ,
temp_pvt_init  ,
temp_pvt_cleanup  ,
static   
)

A per-thread temporary pvt structure.

AST_THREADSTORAGE_CUSTOM_SCOPE ( check_auth_buf  ,
NULL  ,
ast_free_ptr  ,
static   
)
static int attempt_transfer ( struct sip_dual transferer,
struct sip_dual target 
) [static]

Attempt transfer of SIP call This fix for attended transfers on a local PBX.

Definition at line 19486 of file chan_sip.c.

References ast_channel::_state, ast_channel_masquerade(), ast_debug, ast_log(), ast_quiet_chan(), AST_SOFTHANGUP_DEV, ast_softhangup_nolock(), ast_state2str(), sip_dual::chan1, sip_dual::chan2, LOG_NOTICE, LOG_WARNING, and ast_channel::name.

Referenced by local_attended_transfer().

{
   int res = 0;
   struct ast_channel *peera = NULL,   
      *peerb = NULL,
      *peerc = NULL,
      *peerd = NULL;


   /* We will try to connect the transferee with the target and hangup
      all channels to the transferer */   
   ast_debug(4, "Sip transfer:--------------------\n");
   if (transferer->chan1)
      ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
   else
      ast_debug(4, "-- No transferer first channel - odd??? \n");
   if (target->chan1)
      ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
   else
      ast_debug(4, "-- No target first channel ---\n");
   if (transferer->chan2)
      ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
   else
      ast_debug(4, "-- No bridged call to transferee\n");
   if (target->chan2)
      ast_debug(4, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
   else
      ast_debug(4, "-- No target second channel ---\n");
   ast_debug(4, "-- END Sip transfer:--------------------\n");
   if (transferer->chan2) { /* We have a bridge on the transferer's channel */
      peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
      peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
      peerc = transferer->chan2; /* Asterisk to Transferee */
      peerd = target->chan2;     /* Asterisk to Target */
      ast_debug(3, "SIP transfer: Four channels to handle\n");
   } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
      peera = target->chan1;     /* Transferer to PBX -> target channel */
      peerb = transferer->chan1; /* Transferer to IVR*/
      peerc = target->chan2;     /* Asterisk to Target */
      peerd = transferer->chan2; /* Nothing */
      ast_debug(3, "SIP transfer: Three channels to handle\n");
   }

   if (peera && peerb && peerc && (peerb != peerc)) {
      ast_quiet_chan(peera);     /* Stop generators */
      ast_quiet_chan(peerb);  
      ast_quiet_chan(peerc);
      if (peerd)
         ast_quiet_chan(peerd);

      ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
      if (ast_channel_masquerade(peerb, peerc)) {
         ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
         res = -1;
      } else
         ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
      return res;
   } else {
      ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
      if (transferer->chan1)
         ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
      if (target->chan1)
         ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
      return -1;
   }
   return 0;
}
static void auth_headers ( enum sip_auth_type  code,
char **  header,
char **  respheader 
) [static]

return the request and response heade for a 401 or 407 code

Definition at line 12439 of file chan_sip.c.

References ast_verbose(), PROXY_AUTH, and WWW_AUTH.

Referenced by check_auth(), do_proxy_auth(), do_register_auth(), and transmit_request_with_auth().

{
   if (code == WWW_AUTH) {       /* 401 */
      *header = "WWW-Authenticate";
      *respheader = "Authorization";
   } else if (code == PROXY_AUTH) { /* 407 */
      *header = "Proxy-Authenticate";
      *respheader = "Proxy-Authorization";
   } else {
      ast_verbose("-- wrong response code %d\n", code);
      *header = *respheader = "Invalid";
   }
}
static int auto_congest ( const void *  arg) [static]

Scheduled congestion on a call. Only called by the scheduler, must return the reference when done.

Definition at line 5559 of file chan_sip.c.

References append_history, ast_channel_trylock, ast_channel_unlock, AST_CONTROL_CONGESTION, ast_queue_control(), DEFAULT_TRANS_TIMEOUT, dialog_unref(), sip_pvt::initid, sip_pvt::owner, sip_pvt_lock, sip_pvt_unlock, and sip_scheddestroy().

Referenced by sip_call(), and sip_show_sched().

{
   struct sip_pvt *p = (struct sip_pvt *)arg;

   sip_pvt_lock(p);
   p->initid = -1;   /* event gone, will not be rescheduled */
   if (p->owner) {
      /* XXX fails on possible deadlock */
      if (!ast_channel_trylock(p->owner)) {
         append_history(p, "Cong", "Auto-congesting (timer)");
         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
         ast_channel_unlock(p->owner);
      }

      /* Give the channel a chance to act before we proceed with destruction */
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
   }
   sip_pvt_unlock(p);
   dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
   return 0;
}
static void build_callid_pvt ( struct sip_pvt pvt) [static]

Build SIP Call-ID value for a non-REGISTER transaction.

Definition at line 7346 of file chan_sip.c.

References ast_inet_ntoa(), ast_string_field_build, buf, sip_pvt::callid, sip_pvt::fromdomain, generate_random_string(), sip_pvt::ourip, and S_OR.

Referenced by __sip_subscribe_mwi_do(), manager_sipnotify(), sip_alloc(), sip_cli_notify(), sip_poke_peer(), sip_request_call(), and sip_send_mwi_to_peer().

{
   char buf[33];

   const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
   
   ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);

}
static void build_callid_registry ( struct sip_registry reg,
struct in_addr  ourip,
const char *  fromdomain 
) [static]

Build SIP Call-ID value for a REGISTER transaction.

Definition at line 7357 of file chan_sip.c.

References ast_inet_ntoa(), ast_string_field_build, buf, sip_pvt::callid, generate_random_string(), and S_OR.

Referenced by transmit_register().

{
   char buf[33];

   const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));

   ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
}
static void build_contact ( struct sip_pvt p) [static]

Build contact header - the contact header we send out.

Definition at line 11058 of file chan_sip.c.

References ast_inet_ntoa(), ast_string_field_build, ast_strlen_zero(), ast_uri_encode(), sip_pvt::exten, get_transport(), sip_pvt::ourip, ourport, sip_standard_port(), SIP_TRANSPORT_UDP, SIPBUFSIZE, sip_pvt::socket, and sip_socket::type.

Referenced by __sip_subscribe_mwi_do(), check_user_full(), handle_request_invite(), handle_request_options(), handle_request_subscribe(), initreqprep(), register_verify(), and transmit_register().

{
   char tmp[SIPBUFSIZE];
   char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 1);
   int ourport = ntohs(p->ourip.sin_port);

   /* only add port if it's non-standard for the transport type */
   if (!sip_standard_port(p->socket.type, ourport)) {
      if (p->socket.type == SIP_TRANSPORT_UDP)
         ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport);
      else
         ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d;transport=%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
   } else {
      if (p->socket.type == SIP_TRANSPORT_UDP)
         ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
      else
         ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
   }
}
static struct sip_peer * build_peer ( const char *  name,
struct ast_variable v,
struct ast_variable alt,
int  realtime,
int  devstate_only 
) [static, read]

Build peer from configuration (file or realtime static/dynamic)

< The first transport listed should be default outbound

Definition at line 24392 of file chan_sip.c.

References __set_address_from_contact(), accountcode, add_peer_mailboxes(), add_peer_mwi_subs(), add_realm_authentication(), add_var(), sip_peer::addr, sip_settings::allowsubscribe, sip_peer::allowtransfer, sip_peer::amaflags, ao2_t_alloc, ao2_t_find, ao2_t_ref, asprintf, ast_append_ha(), ast_atomic_fetchadd_int(), ast_callerid_split(), ast_cdr_amaflags2int(), ast_copy_flags, ast_copy_string(), ast_debug, ast_dnsmgr_lookup(), ast_free, ast_free_ha(), ast_get_group(), ast_get_ip(), ast_get_time_t(), ast_inet_ntoa(), AST_LIST_EMPTY, AST_LIST_REMOVE_CURRENT, AST_LIST_TRAVERSE, AST_LIST_TRAVERSE_SAFE_BEGIN, AST_LIST_TRAVERSE_SAFE_END, ast_log(), ast_parse_allow_disallow(), ast_parse_caller_presentation(), AST_SCHED_DEL_UNREF, ast_set2_flag, ast_set_flag, ast_skip_blanks(), ast_str_alloca, ast_str_append(), ast_str_buffer(), ast_str_reset(), ast_str_set(), ast_str_strlen(), ast_strdupa, ast_string_field_init, ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_true(), ast_variables_destroy(), sip_peer::auth, sip_peer::autoframing, sip_peer::busy_level, sip_peer::call_limit, sip_peer::callgroup, sip_peer::callingpres, sip_peer::capability, sip_peer::chanvars, cid_name, cid_num, clear_realm_authentication(), sip_peer::contactha, context, sip_peer::defaddr, default_maxcallbitrate, DEFAULT_MAXMS, sip_peer::default_outbound_transport, default_primary_transport, default_transports, sip_mailbox::delme, sip_peer::deprecated_username, destroy_association(), destroy_mailbox(), sip_peer::dnsmgr, errno, sip_peer::expire, FALSE, ast_flags::flags, sip_peer::flags, format, get_srv_protocol(), get_srv_service(), global_max_se, global_min_se, global_qualifyfreq, global_rtpholdtimeout, global_rtpkeepalive, global_rtptimeout, global_st_mode, global_st_refresher, global_t1, global_timer_b, sip_peer::ha, handle_common_options(), handle_t38_options(), sip_peer::host_dynamic, sip_settings::ignore_regexpire, inet_aton(), sip_peer::is_realtime, language, sip_peer::lastms, sip_peer::lastmsgssent, ast_variable::lineno, LOG_ERROR, LOG_NOTICE, LOG_WARNING, mailbox, sip_peer::mailboxes, sip_peer::maxcallbitrate, MAXHOSTNAMELEN, sip_peer::maxms, mohinterpret, mohsuggest, ast_variable::name, sip_peer::name, sip_request::next, ast_variable::next, OBJ_POINTER, OBJ_UNLINK, sip_peer::outboundproxy, parkinglot, sip_peer::pickupgroup, sip_socket::port, port_str2int(), sip_peer::portinuri, sip_peer::prefs, proxy_allocate(), sip_peer::qualifyfreq, ref_peer(), reg_source_db(), sip_peer::remotesecret, sip_peer::rt_fromcontact, sip_peer::rtpholdtimeout, sip_peer::rtpkeepalive, sip_peer::rtptimeout, sip_peer::secret, secret, set_peer_defaults(), set_socket_transport(), sip_cfg, sip_destroy_peer_fn(), SIP_NAT_ROUTE, SIP_PAGE2_ALLOWSUBSCRIBE, SIP_PAGE2_HAVEPEERCONTEXT, SIP_PAGE2_REGISTERTRYING, SIP_PAGE2_RTCACHEFRIENDS, SIP_PAGE2_SUBSCRIBEMWIONLY, sip_poke_peer(), sip_register(), sip_send_mwi_to_peer(), SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, SIP_TRANSPORT_UDP, SIP_TYPE_PEER, SIP_TYPE_USER, SIP_USEREQPHONE, sip_peer::socket, sip_settings::srvlookup, srvlookup, sip_st_cfg::st_max_se, sip_st_cfg::st_min_se, sip_st_cfg::st_mode_oper, sip_st_cfg::st_ref, STANDARD_SIP_PORT, STANDARD_TLS_PORT, sip_peer::stimer, str2stmode(), str2strefresher(), strsep(), sip_peer::t38_maxdatagram, sip_peer::the_mark, sip_peer::timer_b, sip_peer::timer_t1, sip_peer::tohost, TRANSFER_CLOSED, TRANSFER_OPENFORALL, sip_peer::transports, TRUE, sip_socket::type, sip_peer::type, unref_peer(), sip_peer::username, and ast_variable::value.

Referenced by realtime_peer(), and reload_config().

{
   struct sip_peer *peer = NULL;
   struct ast_ha *oldha = NULL;
   int found = 0;
   int firstpass = 1;
   uint16_t port = 0;
   int format = 0;      /* Ama flags */
   time_t regseconds = 0;
   struct ast_flags peerflags[2] = {{(0)}};
   struct ast_flags mask[2] = {{(0)}};
   char callback[256] = "";
   struct sip_peer tmp_peer;
   const char *srvlookup = NULL;
   static int deprecation_warning = 1;
   int alt_fullcontact = alt ? 1 : 0;
   struct ast_str *fullcontact = ast_str_alloca(512);

   if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
      /* Note we do NOT use find_peer here, to avoid realtime recursion */
      /* We also use a case-sensitive comparison (unlike find_peer) so
         that case changes made to the peer name will be properly handled
         during reload
      */
      ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
      peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
   }

   if (peer) {
      /* Already in the list, remove it and it will be added back (or FREE'd)  */
      found++;
      if (!(peer->the_mark))
         firstpass = 0;
   } else {
      if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
         return NULL;

      if (ast_string_field_init(peer, 512)) {
         ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
         return NULL;
      }

      if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
         ast_atomic_fetchadd_int(&rpeerobjs, 1);
         ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
      } else
         ast_atomic_fetchadd_int(&speerobjs, 1);
   }

   /* Note that our peer HAS had its reference count increased */
   if (firstpass) {
      peer->lastmsgssent = -1;
      oldha = peer->ha;
      peer->ha = NULL;
      set_peer_defaults(peer);   /* Set peer defaults */
      peer->type = 0;
   }
   if (!found && name)
      ast_copy_string(peer->name, name, sizeof(peer->name));

   /* If we have channel variables, remove them (reload) */
   if (peer->chanvars) {
      ast_variables_destroy(peer->chanvars);
      peer->chanvars = NULL;
      /* XXX should unregister ? */
   }

   if (found)
      peer->portinuri = 0;

   /* If we have realm authentication information, remove them (reload) */
   clear_realm_authentication(peer->auth);
   peer->auth = NULL;
   /* clear the transport information.  We will detect if a default value is required after parsing the config */
   peer->default_outbound_transport = 0;
   peer->transports = 0;

   if (!devstate_only) {
      struct sip_mailbox *mailbox;
      AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
         mailbox->delme = 1;
      }
   }

   for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
      if (!devstate_only) {
         if (handle_common_options(&peerflags[0], &mask[0], v)) {
            continue;
         }
         if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
            continue;
         }
         if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
            char *val = ast_strdupa(v->value);
            char *trans;

            while ((trans = strsep(&val, ","))) {
               trans = ast_skip_blanks(trans);

               if (!strncasecmp(trans, "udp", 3)) {
                  peer->transports |= SIP_TRANSPORT_UDP;
               } else if (!strncasecmp(trans, "tcp", 3)) {
                  peer->transports |= SIP_TRANSPORT_TCP;
               } else if (!strncasecmp(trans, "tls", 3)) {
                  peer->transports |= SIP_TRANSPORT_TLS;
               } else {
                  ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
               }

               if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
                  peer->default_outbound_transport = peer->transports;
               }
            }
         } else if (realtime && !strcasecmp(v->name, "regseconds")) {
            ast_get_time_t(v->value, &regseconds, 0, NULL);
         } else if (realtime && !strcasecmp(v->name, "name")) {
            ast_copy_string(peer->name, v->value, sizeof(peer->name));
         } else if (realtime && !strcasecmp(v->name, "useragent")) {
            ast_string_field_set(peer, useragent, v->value);
         } else if (!strcasecmp(v->name, "type")) {
            if (!strcasecmp(v->value, "peer")) {
               peer->type |= SIP_TYPE_PEER;
            } else if (!strcasecmp(v->value, "user")) {
               peer->type |= SIP_TYPE_USER;
            } else if (!strcasecmp(v->value, "friend")) {
               peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
            }
         } else if (!strcasecmp(v->name, "remotesecret")) {
            ast_string_field_set(peer, remotesecret, v->value);
         } else if (!strcasecmp(v->name, "secret")) {
            ast_string_field_set(peer, secret, v->value);
         } else if (!strcasecmp(v->name, "md5secret")) {
            ast_string_field_set(peer, md5secret, v->value);
         } else if (!strcasecmp(v->name, "auth")) {
            peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
         } else if (!strcasecmp(v->name, "callerid")) {
            char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };

            ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
            ast_string_field_set(peer, cid_name, cid_name);
            ast_string_field_set(peer, cid_num, cid_num);
         } else if (!strcasecmp(v->name, "fullname")) {
            ast_string_field_set(peer, cid_name, v->value);
         } else if (!strcasecmp(v->name, "trunkname")) {
            /* This is actually for a trunk, so we don't want to override callerid */
            ast_string_field_set(peer, cid_name, "");
         } else if (!strcasecmp(v->name, "cid_number")) {
            ast_string_field_set(peer, cid_num, v->value);
         } else if (!strcasecmp(v->name, "context")) {
            ast_string_field_set(peer, context, v->value);
            ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
         } else if (!strcasecmp(v->name, "subscribecontext")) {
            ast_string_field_set(peer, subscribecontext, v->value);
         } else if (!strcasecmp(v->name, "fromdomain")) {
            ast_string_field_set(peer, fromdomain, v->value);
         } else if (!strcasecmp(v->name, "usereqphone")) {
            ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
         } else if (!strcasecmp(v->name, "fromuser")) {
            ast_string_field_set(peer, fromuser, v->value);
         } else if (!strcasecmp(v->name, "outboundproxy")) {
            char *port, *next, *force, *proxyname;
            int forceopt = FALSE;
            /* Set peer channel variable */
            next = proxyname = ast_strdupa(v->value);
            if ((port = strchr(proxyname, ':'))) {
               *port++ = '\0';
               next = port;
            }
            if ((force = strchr(next, ','))) {
               *force++ = '\0';
               forceopt = strcmp(force, "force");
            }
            /* Allocate proxy object */
            peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
         } else if (!strcasecmp(v->name, "host")) {
            if (!strcasecmp(v->value, "dynamic")) {
               /* They'll register with us */
               if (!found || !peer->host_dynamic) {
                  /* Initialize stuff if this is a new peer, or if it used to
                   * not be dynamic before the reload. */
                  memset(&peer->addr.sin_addr, 0, 4);
                  peer->addr.sin_port = 0;
               }
               peer->host_dynamic = TRUE;
            } else {
               /* Non-dynamic.  Make sure we become that way if we're not */
               AST_SCHED_DEL_UNREF(sched, peer->expire,
                     unref_peer(peer, "removing register expire ref"));
               /* the port will either be set to a default value or a config specified value once all option parsing is complete */
               peer->addr.sin_port = 0;
               peer->host_dynamic = FALSE;
               srvlookup = v->value;
            }
         } else if (!strcasecmp(v->name, "defaultip")) {
            if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
               unref_peer(peer, "unref_peer: from build_peer defaultip");
               return NULL;
            }
         } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
            int ha_error = 0;
            if (!ast_strlen_zero(v->value)) {
               peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
            }
            if (ha_error) {
               ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
            }
         } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
            int ha_error = 0;
            if (!ast_strlen_zero(v->value)) {
               peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
            }
            if (ha_error) {
               ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
            }
         } else if (!strcasecmp(v->name, "port")) {
            peer->portinuri = 1;
            if (!(port = port_str2int(v->value, 0))) {
               if (realtime) {
                  /* If stored as integer, could be 0 for some DBs (notably MySQL) */
                  peer->portinuri = 0;
               } else {
                  ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
               }
            }
         } else if (!strcasecmp(v->name, "callingpres")) {
            peer->callingpres = ast_parse_caller_presentation(v->value);
            if (peer->callingpres == -1) {
               peer->callingpres = atoi(v->value);
            }
         } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
            ast_string_field_set(peer, username, v->value);
            if (!strcasecmp(v->name, "username")) {
               if (deprecation_warning) {
                  ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
                  deprecation_warning = 0;
               }
               peer->deprecated_username = 1;
            }
         } else if (!strcasecmp(v->name, "language")) {
            ast_string_field_set(peer, language, v->value);
         } else if (!strcasecmp(v->name, "regexten")) {
            ast_string_field_set(peer, regexten, v->value);
         } else if (!strcasecmp(v->name, "callbackextension")) {
            ast_copy_string(callback, v->value, sizeof(callback));
         } else if (!strcasecmp(v->name, "amaflags")) {
            format = ast_cdr_amaflags2int(v->value);
            if (format < 0) {
               ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
            } else {
               peer->amaflags = format;
            }
         } else if (!strcasecmp(v->name, "accountcode")) {
            ast_string_field_set(peer, accountcode, v->value);
         } else if (!strcasecmp(v->name, "mohinterpret")) {
            ast_string_field_set(peer, mohinterpret, v->value);
         } else if (!strcasecmp(v->name, "mohsuggest")) {
            ast_string_field_set(peer, mohsuggest, v->value);
         } else if (!strcasecmp(v->name, "parkinglot")) {
            ast_string_field_set(peer, parkinglot, v->value);
         } else if (!strcasecmp(v->name, "mailbox")) {
            add_peer_mailboxes(peer, v->value);
         } else if (!strcasecmp(v->name, "hasvoicemail")) {
            /* People expect that if 'hasvoicemail' is set, that the mailbox will
             * be also set, even if not explicitly specified. */
            if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
               add_peer_mailboxes(peer, name);
            }
         } else if (!strcasecmp(v->name, "subscribemwi")) {
            ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
         } else if (!strcasecmp(v->name, "vmexten")) {
            ast_string_field_set(peer, vmexten, v->value);
         } else if (!strcasecmp(v->name, "callgroup")) {
            peer->callgroup = ast_get_group(v->value);
         } else if (!strcasecmp(v->name, "allowtransfer")) {
            peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
         } else if (!strcasecmp(v->name, "pickupgroup")) {
            peer->pickupgroup = ast_get_group(v->value);
         } else if (!strcasecmp(v->name, "allow")) {
            int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
            if (error) {
               ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
            }
         } else if (!strcasecmp(v->name, "disallow")) {
            int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
            if (error) {
               ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
            }
         } else if (!strcasecmp(v->name, "registertrying")) {
            ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
         } else if (!strcasecmp(v->name, "autoframing")) {
            peer->autoframing = ast_true(v->value);
         } else if (!strcasecmp(v->name, "rtptimeout")) {
            if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
               ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
               peer->rtptimeout = global_rtptimeout;
            }
         } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
            if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
               ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
               peer->rtpholdtimeout = global_rtpholdtimeout;
            }
         } else if (!strcasecmp(v->name, "rtpkeepalive")) {
            if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
               ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
               peer->rtpkeepalive = global_rtpkeepalive;
            }
         } else if (!strcasecmp(v->name, "timert1")) {
            if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
               ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
               peer->timer_t1 = global_t1;
            }
            /* Note that Timer B is dependent upon T1 and MUST NOT be lower
             * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
            if (peer->timer_b < peer->timer_t1 * 64) {
               peer->timer_b = peer->timer_t1 * 64;
            }
         } else if (!strcasecmp(v->name, "timerb")) {
            if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
               ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
               peer->timer_b = global_timer_b;
            }
            if (peer->timer_b < peer->timer_t1 * 64) {
               static int warning = 0;
               if (warning++ % 20 == 0) {
                  ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
               }
            }
         } else if (!strcasecmp(v->name, "setvar")) {
            peer->chanvars = add_var(v->value, peer->chanvars);
         } else if (!strcasecmp(v->name, "qualifyfreq")) {
            int i;
            if (sscanf(v->value, "%30d", &i) == 1) {
               peer->qualifyfreq = i * 1000;
            } else {
               ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
               peer->qualifyfreq = global_qualifyfreq;
            }
         } else if (!strcasecmp(v->name, "maxcallbitrate")) {
            peer->maxcallbitrate = atoi(v->value);
            if (peer->maxcallbitrate < 0) {
               peer->maxcallbitrate = default_maxcallbitrate;
            }
         } else if (!strcasecmp(v->name, "session-timers")) {
            int i = (int) str2stmode(v->value);
            if (i < 0) {
               ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
               peer->stimer.st_mode_oper = global_st_mode;
            } else {
               peer->stimer.st_mode_oper = i;
            }
         } else if (!strcasecmp(v->name, "session-expires")) {
            if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
               ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
               peer->stimer.st_max_se = global_max_se;
            }
         } else if (!strcasecmp(v->name, "session-minse")) {
            if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
               ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
               peer->stimer.st_min_se = global_min_se;
            }
            if (peer->stimer.st_min_se < 90) {
               ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
               peer->stimer.st_min_se = global_min_se;
            }
         } else if (!strcasecmp(v->name, "session-refresher")) {
            int i = (int) str2strefresher(v->value);
            if (i < 0) {
               ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
               peer->stimer.st_ref = global_st_refresher;
            } else {
               peer->stimer.st_ref = i;
            }
         }
      }

      /* These apply to devstate lookups */
      if (realtime && !strcasecmp(v->name, "lastms")) {
         sscanf(v->value, "%30d", &peer->lastms);
      } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
         inet_aton(v->value, &(peer->addr.sin_addr));
      } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
         if (alt_fullcontact && !alt) {
            /* Reset, because the alternate also has a fullcontact and we
             * do NOT want the field value to be doubled. It might be
             * tempting to skip this, but the first table might not have
             * fullcontact and since we're here, we know that the alternate
             * absolutely does. */
            alt_fullcontact = 0;
            ast_str_reset(fullcontact);
         }
         /* Reconstruct field, because realtime separates our value at the ';' */
         if (fullcontact->used > 0) {
            ast_str_append(&fullcontact, 0, ";%s", v->value);
         } else {
            ast_str_set(&fullcontact, 0, "%s", v->value);
         }
      } else if (!strcasecmp(v->name, "qualify")) {
         if (!strcasecmp(v->value, "no")) {
            peer->maxms = 0;
         } else if (!strcasecmp(v->value, "yes")) {
            peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
         } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
            ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
            peer->maxms = 0;
         }
         if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
            /* This would otherwise cause a network storm, where the
             * qualify response refreshes the peer from the database,
             * which in turn causes another qualify to be sent, ad
             * infinitum. */
            ast_log(LOG_WARNING, "Qualify is incompatible with dynamic uncached realtime.  Please either turn rtcachefriends on or turn qualify off on peer '%s'\n", peer->name);
            peer->maxms = 0;
         }
      } else if (!strcasecmp(v->name, "callcounter")) {
         peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
      } else if (!strcasecmp(v->name, "call-limit")) {
         peer->call_limit = atoi(v->value);
         if (peer->call_limit < 0) {
            peer->call_limit = 0;
         }
      } else if (!strcasecmp(v->name, "busylevel")) {
         peer->busy_level = atoi(v->value);
         if (peer->busy_level < 0) {
            peer->busy_level = 0;
         }
      }
   }

   if (!devstate_only) {
      struct sip_mailbox *mailbox;
      AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
         if (mailbox->delme) {
            AST_LIST_REMOVE_CURRENT(entry);
            destroy_mailbox(mailbox);
         }
      }
      AST_LIST_TRAVERSE_SAFE_END;
   }

   if (!peer->default_outbound_transport) {
      /* Set default set of transports */
      peer->transports = default_transports;
      /* Set default primary transport */
      peer->default_outbound_transport = default_primary_transport;
   }

   /* The default transport type set during build_peer should only replace the socket.type when...
    * 1. Registration is not present and the socket.type and default transport types are different.
    * 2. The socket.type is not an acceptable transport type after rebuilding peer.
    * 3. The socket.type is not set yet. */
   if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
      !(peer->socket.type & peer->transports) || !(peer->socket.type)) {

      set_socket_transport(&peer->socket, peer->default_outbound_transport);
   }

   if (port && !realtime && peer->host_dynamic) {
      peer->defaddr.sin_port = htons(port);
   } else if (port) {
      peer->addr.sin_port = htons(port);
   }

   if (ast_str_strlen(fullcontact)) {
      ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
      peer->rt_fromcontact = TRUE;
      /* We have a hostname in the fullcontact, but if we don't have an
       * address listed on the entry (or if it's 'dynamic'), then we need to
       * parse the entry to obtain the IP address, so a dynamic host can be
       * contacted immediately after reload (as opposed to waiting for it to
       * register once again). But if we have an address for this peer and NAT was
       * specified, use that address instead. */
      /* XXX May need to revisit the final argument; does the realtime DB store whether
       * the original contact was over TLS or not? XXX */
      if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
         __set_address_from_contact(fullcontact->str, &peer->addr, 0);
      }
   }

   if (srvlookup && peer->dnsmgr == NULL) {
      char transport[MAXHOSTNAMELEN];
      char _srvlookup[MAXHOSTNAMELEN];
      char *params;

      ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
      if ((params = strchr(_srvlookup, ';'))) {
         *params++ = '\0';
      }

      snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));

      if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
         ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
         unref_peer(peer, "getting rid of a peer pointer");
         return NULL;
      }

      ast_string_field_set(peer, tohost, srvlookup);
      if (global_dynamic_exclude_static) {
         int err = 0;
         global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
         if (err) {
            ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
         }
      }
   }

   if (!peer->addr.sin_port) {
      peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
   }
   if (!peer->defaddr.sin_port) {
      peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
   }
   if (!peer->socket.port) {
      peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
   }

   if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
      time_t nowtime = time(NULL);

      if ((nowtime - regseconds) > 0) {
         destroy_association(peer);
         memset(&peer->addr, 0, sizeof(peer->addr));
         peer->lastms = -1;
         ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
      }
   }

   /* Startup regular pokes */
   if (!devstate_only && realtime && peer->lastms > 0) {
      ref_peer(peer, "schedule qualify");
      sip_poke_peer(peer, 0);
   }

   ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
   ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
   if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
      sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
   }
   if (peer->host_dynamic && !peer->is_realtime) {
      reg_source_db(peer);
   }

   /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
    * subscribe to it now. */
   if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
      !AST_LIST_EMPTY(&peer->mailboxes)) {
      add_peer_mwi_subs(peer);
      /* Send MWI from the event cache only.  This is so we can send initial
       * MWI if app_voicemail got loaded before chan_sip.  If it is the other
       * way, then we will get events when app_voicemail gets loaded. */
      sip_send_mwi_to_peer(peer, NULL, 1);
   }

   peer->the_mark = 0;

   ast_free_ha(oldha);
   if (!ast_strlen_zero(callback)) { /* build string from peer info */
      char *reg_string;
      if (asprintf(&reg_string, "%s?%s:%s@%s/%s", peer->name, peer->username, !ast_strlen_zero(peer->remotesecret) ? peer->remotesecret : peer->secret, peer->tohost, callback) < 0) {
         ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
      } else if (reg_string) {
         sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
         ast_free(reg_string);
      }
   }
   return peer;
}
static int build_reply_digest ( struct sip_pvt p,
int  method,
char *  digest,
int  digest_len 
) [static]

Build reply digest.

Returns:
Returns -1 if we have no auth
Note:
Build digest challenge for authentication of registrations and calls Also used for authentication of BYE

Definition at line 17690 of file chan_sip.c.

References append_history, ast_copy_string(), ast_debug, ast_inet_ntoa(), ast_md5_hash(), ast_random(), ast_strlen_zero(), sip_pvt::authname, sip_pvt::callid, sip_pvt::domain, find_realm_authentication(), sip_auth::md5secret, sip_registry::md5secret, sip_pvt::nonce, sip_pvt::noncecount, sip_pvt::opaque, sip_registry::opaque, sip_pvt::peerauth, sip_pvt::peermd5secret, sip_pvt::peername, sip_pvt::peersecret, sip_pvt::qop, sip_pvt::realm, sip_pvt::sa, sip_auth::secret, secret, sip_methods, text, sip_pvt::uri, sip_auth::username, sip_pvt::username, and sip_registry::username.

Referenced by reply_digest(), transmit_register(), and transmit_request_with_auth().

{
   char a1[256];
   char a2[256];
   char a1_hash[256];
   char a2_hash[256];
   char resp[256];
   char resp_hash[256];
   char uri[256];
   char opaque[256] = "";
   char cnonce[80];
   const char *username;
   const char *secret;
   const char *md5secret;
   struct sip_auth *auth = NULL; /* Realm authentication */

   if (!ast_strlen_zero(p->domain))
      ast_copy_string(uri, p->domain, sizeof(uri));
   else if (!ast_strlen_zero(p->uri))
      ast_copy_string(uri, p->uri, sizeof(uri));
   else
      snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));

   snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());

   /* Check if we have separate auth credentials */
   if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
      auth = find_realm_authentication(authl, p->realm); /* If not, global list */

   if (auth) {
      ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
      username = auth->username;
      secret = auth->secret;
      md5secret = auth->md5secret;
      if (sipdebug)
         ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
   } else {
      /* No authentication, use peer or register= config */
      username = p->authname;
      secret =  p->peersecret;
      md5secret = p->peermd5secret;
   }
   if (ast_strlen_zero(username))   /* We have no authentication */
      return -1;

   /* Calculate SIP digest response */
   snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
   snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
   if (!ast_strlen_zero(md5secret))
      ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
   else
      ast_md5_hash(a1_hash, a1);
   ast_md5_hash(a2_hash, a2);

   p->noncecount++;
   if (!ast_strlen_zero(p->qop))
      snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
   else
      snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
   ast_md5_hash(resp_hash, resp);

   /* only include the opaque string if it's set */
   if (!ast_strlen_zero(p->opaque)) {
     snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
   }

   /* XXX We hard code our qop to "auth" for now.  XXX */
   if (!ast_strlen_zero(p->qop))
      snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, p->noncecount);
   else
      snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s", username, p->realm, uri, p->nonce, resp_hash, opaque);

   append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);

   return 0;
}
static void build_route ( struct sip_pvt p,
struct sip_request req,
int  backwards 
) [static]

Build route list from Record-Route header.

Definition at line 12979 of file chan_sip.c.

References __get_header(), ast_copy_string(), ast_debug, ast_malloc, ast_strlen_zero(), free_old_route(), get_header(), sip_route::hop, sip_request::len, list_route(), sip_route::next, sip_pvt::route, sip_pvt::route_persistant, and sip_debug_test_pvt().

Referenced by handle_request_invite(), handle_request_subscribe(), and handle_response_invite().

{
   struct sip_route *thishop, *head, *tail;
   int start = 0;
   int len;
   const char *rr, *contact, *c;

   /* Once a persistant route is set, don't fool with it */
   if (p->route && p->route_persistant) {
      ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
      return;
   }

   if (p->route) {
      free_old_route(p->route);
      p->route = NULL;
   }

   /* We only want to create the route set the first time this is called */
   p->route_persistant = 1;
   
   /* Build a tailq, then assign it to p->route when done.
    * If backwards, we add entries from the head so they end up
    * in reverse order. However, we do need to maintain a correct
    * tail pointer because the contact is always at the end.
    */
   head = NULL;
   tail = head;
   /* 1st we pass through all the hops in any Record-Route headers */
   for (;;) {
      /* Each Record-Route header */
      rr = __get_header(req, "Record-Route", &start);
      if (*rr == '\0')
         break;
      for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
         ++rr;
         len = strcspn(rr, ">") + 1;
         /* Make a struct route */
         if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
            /* ast_calloc is not needed because all fields are initialized in this block */
            ast_copy_string(thishop->hop, rr, len);
            ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
            /* Link in */
            if (backwards) {
               /* Link in at head so they end up in reverse order */
               thishop->next = head;
               head = thishop;
               /* If this was the first then it'll be the tail */
               if (!tail)
                  tail = thishop;
            } else {
               thishop->next = NULL;
               /* Link in at the end */
               if (tail)
                  tail->next = thishop;
               else
                  head = thishop;
               tail = thishop;
            }
         }
      }
   }

   /* Only append the contact if we are dealing with a strict router */
   if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
      /* 2nd append the Contact: if there is one */
      /* Can be multiple Contact headers, comma separated values - we just take the first */
      contact = get_header(req, "Contact");
      if (!ast_strlen_zero(contact)) {
         ast_debug(2, "build_route: Contact hop: %s\n", contact);
         /* Look for <: delimited address */
         c = strchr(contact, '<');
         if (c) {
            /* Take to > */
            ++c;
            len = strcspn(c, ">") + 1;
         } else {
            /* No <> - just take the lot */
            c = contact;
            len = strlen(contact) + 1;
         }
         if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
            /* ast_calloc is not needed because all fields are initialized in this block */
            ast_copy_string(thishop->hop, c, len);
            thishop->next = NULL;
            /* Goes at the end */
            if (tail)
               tail->next = thishop;
            else
               head = thishop;
         }
      }
   }

   /* Store as new route */
   p->route = head;

   /* For debugging dump what we ended up with */
   if (sip_debug_test_pvt(p))
      list_route(p->route);
}
static void build_rpid ( struct sip_pvt p) [static]

Build the Remote Party-ID & From using callingpres options.

Definition at line 11079 of file chan_sip.c.

References ast_inet_ntoa(), ast_log(), AST_PRES_ALLOWED, AST_PRES_ALLOWED_NETWORK_NUMBER, AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN, AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED, AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, AST_PRES_NUMBER_NOT_AVAILABLE, AST_PRES_PROHIB_NETWORK_NUMBER, AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN, AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED, AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN, AST_PRES_RESTRICTION, ast_string_field_build, ast_string_field_set, ast_strlen_zero(), buf, sip_pvt::callingpres, ast_channel::cid, ast_callerid::cid_name, ast_callerid::cid_num, default_callerid, FALSE, sip_pvt::fromdomain, sip_pvt::fromuser, LOG_WARNING, sip_pvt::ourip, sip_pvt::owner, sip_pvt::rpid, sip_pvt::rpid_from, S_OR, sip_pvt::tag, and TRUE.

Referenced by initreqprep().

{
   int send_pres_tags = TRUE;
   const char *privacy=NULL;
   const char *screen=NULL;
   char buf[256];
   const char *clid = default_callerid;
   const char *clin = NULL;
   const char *fromdomain;

   if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))  
      return;

   if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
      clid = p->owner->cid.cid_num;
   if (p->owner && p->owner->cid.cid_name)
      clin = p->owner->cid.cid_name;
   if (ast_strlen_zero(clin))
      clin = clid;

   switch (p->callingpres) {
   case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
      privacy = "off";
      screen = "no";
      break;
   case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
      privacy = "off";
      screen = "yes";
      break;
   case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
      privacy = "off";
      screen = "no";
      break;
   case AST_PRES_ALLOWED_NETWORK_NUMBER:
      privacy = "off";
      screen = "yes";
      break;
   case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
      privacy = "full";
      screen = "no";
      break;
   case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
      privacy = "full";
      screen = "yes";
      break;
   case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
      privacy = "full";
      screen = "no";
      break;
   case AST_PRES_PROHIB_NETWORK_NUMBER:
      privacy = "full";
      screen = "yes";
      break;
   case AST_PRES_NUMBER_NOT_AVAILABLE:
      send_pres_tags = FALSE;
      break;
   default:
      ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
      if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
         privacy = "full";
      else
         privacy = "off";
      screen = "no";
      break;
   }
   
   fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));

   snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
   if (send_pres_tags)
      snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
   ast_string_field_set(p, rpid, buf);

   ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
                S_OR(p->fromuser, clid),
                fromdomain, p->tag);
}
static void build_via ( struct sip_pvt p) [static]

Build a Via header for a request.

Definition at line 3775 of file chan_sip.c.

References ast_inet_ntoa(), ast_test_flag, sip_pvt::branch, sip_pvt::flags, get_transport_pvt(), sip_pvt::ourip, SIP_NAT, SIP_NAT_RFC3581, and sip_pvt::via.

Referenced by __sip_subscribe_mwi_do(), manager_sipnotify(), reqprep(), sip_alloc(), sip_cli_notify(), sip_poke_peer(), sip_request_call(), sip_send_mwi_to_peer(), transmit_invite(), transmit_register(), and transmit_response_using_temp().

{
   /* Work around buggy UNIDEN UIP200 firmware */
   const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";

   /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
   snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
       get_transport_pvt(p),
       ast_inet_ntoa(p->ourip.sin_addr),
       ntohs(p->ourip.sin_port), (int) p->branch, rport);
}
static int cb_extensionstate ( char *  context,
char *  exten,
int  state,
void *  data 
) [static]

Callback for the devicestate notification (SUBSCRIBE) support subsystem.

Note:
If you add an "hint" priority to the extension in the dial plan, you will get notifications on device state changes

Definition at line 13311 of file chan_sip.c.

References append_history, AST_EXTENSION_DEACTIVATED, AST_EXTENSION_REMOVED, ast_extension_state2str(), ast_log(), ast_set_flag, ast_test_flag, ast_verb, sip_pvt::autokillid, sip_request::data, DEFAULT_TRANS_TIMEOUT, FALSE, sip_pvt::flags, sip_pvt::laststate, LOG_WARNING, NONE, sip_pvt::pendinginvite, sip_cancel_destroy(), SIP_PAGE2_STATECHANGEQUEUE, sip_pvt_lock, sip_pvt_unlock, sip_scheddestroy(), sip_pvt::stateid, sip_pvt::subscribed, transmit_state_notify(), and sip_pvt::username.

Referenced by handle_request_subscribe(), handle_response(), and handle_response_notify().

{
   struct sip_pvt *p = data;

   sip_pvt_lock(p);

   switch(state) {
   case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
   case AST_EXTENSION_REMOVED:   /* Extension is gone */
      if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
         ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
      ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
      p->stateid = -1;
      p->subscribed = NONE;
      append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
      break;
   default: /* Tell user */
      p->laststate = state;
      break;
   }
   if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
      if (!p->pendinginvite) {
         transmit_state_notify(p, state, 1, FALSE);
      } else {
         /* We already have a NOTIFY sent that is not answered. Queue the state up.
            if many state changes happen meanwhile, we will only send a notification of the last one */
         ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
      }
   }
   ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
         ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");

   sip_pvt_unlock(p);

   return 0;
}
static void change_hold_state ( struct sip_pvt dialog,
struct sip_request req,
int  holdstate,
int  sendonly 
) [static]

Change hold state for a call.

Definition at line 8399 of file chan_sip.c.

References append_history, ast_clear_flag, ast_set_flag, ast_test_flag, sip_settings::callevents, sip_request::data, EVENT_FLAG_CALL, sip_pvt::flags, manager_event, ast_channel::name, sip_settings::notifyhold, sip_pvt::owner, sip_cfg, SIP_PAGE2_CALL_ONHOLD, SIP_PAGE2_CALL_ONHOLD_ACTIVE, SIP_PAGE2_CALL_ONHOLD_INACTIVE, SIP_PAGE2_CALL_ONHOLD_ONEDIR, sip_peer_hold(), and ast_channel::uniqueid.

Referenced by handle_request_invite(), and process_sdp().

{
   if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
      sip_peer_hold(dialog, holdstate);
   if (sip_cfg.callevents)
      manager_event(EVENT_FLAG_CALL, "Hold",
               "Status: %s\r\n"
               "Channel: %s\r\n"
               "Uniqueid: %s\r\n",
               holdstate ? "On" : "Off",
               dialog->owner->name,
               dialog->owner->uniqueid);
   append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
   if (!holdstate) { /* Put off remote hold */
      ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);   /* Clear both flags */
      return;
   }
   /* No address for RTP, we're on hold */

   if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
      ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
   else if (sendonly == 2) /* Inactive stream */
      ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
   else
      ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
   return;
}
static void change_t38_state ( struct sip_pvt p,
int  state 
) [static]

Change the T38 state on a SIP dialog.

Definition at line 5232 of file chan_sip.c.

References AST_CONTROL_T38_PARAMETERS, ast_debug, ast_queue_control_data(), AST_T38_NEGOTIATED, AST_T38_REFUSED, AST_T38_REQUEST_NEGOTIATE, AST_T38_TERMINATED, ast_udptl_get_far_max_ifp(), ast_udptl_set_tag(), chan, ast_control_t38_parameters::max_ifp, ast_channel::name, sip_pvt::owner, ast_control_t38_parameters::request_response, t38properties::state, sip_pvt::t38, T38_DISABLED, T38_ENABLED, T38_LOCAL_REINVITE, T38_PEER_REINVITE, t38properties::their_parms, sip_pvt::udptl, and sip_pvt::username.

Referenced by handle_response_invite(), interpret_t38_parameters(), process_sdp(), and sip_t38_abort().

{
   int old = p->t38.state;
   struct ast_channel *chan = p->owner;
   struct ast_control_t38_parameters parameters = { .request_response = 0 };

   /* Don't bother changing if we are already in the state wanted */
   if (old == state)
      return;

   p->t38.state = state;
   ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");

   /* If no channel was provided we can't send off a control frame */
   if (!chan)
      return;

   /* Given the state requested and old state determine what control frame we want to queue up */
   switch (state) {
   case T38_PEER_REINVITE:
      parameters = p->t38.their_parms;
      parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
      parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
      ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
      break;
   case T38_ENABLED:
      parameters = p->t38.their_parms;
      parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
      parameters.request_response = AST_T38_NEGOTIATED;
      ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
      break;
   case T38_DISABLED:
      if (old == T38_ENABLED) {
         parameters.request_response = AST_T38_TERMINATED;
      } else if (old == T38_LOCAL_REINVITE) {
         parameters.request_response = AST_T38_REFUSED;
      }
      break;
   case T38_LOCAL_REINVITE:
      /* wait until we get a peer response before responding to local reinvite */
      break;
   }

   /* Woot we got a message, create a control frame and send it on! */
   if (parameters.request_response)
      ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
}
static enum check_auth_result check_auth ( struct sip_pvt p,
struct sip_request req,
const char *  username,
const char *  secret,
const char *  md5secret,
int  sipmethod,
char *  uri,
enum xmittype  reliable,
int  ignore 
) [static]

Check user authorization from peer definition Some actions, like REGISTER and INVITEs from peers require authentication (if peer have secret set)

Returns:
0 on success, non-zero on error

XXX

Todo:
need a better return code here

XXX

Todo:
need a better return code here

Definition at line 13103 of file chan_sip.c.

References append_history, ast_copy_string(), AST_DYNSTR_BUILD_FAILED, ast_log(), ast_md5_hash(), ast_skip_blanks(), ast_str_set(), ast_str_thread_get(), ast_strlen_zero(), AUTH_CHALLENGE_SENT, auth_headers(), AUTH_SECRET_FAILED, AUTH_SUCCESSFUL, AUTH_USERNAME_MISMATCH, buf, CHECK_AUTH_BUF_INITLEN, DEFAULT_TRANS_TIMEOUT, FALSE, get_header(), sip_request::ignore, LOG_NOTICE, LOG_WARNING, sip_pvt::randdata, sip_settings::realm, s, S_OR, set_nonce_randdata(), sip_cfg, sip_methods, sip_scheddestroy(), sip_pvt::stalenonce, strsep(), text, transmit_response_with_auth(), TRUE, and WWW_AUTH.

Referenced by check_peer_ok(), and register_verify().

{
   const char *response;
   char *reqheader, *respheader;
   const char *authtoken;
   char a1_hash[256];
   char resp_hash[256]="";
   char *c;
   int  wrongnonce = FALSE;
   int  good_response;
   const char *usednonce = p->randdata;
   struct ast_str *buf;
   int res;

   /* table of recognised keywords, and their value in the digest */
   enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
   struct x {
      const char *key;
      const char *s;
   } *i, keys[] = {
      [K_RESP] = { "response=", "" },
      [K_URI] = { "uri=", "" },
      [K_USER] = { "username=", "" },
      [K_NONCE] = { "nonce=", "" },
      [K_LAST] = { NULL, NULL}
   };

   /* Always OK if no secret */
   if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
      return AUTH_SUCCESSFUL;

   /* Always auth with WWW-auth since we're NOT a proxy */
   /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
   response = "401 Unauthorized";

   /*
    * Note the apparent swap of arguments below, compared to other
    * usages of auth_headers().
    */
   auth_headers(WWW_AUTH, &respheader, &reqheader);

   authtoken =  get_header(req, reqheader);  
   if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
      /* This is a retransmitted invite/register/etc, don't reconstruct authentication
         information */
      if (!reliable) {
         /* Resend message if this was NOT a reliable delivery.   Otherwise the
            retransmission should get it */
         transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
         /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      }
      return AUTH_CHALLENGE_SENT;
   } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
      /* We have no auth, so issue challenge and request authentication */
      set_nonce_randdata(p, 1); /* Create nonce for challenge */
      transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
      /* Schedule auto destroy in 32 seconds */
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      return AUTH_CHALLENGE_SENT;
   } 

   /* --- We have auth, so check it */

   /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
      an example in the spec of just what it is you're doing a hash on. */

   if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
      return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */

   /* Make a copy of the response and parse it */
   res = ast_str_set(&buf, 0, "%s", authtoken);

   if (res == AST_DYNSTR_BUILD_FAILED)
      return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */

   c = buf->str;

   while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
      for (i = keys; i->key != NULL; i++) {
         const char *separator = ",";  /* default */

         if (strncasecmp(c, i->key, strlen(i->key)) != 0)
            continue;
         /* Found. Skip keyword, take text in quotes or up to the separator. */
         c += strlen(i->key);
         if (*c == '"') { /* in quotes. Skip first and look for last */
            c++;
            separator = "\"";
         }
         i->s = c;
         strsep(&c, separator);
         break;
      }
      if (i->key == NULL) /* not found, jump after space or comma */
         strsep(&c, " ,");
   }

   /* Verify that digest username matches  the username we auth as */
   if (strcmp(username, keys[K_USER].s)) {
      ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
         username, keys[K_USER].s);
      /* Oops, we're trying something here */
      return AUTH_USERNAME_MISMATCH;
   }

   /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
    * If this check fails, send 401 with new nonce */
   if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
      wrongnonce = TRUE;
      usednonce = keys[K_NONCE].s;
   } else {
      p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
   }

   if (!ast_strlen_zero(md5secret))
      ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
   else {
      char a1[256];
      snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
      ast_md5_hash(a1_hash, a1);
   }

   /* compute the expected response to compare with what we received */
   {
      char a2[256];
      char a2_hash[256];
      char resp[256];

      snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
            S_OR(keys[K_URI].s, uri));
      ast_md5_hash(a2_hash, a2);
      snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
      ast_md5_hash(resp_hash, resp);
   }

   good_response = keys[K_RESP].s &&
         !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
   if (wrongnonce) {
      if (good_response) {
         if (sipdebug)
            ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
         /* We got working auth token, based on stale nonce . */
         set_nonce_randdata(p, 0);
         transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
      } else {
         /* Everything was wrong, so give the device one more try with a new challenge */
         if (!req->ignore) {
            if (sipdebug)
               ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
            set_nonce_randdata(p, 1);
         } else {
            if (sipdebug)
               ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
         }
         transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
      }

      /* Schedule auto destroy in 32 seconds */
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      return AUTH_CHALLENGE_SENT;
   } 
   if (good_response) {
      append_history(p, "AuthOK", "Auth challenge successful for %s", username);
      return AUTH_SUCCESSFUL;
   }

   /* Ok, we have a bad username/secret pair */
   /* Tell the UAS not to re-send this authentication data, because
      it will continue to fail
   */

   return AUTH_SECRET_FAILED;
}
static enum check_auth_result check_peer_ok ( struct sip_pvt p,
char *  of,
struct sip_request req,
int  sipmethod,
struct sockaddr_in *  sin,
struct sip_peer **  authpeer,
enum xmittype  reliable,
char *  rpid_num,
char *  calleridname,
char *  uri2 
) [static]

Validate device authentication.

Definition at line 14506 of file chan_sip.c.

References sip_peer::accountcode, accountcode, sip_peer::amaflags, sip_pvt::amaflags, ao2_t_ref, ast_apply_ha(), ast_copy_flags, ast_debug, AST_FORMAT_TEXT_MASK, AST_FORMAT_VIDEO_MASK, ast_inet_ntoa(), ast_is_shrinkable_phonenumber(), ast_rtp_codec_setpref(), ast_rtp_destroy(), AST_RTP_DTMF, ast_set_flag, ast_shrink_phone_number(), ast_strdupa, ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_verbose(), AUTH_ACL_FAILED, AUTH_DONT_KNOW, sip_peer::autoframing, sip_pvt::autoframing, sip_peer::call_limit, sip_peer::callgroup, sip_pvt::callgroup, sip_pvt::callingpres, sip_peer::callingpres, sip_peer::capability, sip_pvt::capability, sip_peer::chanvars, sip_pvt::chanvars, check_auth(), cid_name, sip_peer::cid_name, cid_num, sip_peer::cid_num, context, sip_peer::context, copy_vars(), sip_request::debug, do_setnat(), FALSE, find_peer(), FINDALLDEVICES, FINDPEERS, FINDUSERS, sip_peer::flags, sip_pvt::flags, sip_peer::fullcontact, sip_peer::ha, sip_request::ignore, sip_pvt::jointcapability, sip_pvt::jointnoncodeccapability, sip_peer::language, language, sip_peer::lastms, sip_peer::maxcallbitrate, sip_pvt::maxcallbitrate, sip_peer::maxms, sip_peer::md5secret, sip_peer::mohinterpret, mohinterpret, sip_peer::mohsuggest, mohsuggest, sip_peer::name, sip_pvt::noncodeccapability, sip_peer::parkinglot, parkinglot, sip_pvt::peercapability, sip_pvt::peermd5secret, sip_pvt::peersecret, sip_peer::pickupgroup, sip_pvt::pickupgroup, sip_pvt::prefs, sip_peer::prefs, sip_pvt::recv, replace_cid(), sip_pvt::rtp, sip_peer::secret, set_t38_capabilities(), SIP_CALL_LIMIT, sip_debug_test_addr(), SIP_DTMF, SIP_DTMF_AUTO, SIP_DTMF_RFC2833, SIP_FLAGS_TO_COPY, SIP_INSECURE_INVITE, SIP_INVITE, SIP_NAT_ROUTE, SIP_PAGE2_FLAGS_TO_COPY, SIP_PAGE2_T38SUPPORT, SIP_PAGE2_TEXTSUPPORT, SIP_PAGE2_VIDEOSUPPORT, SIP_PAGE2_VIDEOSUPPORT_ALWAYS, SIP_SUBSCRIBE, sip_peer::sipoptions, sip_pvt::sipoptions, sip_pvt::socket, sip_peer::subscribecontext, sip_peer::t38_maxdatagram, sip_pvt::t38_maxdatagram, sip_pvt::timer_b, sip_peer::timer_b, sip_peer::timer_t1, sip_pvt::timer_t1, sip_pvt::trtp, TRUE, sip_socket::type, sip_pvt::udptl, unref_peer(), sip_peer::username, and sip_pvt::vrtp.

Referenced by check_user_full().

{
   enum check_auth_result res;
   int debug=sip_debug_test_addr(sin);
   struct sip_peer *peer;

   if (sipmethod == SIP_SUBSCRIBE) {
      /* For subscribes, match on device name only; for other methods,
      * match on IP address-port of the incoming request.
      */
      peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
   } else {
      /* First find devices based on username (avoid all type=peer's) */
      peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);

      /* Then find devices based on IP */
      if (!peer) {
         peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
      }
   }

   if (!peer) {
      if (debug)
         ast_verbose("No matching peer for '%s' from '%s:%d'\n",
            of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
      return AUTH_DONT_KNOW;
   }
   if (!ast_apply_ha(peer->ha, sin)) {
      ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
      unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
      return AUTH_ACL_FAILED;
   }
   if (debug)
      ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
         peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));

   /* XXX what about p->prefs = peer->prefs; ? */
   /* Set Frame packetization */
   if (p->rtp) {
      ast_rtp_codec_setpref(p->rtp, &peer->prefs);
      p->autoframing = peer->autoframing;
   }

   /* Take the peer */
   ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
   ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);

   if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
      p->t38_maxdatagram = peer->t38_maxdatagram;
      set_t38_capabilities(p);
   }

   /* Copy SIP extensions profile to peer */
   /* XXX is this correct before a successful auth ? */
   if (p->sipoptions)
      peer->sipoptions = p->sipoptions;

   replace_cid(p, rpid_num, calleridname);
   do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));

   ast_string_field_set(p, peersecret, peer->secret);
   ast_string_field_set(p, peermd5secret, peer->md5secret);
   ast_string_field_set(p, subscribecontext, peer->subscribecontext);
   ast_string_field_set(p, mohinterpret, peer->mohinterpret);
   ast_string_field_set(p, mohsuggest, peer->mohsuggest);
   ast_string_field_set(p, parkinglot, peer->parkinglot);
   if (peer->callingpres)  /* Peer calling pres setting will override RPID */
      p->callingpres = peer->callingpres;
   if (peer->maxms && peer->lastms)
      p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
   else
      p->timer_t1 = peer->timer_t1;
 
   /* Set timer B to control transaction timeouts */
   if (peer->timer_b)
      p->timer_b = peer->timer_b;
   else
      p->timer_b = 64 * p->timer_t1;
 
   if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
      /* Pretend there is no required authentication */
      ast_string_field_set(p, peersecret, NULL);
      ast_string_field_set(p, peermd5secret, NULL);
   }
   if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
      ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
      ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
      /* If we have a call limit, set flag */
      if (peer->call_limit)
         ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
      ast_string_field_set(p, peername, peer->name);
      ast_string_field_set(p, authname, peer->name);

      if (sipmethod == SIP_INVITE) {
         /* copy channel vars */
         p->chanvars = copy_vars(peer->chanvars);
      }

      if (authpeer) {
         ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
         (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
      }

      if (!ast_strlen_zero(peer->username)) {
         ast_string_field_set(p, username, peer->username);
         /* Use the default username for authentication on outbound calls */
         /* XXX this takes the name from the caller... can we override ? */
         ast_string_field_set(p, authname, peer->username);
      }
      if (!ast_strlen_zero(peer->cid_num)) {
         char *tmp = ast_strdupa(peer->cid_num);
         if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
            ast_shrink_phone_number(tmp);
         ast_string_field_set(p, cid_num, tmp);
      }
      if (!ast_strlen_zero(peer->cid_name)) 
         ast_string_field_set(p, cid_name, peer->cid_name);
      ast_string_field_set(p, fullcontact, peer->fullcontact);
      if (!ast_strlen_zero(peer->context))
         ast_string_field_set(p, context, peer->context);
      ast_string_field_set(p, peersecret, peer->secret);
      ast_string_field_set(p, peermd5secret, peer->md5secret);
      ast_string_field_set(p, language, peer->language);
      ast_string_field_set(p, accountcode, peer->accountcode);
      p->amaflags = peer->amaflags;
      p->callgroup = peer->callgroup;
      p->pickupgroup = peer->pickupgroup;
      p->capability = peer->capability;
      p->prefs = peer->prefs;
      p->jointcapability = peer->capability;
      if (p->peercapability)
         p->jointcapability &= p->peercapability;
      p->maxcallbitrate = peer->maxcallbitrate;
      if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
            (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
               !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
            p->vrtp) {
         ast_rtp_destroy(p->vrtp);
         p->vrtp = NULL;
      }
      if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
         ast_rtp_destroy(p->trtp);
         p->trtp = NULL;
      }
      if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
          (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
         p->noncodeccapability |= AST_RTP_DTMF;
      else
         p->noncodeccapability &= ~AST_RTP_DTMF;
      p->jointnoncodeccapability = p->noncodeccapability;
   }
   unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
   return res;
}
static void check_pendings ( struct sip_pvt p) [static]

Check pending actions on SIP call.

Note:
both sip_pvt and sip_pvt's owner channel (if present) must be locked for this function.

Definition at line 18103 of file chan_sip.c.

References ast_clear_flag, ast_debug, AST_SOFTHANGUP_DEV, ast_softhangup_nolock(), ast_test_flag, sip_pvt::callid, DEFAULT_TRANS_TIMEOUT, FALSE, sip_pvt::flags, INV_CALLING, INV_CANCELLED, INV_EARLY_MEDIA, INV_PROCEEDING, sip_pvt::invitestate, sip_pvt::lastinvite, sip_pvt::owner, sip_pvt::pendinginvite, SIP_BYE, SIP_CANCEL, SIP_NEEDREINVITE, SIP_PENDINGBYE, sip_scheddestroy(), t38properties::state, sip_pvt::t38, T38_LOCAL_REINVITE, transmit_reinvite_with_sdp(), transmit_request(), transmit_request_with_auth(), TRUE, sip_pvt::waitid, and XMIT_RELIABLE.

Referenced by handle_incoming(), handle_response_invite(), and sip_reinvite_retry().

{
   if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
      /* if we can't BYE, then this is really a pending CANCEL */
      if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
         p->invitestate = INV_CANCELLED;
         transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
         /* Actually don't destroy us yet, wait for the 487 on our original 
            INVITE, but do set an autodestruct just in case we never get it. */
      } else {
         /* We have a pending outbound invite, don't send something
            new in-transaction */
         if (p->pendinginvite)
            return;

         if (p->owner) {
            ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
         }
         /* Perhaps there is an SD change INVITE outstanding */
         transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
      }
      ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
   } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
      /* if we can't REINVITE, hold it for later */
      if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
         ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
      } else {
         ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
         /* Didn't get to reinvite yet, so do it now */
         transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
         ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
      }
   }
}
static void check_rtp_timeout ( struct sip_pvt dialog,
time_t  t 
) [static]

helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked

Todo:
Check video RTP keepalives

Do we need to move the lastrtptx to the RTP structure to have one for audio and one for video? It really does belong to the RTP structure.

Definition at line 22999 of file chan_sip.c.

References ast_channel::_state, ast_channel_trylock, ast_channel_unlock, ast_log(), ast_rtp_get_peer(), ast_rtp_get_rtpholdtimeout(), ast_rtp_get_rtpkeepalive(), ast_rtp_get_rtptimeout(), ast_rtp_sendcng(), ast_rtp_set_rtpholdtimeout(), ast_rtp_set_rtptimeout(), AST_SOFTHANGUP_DEV, ast_softhangup_nolock(), AST_STATE_UP, ast_test_flag, sip_pvt::flags, sip_pvt::lastrtprx, sip_pvt::lastrtptx, LOG_NOTICE, ast_channel::name, sip_pvt::owner, sip_pvt::redirip, sip_pvt::rtp, SIP_PAGE2_CALL_ONHOLD, sip_pvt_lock, sip_pvt_unlock, t38properties::state, sip_pvt::t38, T38_ENABLED, and sip_pvt::vrtp.

Referenced by dialog_needdestroy().

{
   /* If we have no RTP or no active owner, no need to check timers */
   if (!dialog->rtp || !dialog->owner)
      return;
   /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */

   if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
      return;

   /* If the call is involved in a T38 fax session do not check RTP timeout */
   if (dialog->t38.state == T38_ENABLED)
      return;

   /* If we have no timers set, return now */
   if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
      return;

   /* Check AUDIO RTP keepalives */
   if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
          (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
      /* Need to send an empty RTP packet */
      dialog->lastrtptx = time(NULL);
      ast_rtp_sendcng(dialog->rtp, 0);
   }

   /*! \todo Check video RTP keepalives

      Do we need to move the lastrtptx to the RTP structure to have one for audio and one
      for video? It really does belong to the RTP structure.
   */

   /* Check AUDIO RTP timers */
   if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
          (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {

      /* Might be a timeout now -- see if we're on hold */
      struct sockaddr_in sin;
      ast_rtp_get_peer(dialog->rtp, &sin);
      if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
           (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
         /* Needs a hangup */
         if (ast_rtp_get_rtptimeout(dialog->rtp)) {
            while (dialog->owner && ast_channel_trylock(dialog->owner)) {
               sip_pvt_unlock(dialog);
               usleep(1);
               sip_pvt_lock(dialog);
            }
            if (!dialog->owner) {
               return; /* channel hangup can occur during deadlock avoidance. */
            }
            ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
               dialog->owner->name, (long) (t - dialog->lastrtprx));
            /* Issue a softhangup */
            ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
            ast_channel_unlock(dialog->owner);
            /* forget the timeouts for this call, since a hangup
               has already been requested and we don't want to
               repeatedly request hangups
            */
            ast_rtp_set_rtptimeout(dialog->rtp, 0);
            ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
            if (dialog->vrtp) {
               ast_rtp_set_rtptimeout(dialog->vrtp, 0);
               ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
            }
         }
      }
   }
}
static int check_sip_domain ( const char *  domain,
char *  context,
size_t  len 
) [static]

check_sip_domain: Check if domain part of uri is local to our server

Definition at line 24134 of file chan_sip.c.

References ast_copy_string(), AST_LIST_LOCK, AST_LIST_TRAVERSE, AST_LIST_UNLOCK, ast_strlen_zero(), domain::context, and domain::domain.

Referenced by func_check_sipdomain(), get_destination(), handle_request_refer(), and register_verify().

{
   struct domain *d;
   int result = 0;

   AST_LIST_LOCK(&domain_list);
   AST_LIST_TRAVERSE(&domain_list, d, list) {
      if (strcasecmp(d->domain, domain))
         continue;

      if (len && !ast_strlen_zero(d->context))
         ast_copy_string(context, d->context, len);
      
      result = 1;
      break;
   }
   AST_LIST_UNLOCK(&domain_list);

   return result;
}
static int check_user ( struct sip_pvt p,
struct sip_request req,
int  sipmethod,
char *  uri,
enum xmittype  reliable,
struct sockaddr_in *  sin 
) [static]

Find user If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced.

Definition at line 14787 of file chan_sip.c.

References check_user_full().

Referenced by handle_request_invite().

{
   return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
}
static enum check_auth_result check_user_full ( struct sip_pvt p,
struct sip_request req,
int  sipmethod,
char *  uri,
enum xmittype  reliable,
struct sockaddr_in *  sin,
struct sip_peer **  authpeer 
) [static]

Check if matching user or peer is defined Match user on From: user name and peer on IP/port This is used on first invite (not re-invites) and subscribe requests.

Returns:
0 on success, non-zero on failure

Definition at line 14671 of file chan_sip.c.

References sip_settings::allowguest, sip_settings::alwaysauthreject, ast_copy_string(), ast_is_shrinkable_phonenumber(), ast_log(), ast_set_flag, ast_shrink_phone_number(), ast_strdupa, ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_uri_decode(), AUTH_DONT_KNOW, AUTH_FAKE_AUTH, AUTH_SECRET_FAILED, AUTH_SUCCESSFUL, build_contact(), sip_pvt::callingpres, check_peer_ok(), cid_name, cid_num, dummy(), exten, sip_pvt::exten, sip_pvt::flags, get_calleridname(), get_header(), get_in_brackets(), get_rpid_num(), LOG_NOTICE, sip_pvt::our_contact, parse_uri(), sip_settings::pedanticsipchecking, replace_cid(), sip_cfg, SIP_NAT_ROUTE, SIP_PAGE2_RPORT_PRESENT, strsep(), and terminate_uri().

Referenced by check_user(), and handle_request_subscribe().

{
   char from[256];
   char *dummy;   /* dummy return value for parse_uri */
   char *domain;  /* dummy return value for parse_uri */
   char *of;
   char rpid_num[50];
   const char *rpid;
   enum check_auth_result res;
   char calleridname[50];
   char *uri2 = ast_strdupa(uri);

   terminate_uri(uri2); /* trim extra stuff */

   ast_copy_string(from, get_header(req, "From"), sizeof(from));
   if (sip_cfg.pedanticsipchecking)
      ast_uri_decode(from);
   /* XXX here tries to map the username for invite things */
   memset(calleridname, 0, sizeof(calleridname));
   get_calleridname(from, calleridname, sizeof(calleridname));
   if (calleridname[0])
      ast_string_field_set(p, cid_name, calleridname);

   rpid = get_header(req, "Remote-Party-ID");
   memset(rpid_num, 0, sizeof(rpid_num));
   if (!ast_strlen_zero(rpid)) 
      p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));

   of = get_in_brackets(from);
   if (ast_strlen_zero(p->exten)) {
      char *t = uri2;
      if (!strncasecmp(t, "sip:", 4))
         t+= 4;
      else if (!strncasecmp(t, "sips:", 5))
         t += 5;
      ast_string_field_set(p, exten, t);
      t = strchr(p->exten, '@');
      if (t)
         *t = '\0';
      if (ast_strlen_zero(p->our_contact))
         build_contact(p);
   }
   /* save the URI part of the From header */
   ast_string_field_set(p, from, of);

   /* ignore all fields but name */
   if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
      ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
   }

   if (ast_strlen_zero(of)) {
      /* XXX note: the original code considered a missing @host
       * as a username-only URI. The SIP RFC (19.1.1) says that
       * this is wrong, and it should be considered as a domain-only URI.
       * For backward compatibility, we keep this block, but it is
       * really a mistake and should go away.
       */
      of = domain;
   } else {
      char *tmp = ast_strdupa(of);
      /* We need to be able to handle auth-headers looking like
         <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
      */
      tmp = strsep(&tmp, ";");
      if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
         ast_shrink_phone_number(tmp);
      ast_string_field_set(p, cid_num, tmp);
   }

   if (global_match_auth_username) {
      /*
       * XXX This is experimental code to grab the search key from the
       * Auth header's username instead of the 'From' name, if available.
       * Do not enable this block unless you understand the side effects (if any!)
       * Note, the search for "username" should be done in a more robust way.
       * Note2, at the moment we check both fields, though maybe we should
       * pick one or another depending on the request ? XXX
       */
      const char *hdr = get_header(req, "Authorization");
      if (ast_strlen_zero(hdr))
         hdr = get_header(req, "Proxy-Authorization");

      if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
         ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
         of = from;
         of = strsep(&of, "\"");
      }
   }

   res = check_peer_ok(p, of, req, sipmethod, sin,
         authpeer, reliable, rpid_num, calleridname, uri2);
   if (res != AUTH_DONT_KNOW)
      return res;

   /* Finally, apply the guest policy */
   if (sip_cfg.allowguest) {
      replace_cid(p, rpid_num, calleridname);
      res = AUTH_SUCCESSFUL;
   } else if (sip_cfg.alwaysauthreject)
      res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
   else
      res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */


   if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
      ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
   }

   return res;
}
static void check_via ( struct sip_pvt p,
struct sip_request req 
) [static]

check Via: header for hostname, port and rport request/answer

Definition at line 14353 of file chan_sip.c.

References ast_copy_string(), ast_gethostbyname(), ast_inet_ntoa(), ast_log(), ast_set_flag, ast_skip_blanks(), ast_verbose(), sip_pvt::flags, get_header(), hp, LOG_WARNING, port_str2int(), sip_pvt::sa, sip_debug_test_pvt(), sip_nat_mode(), SIP_PAGE2_RPORT_PRESENT, sip_real_dst(), and STANDARD_SIP_PORT.

Referenced by handle_request_bye(), handle_request_cancel(), handle_request_invite(), handle_request_register(), and handle_request_subscribe().

{
   char via[512];
   char *c, *pt, *maddr;
   struct hostent *hp;
   struct ast_hostent ahp;

   ast_copy_string(via, get_header(req, "Via"), sizeof(via));

   /* Work on the leftmost value of the topmost Via header */
   c = strchr(via, ',');
   if (c)
      *c = '\0';

   /* Check for rport */
   c = strstr(via, ";rport");
   if (c && (c[6] != '=')) /* rport query, not answer */
      ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);

   /* Check for maddr */
   maddr = strstr(via, "maddr=");
   if (maddr) {
      maddr += 6;
      c = maddr + strspn(maddr, "0123456789.");
      *c = '\0';
   }

   c = strchr(via, ';');
   if (c)
      *c = '\0';

   c = strchr(via, ' ');
   if (c) {
      *c = '\0';
      c = ast_skip_blanks(c+1);
      if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
         ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
         return;
      }
      pt = strchr(c, ':');
      if (pt)
         *pt++ = '\0';  /* remember port pointer */
      /* Use maddr if found */
      if (maddr)
         c = maddr;
      hp = ast_gethostbyname(c, &ahp);
      if (!hp) {
         ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
         return;
      }
      memset(&p->sa, 0, sizeof(p->sa));
      p->sa.sin_family = AF_INET;
      memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
      p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));

      if (sip_debug_test_pvt(p)) {
         const struct sockaddr_in *dst = sip_real_dst(p);
         ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
      }
   }
}
static attribute_unused void check_via_response ( struct sip_pvt p,
struct sip_request req 
) [static]

check received= and rport= in a SIP response. If we get a response with received= and/or rport= in the Via: line, use them as 'p->ourip' (see RFC 3581 for rport, and RFC 3261 for received). Using these two fields SIP can produce the correct address and port in the SIP headers without the need for STUN. The address part is also reused for the media sessions. Note that ast_sip_ouraddrfor() still rewrites p->ourip if you specify externip/seternaddr/stunaddr.

Definition at line 14323 of file chan_sip.c.

References ast_copy_string(), ast_parse_arg(), get_header(), sip_pvt::ourip, PARSE_INADDR, and strsep().

{
   char via[256];
   char *cur, *opts;

   ast_copy_string(via, get_header(req, "Via"), sizeof(via));

   /* Work on the leftmost value of the topmost Via header */
   opts = strchr(via, ',');
   if (opts)
      *opts = '\0';

   /* parse all relevant options */
   opts = strchr(via, ';');
   if (!opts)
      return;  /* no options to parse */
   *opts++ = '\0';
   while ( (cur = strsep(&opts, ";")) ) {
      if (!strncmp(cur, "rport=", 6)) {
         int port = strtol(cur+6, NULL, 10);
         /* XXX add error checking */
         p->ourip.sin_port = ntohs(port);
      } else if (!strncmp(cur, "received=", 9)) {
         if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
            ;  /* XXX add error checking */
      }
   }
}
static void cleanup_stale_contexts ( char *  new,
char *  old 
) [static]

Destroy disused contexts between reloads Only used in reload_config so the code for regcontext doesn't get ugly.

Definition at line 15516 of file chan_sip.c.

References ast_context_destroy(), ast_context_find(), ast_copy_string(), AST_MAX_CONTEXT, and strsep().

Referenced by reload_config().

{
   char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];

   while ((oldcontext = strsep(&old, "&"))) {
      stalecontext = '\0';
      ast_copy_string(newlist, new, sizeof(newlist));
      stringp = newlist;
      while ((newcontext = strsep(&stringp, "&"))) {
         if (!strcmp(newcontext, oldcontext)) {
            /* This is not the context you're looking for */
            stalecontext = '\0';
            break;
         } else if (strcmp(newcontext, oldcontext)) {
            stalecontext = oldcontext;
         }
         
      }
      if (stalecontext)
         ast_context_destroy(ast_context_find(stalecontext), "SIP");
   }
}
static void clear_peer_mailboxes ( struct sip_peer peer) [static]

Destroy all peer-related mailbox subscriptions

Definition at line 4840 of file chan_sip.c.

References AST_LIST_REMOVE_HEAD, destroy_mailbox(), mailbox, and sip_peer::mailboxes.

Referenced by set_peer_defaults(), and sip_destroy_peer().

{
   struct sip_mailbox *mailbox;

   while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
      destroy_mailbox(mailbox);
}
static int clear_realm_authentication ( struct sip_auth authlist) [static]

Clear realm authentication list (at reload)

Definition at line 24223 of file chan_sip.c.

References ast_free, and sip_auth::next.

Referenced by build_peer(), reload_config(), sip_destroy_peer(), and unload_module().

{
   struct sip_auth *a = authlist;
   struct sip_auth *b;

   while (a) {
      b = a;
      a = a->next;
      ast_free(b);
   }

   return 1;
}
static void clear_sip_domains ( void  ) [static]

Clear our domain list (at reload)

Definition at line 24156 of file chan_sip.c.

References ast_free, AST_LIST_LOCK, AST_LIST_REMOVE_HEAD, and AST_LIST_UNLOCK.

Referenced by reload_config(), and unload_module().

static const char* cli_yesno ( int  x) [static]

return Yes or No depending on the argument. This is used in many places in CLI command, having a function to generate this helps maintaining a consistent output (and possibly emitting the output in other languages, at some point).

Definition at line 15027 of file chan_sip.c.

Referenced by _sip_show_peer(), show_channels_cb(), sip_show_channel(), sip_show_settings(), sip_show_user(), and sip_show_users().

{
   return x ? "Yes" : "No";
}
static char * complete_sip_peer ( const char *  word,
int  state,
int  flags2 
) [static]

Do completion on peer name.

Definition at line 16885 of file chan_sip.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_t_iterator_next, ast_strdup, ast_test_flag, sip_peer::flags, sip_peer::name, and unref_peer().

Referenced by complete_sip_show_peer(), complete_sipnotify(), sip_do_debug(), and sip_prune_realtime().

{
   char *result = NULL;
   int wordlen = strlen(word);
   int which = 0;
   struct ao2_iterator i = ao2_iterator_init(peers, 0);
   struct sip_peer *peer;

   while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
      /* locking of the object is not required because only the name and flags are being compared */
      if (!strncasecmp(word, peer->name, wordlen) &&
            (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
            ++which > state)
         result = ast_strdup(peer->name);
      unref_peer(peer, "toss iterator peer ptr before break");
      if (result) {
         break;
      }
   }
   ao2_iterator_destroy(&i);
   return result;
}
static char * complete_sip_registered_peer ( const char *  word,
int  state,
int  flags2 
) [static]

Do completion on registered peer name.

Definition at line 16909 of file chan_sip.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_t_iterator_next, ast_strdup, ast_test_flag, sip_peer::expire, sip_peer::flags, sip_peer::name, and unref_peer().

Referenced by complete_sip_unregister().

{
       char *result = NULL;
       int wordlen = strlen(word);
       int which = 0;
       struct ao2_iterator i;
       struct sip_peer *peer;
       
       i = ao2_iterator_init(peers, 0);
       while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
          if (!strncasecmp(word, peer->name, wordlen) &&
         (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
         ++which > state && peer->expire > 0)
             result = ast_strdup(peer->name);
          if (result) {
             unref_peer(peer, "toss iterator peer ptr before break");
             break;
          }
          unref_peer(peer, "toss iterator peer ptr");
       }
       ao2_iterator_destroy(&i);
       return result;
}
static char * complete_sip_show_history ( const char *  line,
const char *  word,
int  pos,
int  state 
) [static]

Support routine for 'sip show history' CLI.

Definition at line 16934 of file chan_sip.c.

References complete_sipch().

Referenced by sip_show_history().

{
   if (pos == 3)
      return complete_sipch(line, word, pos, state);

   return NULL;
}
static char * complete_sip_show_peer ( const char *  line,
const char *  word,
int  pos,
int  state 
) [static]

Support routine for 'sip show peer' CLI.

Definition at line 16943 of file chan_sip.c.

References complete_sip_peer().

Referenced by sip_qualify_peer(), and sip_show_peer().

{
   if (pos == 3) {
      return complete_sip_peer(word, state, 0);
   }

   return NULL;
}
static char* complete_sip_show_user ( const char *  line,
const char *  word,
int  pos,
int  state 
) [static]

Support routine for 'sip show user' CLI.

Definition at line 16199 of file chan_sip.c.

References complete_sip_user().

Referenced by sip_show_user().

{
   if (pos == 3)
      return complete_sip_user(word, state);

   return NULL;
}
static char * complete_sip_unregister ( const char *  line,
const char *  word,
int  pos,
int  state 
) [static]

Support routine for 'sip unregister' CLI.

Definition at line 16953 of file chan_sip.c.

References complete_sip_registered_peer().

Referenced by sip_unregister().

{
       if (pos == 2)
               return complete_sip_registered_peer(word, state, 0);

       return NULL;
}
static char* complete_sip_user ( const char *  word,
int  state 
) [static]

Do completion on user name.

Definition at line 16169 of file chan_sip.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_iterator_next, ao2_lock(), ao2_unlock(), ast_strdup, sip_peer::name, SIP_TYPE_USER, sip_peer::type, unref_peer(), and user.

Referenced by complete_sip_show_user().

{
   char *result = NULL;
   int wordlen = strlen(word);
   int which = 0;
   struct ao2_iterator user_iter;
   struct sip_peer *user;

   user_iter = ao2_iterator_init(peers, 0);
   while ((user = ao2_iterator_next(&user_iter))) {
      ao2_lock(user);
      if (!(user->type & SIP_TYPE_USER)) {
         ao2_unlock(user);
         unref_peer(user, "complete sip user");
         continue;
      }
      /* locking of the object is not required because only the name and flags are being compared */
      if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
         result = ast_strdup(user->name);
      }
      ao2_unlock(user);
      unref_peer(user, "complete sip user");
      if (result) {
         break;
      }
   }
   ao2_iterator_destroy(&user_iter);
   return result;
}
static char* complete_sipch ( const char *  line,
const char *  word,
int  pos,
int  state 
) [static]

Support routine for 'sip show channel' and 'sip show history' CLI This is in charge of generating all strings that match a prefix in the given position. As many functions of this kind, each invokation has O(state) time complexity so be careful in using it.

Definition at line 16855 of file chan_sip.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_t_iterator_next, ast_strdup, ao2_iterator::c, sip_pvt::callid, dialog_unref(), sip_pvt_lock, and sip_pvt_unlock.

Referenced by complete_sip_show_history(), and sip_show_channel().

{
   int which=0;
   struct sip_pvt *cur;
   char *c = NULL;
   int wordlen = strlen(word);
   struct ao2_iterator i;

   if (pos != 3) {
      return NULL;
   }

   i = ao2_iterator_init(dialogs, 0);
   while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
      sip_pvt_lock(cur);
      if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
         c = ast_strdup(cur->callid);
         sip_pvt_unlock(cur);
         dialog_unref(cur, "drop ref in iterator loop break");
         break;
      }
      sip_pvt_unlock(cur);
      dialog_unref(cur, "drop ref in iterator loop");
   }
   ao2_iterator_destroy(&i);
   return c;
}
static char * complete_sipnotify ( const char *  line,
const char *  word,
int  pos,
int  state 
) [static]

Support routine for 'sip notify' CLI.

Definition at line 16962 of file chan_sip.c.

References ast_category_browse(), ast_strdup, and complete_sip_peer().

Referenced by sip_cli_notify().

{
   char *c = NULL;

   if (pos == 2) {
      int which = 0;
      char *cat = NULL;
      int wordlen = strlen(word);

      /* do completion for notify type */

      if (!notify_types)
         return NULL;
      
      while ( (cat = ast_category_browse(notify_types, cat)) ) {
         if (!strncasecmp(word, cat, wordlen) && ++which > state) {
            c = ast_strdup(cat);
            break;
         }
      }
      return c;
   }

   if (pos > 2)
      return complete_sip_peer(word, state, 0);

   return NULL;
}
static int copy_all_header ( struct sip_request req,
const struct sip_request orig,
const char *  field 
) [static]

Copy all headers from one request to another.

Definition at line 9546 of file chan_sip.c.

References __get_header(), add_header(), and ast_strlen_zero().

Referenced by respprep().

{
   int start = 0;
   int copied = 0;
   for (;;) {
      const char *tmp = __get_header(orig, field, &start);

      if (ast_strlen_zero(tmp))
         break;
      /* Add what we're responding to */
      add_header(req, field, tmp);
      copied++;
   }
   return copied ? 0 : -1;
}
static int copy_header ( struct sip_request req,
const struct sip_request orig,
const char *  field 
) [static]

Copy one header field from one request to another.

Definition at line 9535 of file chan_sip.c.

References add_header(), ast_log(), ast_strlen_zero(), get_header(), and LOG_NOTICE.

Referenced by reqprep(), and respprep().

{
   const char *tmp = get_header(orig, field);

   if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
      return add_header(req, field, tmp);
   ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
   return -1;
}
static void copy_request ( struct sip_request dst,
const struct sip_request src 
) [static]

copy SIP request (mostly used to save request for responses)

Definition at line 10884 of file chan_sip.c.

References ast_str_copy_string(), ast_str_create(), ast_str_strlen(), sip_request::content, and sip_request::data.

Referenced by _sip_tcp_helper_thread(), handle_request_bye(), handle_request_invite(), handle_request_refer(), handle_request_register(), handle_request_subscribe(), initialize_initreq(), parse_copy(), queue_request(), sip_park(), and sip_park_thread().

{
   /* XXX this function can encounter memory allocation errors, perhaps it
    * should return a value */

   struct ast_str *duplicate = dst->data;
   struct ast_str *duplicate_content = dst->content;

   /* copy the entire request then restore the original data and content
    * members from the dst request */
   memcpy(dst, src, sizeof(*dst));
   dst->data = duplicate;
   dst->content = duplicate_content;

   /* copy the data into the dst request */
   if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
      return;
   ast_str_copy_string(&dst->data, src->data);

   /* copy the content into the dst request (if it exists) */
   if (src->content) {
      if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
         return;
      ast_str_copy_string(&dst->content, src->content);
   }
}
static void copy_socket_data ( struct sip_socket to_sock,
const struct sip_socket from_sock 
) [static]

Definition at line 5294 of file chan_sip.c.

References ao2_ref, and sip_socket::tcptls_session.

Referenced by create_addr_from_peer(), handle_request_do(), parse_register_contact(), sip_poke_peer(), and transmit_response_using_temp().

{
   if (to_sock->tcptls_session) {
      ao2_ref(to_sock->tcptls_session, -1);
      to_sock->tcptls_session = NULL;
   }

   if (from_sock->tcptls_session) {
      ao2_ref(from_sock->tcptls_session, +1);
   }

   *to_sock = *from_sock;
}
static struct ast_variable * copy_vars ( struct ast_variable src) [static, read]

duplicate a list of channel variables,

Returns:
the copy.

Definition at line 2779 of file chan_sip.c.

References ast_variable_new(), and ast_variable::next.

Referenced by check_peer_ok(), and create_addr_from_peer().

{
   struct ast_variable *res = NULL, *tmp, *v = NULL;

   for (v = src ; v ; v = v->next) {
      if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
         tmp->next = res;
         res = tmp;
      }
   }
   return res;
}
static int copy_via_headers ( struct sip_pvt p,
struct sip_request req,
const struct sip_request orig,
const char *  field 
) [static]

Copy SIP VIA Headers from the request to the response.

Note:
If the client indicates that it wishes to know the port we received from, it adds ;rport without an argument to the topmost via header. We need to add the port number (from our point of view) to that parameter.
	We always add ;received=<ip address> to the topmost via header.
Received: RFC 3261, rport RFC 3581

Definition at line 9570 of file chan_sip.c.

References __get_header(), add_header(), ast_copy_string(), ast_inet_ntoa(), ast_log(), ast_strlen_zero(), ast_test_flag, sip_pvt::flags, LOG_NOTICE, sip_pvt::recv, SIP_NAT, SIP_NAT_ALWAYS, and SIP_NAT_RFC3581.

Referenced by respprep().

{
   int copied = 0;
   int start = 0;

   for (;;) {
      char new[512];
      const char *oh = __get_header(orig, field, &start);

      if (ast_strlen_zero(oh))
         break;

      if (!copied) { /* Only check for empty rport in topmost via header */
         char leftmost[512], *others, *rport;

         /* Only work on leftmost value */
         ast_copy_string(leftmost, oh, sizeof(leftmost));
         others = strchr(leftmost, ',');
         if (others)
             *others++ = '\0';

         /* Find ;rport;  (empty request) */
         rport = strstr(leftmost, ";rport");
         if (rport && *(rport+6) == '=') 
            rport = NULL;     /* We already have a parameter to rport */

         /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting)  */
         if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
            /* We need to add received port - rport */
            char *end;

            rport = strstr(leftmost, ";rport");

            if (rport) {
               end = strchr(rport + 1, ';');
               if (end)
                  memmove(rport, end, strlen(end) + 1);
               else
                  *rport = '\0';
            }

            /* Add rport to first VIA header if requested */
            snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
               leftmost, ast_inet_ntoa(p->recv.sin_addr),
               ntohs(p->recv.sin_port),
               others ? "," : "", others ? others : "");
         } else {
            /* We should *always* add a received to the topmost via */
            snprintf(new, sizeof(new), "%s;received=%s%s%s",
               leftmost, ast_inet_ntoa(p->recv.sin_addr),
               others ? "," : "", others ? others : "");
         }
         oh = new;   /* the header to copy */
      }  /* else add the following via headers untouched */
      add_header(req, field, oh);
      copied++;
   }
   if (!copied) {
      ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
      return -1;
   }
   return 0;
}
static int create_addr ( struct sip_pvt dialog,
const char *  opeer,
struct sockaddr_in *  sin,
int  newdialog 
) [static]

create address structure from device name Or, if peer not found, find it in the global DNS returns TRUE (-1) on failure, FALSE on success

Todo:
Fix this function. When we ask for SRV, we should check all transports In the future, we should first check NAPTR to find out transport preference

Definition at line 5462 of file chan_sip.c.

References ast_copy_string(), ast_get_srv(), ast_gethostbyname(), ast_log(), ast_string_field_set, ast_strlen_zero(), ast_test_flag, bindaddr, create_addr_from_peer(), do_setnat(), FALSE, find_peer(), FINDPEERS, sip_pvt::flags, get_srv_protocol(), get_srv_service(), global_t1, global_timer_b, hp, LOG_WARNING, MAXHOSTNAMELEN, obproxy_get(), sip_socket::port, port_str2int(), sip_pvt::portinuri, sip_pvt::recv, ref_proxy(), sip_pvt::sa, service, set_socket_transport(), sip_cfg, SIP_NAT, SIP_NAT_ROUTE, SIP_TRANSPORT_TLS, SIP_TRANSPORT_UDP, sip_pvt::socket, sip_settings::srvlookup, STANDARD_SIP_PORT, STANDARD_TLS_PORT, sip_pvt::timer_b, sip_pvt::timer_t1, sip_peer::tohost, TRUE, sip_socket::type, and unref_peer().

Referenced by __sip_subscribe_mwi_do(), manager_sipnotify(), sip_cli_notify(), sip_request_call(), and transmit_register().

{
   struct hostent *hp;
   struct ast_hostent ahp;
   struct sip_peer *peer;
   char *port;
   int portno = 0;
   char host[MAXHOSTNAMELEN], *hostn;
   char peername[256];
   int srv_ret = 0;

   ast_copy_string(peername, opeer, sizeof(peername));
   port = strchr(peername, ':');
   if (port) {
      *port++ = '\0';
      dialog->portinuri = 1;
   }
   dialog->sa.sin_family = AF_INET;
   dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
   dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
   peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);

   if (peer) {
      int res;
      if (newdialog) {
         set_socket_transport(&dialog->socket, 0);
      }
      res = create_addr_from_peer(dialog, peer);
      if (!ast_strlen_zero(port)) {
         if ((portno = atoi(port))) {
            dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
         }
      }
      unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
      return res;
   }

   do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);

   ast_string_field_set(dialog, tohost, peername);

   /* Get the outbound proxy information */
   ref_proxy(dialog, obproxy_get(dialog, NULL));

   if (sin) {
      /* This address should be updated using dnsmgr */
      memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
      if (!sin->sin_port) {
         portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
      } else {
         portno = ntohs(sin->sin_port);
      }
   } else {

      /* Let's see if we can find the host in DNS. First try DNS SRV records,
         then hostname lookup */
      /*! \todo Fix this function. When we ask for SRV, we should check all transports 
           In the future, we should first check NAPTR to find out transport preference
       */
      hostn = peername;
      /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
       * an A record lookup should be used instead of SRV.
       */
      if (!port && sip_cfg.srvlookup) {
         char service[MAXHOSTNAMELEN];
         int tportno;
         snprintf(service, sizeof(service), "_%s._%s.%s",
             get_srv_service(dialog->socket.type),
             get_srv_protocol(dialog->socket.type), peername);
         srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
         if (srv_ret > 0) {
            hostn = host;
            portno = tportno;
         }
      }
      if (!portno)
         portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
      hp = ast_gethostbyname(hostn, &ahp);
      if (!hp) {
         ast_log(LOG_WARNING, "No such host: %s\n", peername);
         return -1;
      }
      memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
   }

   if (!dialog->socket.type)
      set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
   if (!dialog->socket.port)
      dialog->socket.port = bindaddr.sin_port;
   dialog->sa.sin_port = htons(portno);
   dialog->recv = dialog->sa;
   return 0;
}
static int create_addr_from_peer ( struct sip_pvt dialog,
struct sip_peer peer 
) [static]

Create address structure from peer reference. This function copies data from peer to the dialog, so we don't have to look up the peer again from memory or database during the life time of the dialog.

Returns:
-1 on error, 0 on success.

Definition at line 5315 of file chan_sip.c.

References sip_peer::addr, sip_peer::allowtransfer, sip_pvt::allowtransfer, ao2_t_link, ao2_t_unlink, ast_clear_flag, ast_copy_flags, ast_debug, AST_FORMAT_VIDEO_MASK, ast_inet_ntoa(), ast_rtp_codec_setpref(), ast_rtp_destroy(), AST_RTP_DTMF, ast_rtp_set_rtpholdtimeout(), ast_rtp_set_rtpkeepalive(), ast_rtp_set_rtptimeout(), ast_rtp_setdtmf(), ast_rtp_setdtmfcompensate(), ast_set_flag, ast_strdupa, ast_string_field_build, ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_udptl_destroy(), ast_udptl_new_with_bindaddr(), sip_peer::auth, sip_peer::autoframing, sip_pvt::autoframing, bindaddr, sip_peer::call_limit, sip_peer::callgroup, sip_pvt::callgroup, sip_pvt::callid, sip_peer::capability, sip_pvt::capability, sip_peer::chanvars, sip_pvt::chanvars, check_request_transport, sip_peer::context, context, copy_socket_data(), copy_vars(), sip_peer::defaddr, do_setnat(), sip_peer::flags, sip_pvt::flags, sip_peer::fromdomain, sip_peer::fromuser, sip_peer::fullcontact, sip_request::headers, sip_pvt::initreq, sip_pvt::jointnoncodeccapability, language, sip_peer::language, sip_peer::lastms, sip_peer::maxcallbitrate, sip_pvt::maxcallbitrate, sip_peer::maxms, sip_peer::md5secret, sip_peer::mohinterpret, mohinterpret, sip_peer::mohsuggest, mohsuggest, sip_peer::name, sip_pvt::noncodeccapability, obproxy_get(), sip_peer::parkinglot, parkinglot, sip_pvt::peerauth, sip_peer::pickupgroup, sip_pvt::pickupgroup, sip_peer::portinuri, sip_pvt::portinuri, sip_peer::prefs, sip_pvt::prefs, sip_pvt::recv, ref_proxy(), sip_pvt::rtp, sip_peer::rtpholdtimeout, sip_peer::rtpkeepalive, sip_pvt::rtptimeout, sip_peer::rtptimeout, sip_pvt::sa, sip_peer::secret, set_t38_capabilities(), SIP_CALL_LIMIT, SIP_DTMF, SIP_DTMF_AUTO, SIP_DTMF_RFC2833, SIP_FLAGS_TO_COPY, SIP_NAT, SIP_NAT_ROUTE, SIP_PAGE2_FLAGS_TO_COPY, SIP_PAGE2_RFC2833_COMPENSATE, SIP_PAGE2_T38SUPPORT, SIP_PAGE2_TEXTSUPPORT, SIP_PAGE2_VIDEOSUPPORT, SIP_PAGE2_VIDEOSUPPORT_ALWAYS, sip_peer::socket, sip_pvt::socket, sip_peer::t38_maxdatagram, sip_pvt::t38_maxdatagram, sip_pvt::timer_b, sip_peer::timer_b, sip_peer::timer_t1, sip_pvt::timer_t1, sip_pvt::tohost, sip_peer::tohost, sip_pvt::trtp, sip_socket::type, sip_pvt::udptl, sip_peer::username, and sip_pvt::vrtp.

Referenced by create_addr(), and sip_send_mwi_to_peer().

{

   /* this checks that the dialog is contacting the peer on a valid
    * transport type based on the peers transport configuration,
    * otherwise, this function bails out */
   if (dialog->socket.type && check_request_transport(peer, dialog))
      return -1;
   copy_socket_data(&dialog->socket, &peer->socket);

   if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
       (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
      dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
      dialog->recv = dialog->sa;
   } else 
      return -1;

   ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
   ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
   dialog->capability = peer->capability;
   if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
         (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
            !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
         dialog->vrtp) {
      ast_rtp_destroy(dialog->vrtp);
      dialog->vrtp = NULL;
   }
   if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
      ast_rtp_destroy(dialog->trtp);
      dialog->trtp = NULL;
   }
   dialog->prefs = peer->prefs;
   if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
      /* t38pt_udptl was enabled in the peer and not in [general] */
      if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr)))) {
         dialog->t38_maxdatagram = peer->t38_maxdatagram;
         set_t38_capabilities(dialog);
      } else {
         /* It is impossible to support T38 without udptl */
         ast_debug(1, "UDPTL creation failed on dialog.\n");
         ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
      }
   } else if (dialog->udptl) {
      ast_udptl_destroy(dialog->udptl);
      dialog->udptl = NULL;
   }
   do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);

   if (dialog->rtp) { /* Audio */
      ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
      ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
      ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
      ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
      ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
      /* Set Frame packetization */
      ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
      dialog->autoframing = peer->autoframing;
   }
   if (dialog->vrtp) { /* Video */
      ast_rtp_setdtmf(dialog->vrtp, 0);
      ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
      ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
      ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
      ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
   }
   if (dialog->trtp) { /* Realtime text */
      ast_rtp_setdtmf(dialog->trtp, 0);
      ast_rtp_setdtmfcompensate(dialog->trtp, 0);
      ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
      ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
      ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
   }

   ast_string_field_set(dialog, peername, peer->name);
   ast_string_field_set(dialog, authname, peer->username);
   ast_string_field_set(dialog, username, peer->username);
   ast_string_field_set(dialog, peersecret, peer->secret);
   ast_string_field_set(dialog, peermd5secret, peer->md5secret);
   ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
   ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
   ast_string_field_set(dialog, tohost, peer->tohost);
   ast_string_field_set(dialog, fullcontact, peer->fullcontact);
   ast_string_field_set(dialog, context, peer->context);
   ast_string_field_set(dialog, parkinglot, peer->parkinglot);
   ref_proxy(dialog, obproxy_get(dialog, peer));
   dialog->callgroup = peer->callgroup;
   dialog->pickupgroup = peer->pickupgroup;
   dialog->allowtransfer = peer->allowtransfer;
   dialog->jointnoncodeccapability = dialog->noncodeccapability;
   dialog->rtptimeout = peer->rtptimeout;
   dialog->peerauth = peer->auth;
   dialog->maxcallbitrate = peer->maxcallbitrate;
   if (ast_strlen_zero(dialog->tohost))
      ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
   if (!ast_strlen_zero(peer->fromdomain)) {
      ast_string_field_set(dialog, fromdomain, peer->fromdomain);
      if (!dialog->initreq.headers) {
         char *c;
         char *tmpcall = ast_strdupa(dialog->callid);
         /* this sure looks to me like we are going to change the callid on this dialog!! */
         c = strchr(tmpcall, '@');
         if (c) {
            *c = '\0';
            ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
            ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
            ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
         }
      }
   }
   if (!ast_strlen_zero(peer->fromuser)) 
      ast_string_field_set(dialog, fromuser, peer->fromuser);
   if (!ast_strlen_zero(peer->language))
      ast_string_field_set(dialog, language, peer->language);
   /* Set timer T1 to RTT for this peer (if known by qualify=) */
   /* Minimum is settable or default to 100 ms */
   /* If there is a maxms and lastms from a qualify use that over a manual T1
      value. Otherwise, use the peer's T1 value. */
   if (peer->maxms && peer->lastms)
      dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
   else
      dialog->timer_t1 = peer->timer_t1;

   /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
      the known timer */
   if (peer->timer_b)
      dialog->timer_b = peer->timer_b;
   else
      dialog->timer_b = 64 * dialog->timer_t1;

   if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
       (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
      dialog->noncodeccapability |= AST_RTP_DTMF;
   else
      dialog->noncodeccapability &= ~AST_RTP_DTMF;
   if (peer->call_limit)
      ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
   if (!dialog->portinuri)
      dialog->portinuri = peer->portinuri;
   
   dialog->chanvars = copy_vars(peer->chanvars);

   return 0;
}
static void deinit_req ( struct sip_request req) [static]

Deinitialize SIP response/request.

Definition at line 9784 of file chan_sip.c.

References ast_free, sip_request::content, and sip_request::data.

Referenced by __sip_destroy(), _sip_tcp_helper_thread(), send_request(), send_response(), sip_park(), sip_park_thread(), and sipsock_read().

{
   if (req->data) {
      ast_free(req->data);
      req->data = NULL;
   }
   if (req->content) {
      ast_free(req->content);
      req->content = NULL;
   }
}
static void destroy_association ( struct sip_peer peer) [static]

Remove registration data from realtime database or AST/DB when registration expires.

Definition at line 12485 of file chan_sip.c.

References ast_check_realtime(), ast_db_del(), ast_update_realtime(), sip_settings::ignore_regexpire, sip_peer::name, sip_settings::peer_rtupdate, sip_peer::rt_fromcontact, SENTINEL, and sip_cfg.

Referenced by build_peer(), expire_register(), and parse_register_contact().

{
   int realtimeregs = ast_check_realtime("sipregs");
   char *tablename = (realtimeregs) ? "sipregs" : "sippeers";

   if (!sip_cfg.ignore_regexpire) {
      if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
         ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
      } else {
         ast_db_del("SIP/Registry", peer->name);
      }
   }
}
static void destroy_mailbox ( struct sip_mailbox mailbox) [static]

Destroy mailbox subscriptions

Definition at line 4828 of file chan_sip.c.

References ast_event_unsubscribe(), ast_free, sip_mailbox::context, sip_mailbox::event_sub, and sip_mailbox::mailbox.

Referenced by build_peer(), and clear_peer_mailboxes().

{
   if (mailbox->mailbox)
      ast_free(mailbox->mailbox);
   if (mailbox->context)
      ast_free(mailbox->context);
   if (mailbox->event_sub)
      ast_event_unsubscribe(mailbox->event_sub);
   ast_free(mailbox);
}
static int determine_firstline_parts ( struct sip_request req) [static]

Parse first line of incoming SIP request.

Definition at line 10942 of file chan_sip.c.

References ast_debug, ast_skip_blanks(), ast_skip_nonblanks(), ast_trim_blanks(), sip_request::data, sip_request::rlPart1, and sip_request::rlPart2.

Referenced by parse_request().

{
   char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
   char *local_rlPart1;

   if (!*e)
      return -1;
   req->rlPart1 = e - req->data->str;  /* method or protocol */
   local_rlPart1 = e;
   e = ast_skip_nonblanks(e);
   if (*e)
      *e++ = '\0';
   /* Get URI or status code */
   e = ast_skip_blanks(e);
   if ( !*e )
      return -1;
   ast_trim_blanks(e);

   if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
      if (strlen(e) < 3)   /* status code is 3 digits */
         return -1;
      req->rlPart2 = e - req->data->str;
   } else { /* We have a request */
      if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
         ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
         e++;
         if (!*e)
            return -1; 
      }
      req->rlPart2 = e - req->data->str;  /* URI */
      e = ast_skip_nonblanks(e);
      if (*e)
         *e++ = '\0';
      e = ast_skip_blanks(e);
      if (strcasecmp(e, "SIP/2.0") ) {
         ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
         return -1;
      }
   }
   return 1;
}
static int dialog_cmp_cb ( void *  obj,
void *  arg,
int  flags 
) [static]
Note:
The only member of the dialog used here callid string

Definition at line 2145 of file chan_sip.c.

References sip_pvt::callid, CMP_MATCH, and CMP_STOP.

Referenced by load_module().

{
   struct sip_pvt *pvt = obj, *pvt2 = arg;
   
   return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
}
static int dialog_dump_func ( void *  userobj,
void *  arg,
int  flags 
) [static]

Definition at line 15432 of file chan_sip.c.

References ao2_t_ref, ast_cli(), and sip_pvt::callid.

Referenced by sip_show_objects().

{
   struct sip_pvt *pvt = userobj;
   int refc = ao2_t_ref(userobj, 0, "");
   int *fd = arg;
   
   ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n", 
          pvt->callid, 0, refc);
   return 0;
}
static int dialog_hash_cb ( const void *  obj,
const int  flags 
) [static]
Note:
The only member of the dialog used here callid string

Definition at line 2135 of file chan_sip.c.

References ast_str_case_hash(), and sip_pvt::callid.

Referenced by load_module().

{
   const struct sip_pvt *pvt = obj;

   return ast_str_case_hash(pvt->callid);
}
static int dialog_needdestroy ( void *  dialogobj,
void *  arg,
int  flags 
) [static]

Match dialogs that need to be destroyed.

This is used with ao2_callback to unlink/delete all dialogs that are marked needdestroy. It will return CMP_MATCH for candidates, and they will be unlinked.

Todo:
Re-work this to improve efficiency. Currently, this function is called on _every_ dialog after processing _every_ incoming SIP/UDP packet, or potentially even more often when the scheduler has entries to run.

Definition at line 15551 of file chan_sip.c.

References ast_debug, ast_rtp_get_bridged(), sip_pvt::callid, check_rtp_timeout(), dialog_unlink_all(), FALSE, sip_pvt::method, sip_pvt::needdestroy, sip_pvt::owner, sip_pvt::packets, sip_pvt::rtp, sip_methods, sip_pvt_trylock, sip_pvt_unlock, cfsip_methods::text, TRUE, and sip_pvt::vrtp.

Referenced by do_monitor().

{
   struct sip_pvt *dialog = dialogobj;
   time_t *t = arg;

   if (sip_pvt_trylock(dialog)) {
      /* Don't block the monitor thread.  This function is called often enough
       * that we can wait for the next time around. */
      return 0;
   }
   
   /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
   check_rtp_timeout(dialog, *t);

   /* If we have sessions that needs to be destroyed, do it now */
   /* Check if we have outstanding requests not responsed to or an active call
      - if that's the case, wait with destruction */
   if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
      /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
      if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
         ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
         sip_pvt_unlock(dialog);
         return 0;
      }
      
      if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
         ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
         sip_pvt_unlock(dialog);
         return 0;
      }

      sip_pvt_unlock(dialog);
      /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
      /* the CMP_MATCH will unlink this dialog from the dialog hash table */
      dialog_unlink_all(dialog, TRUE, FALSE);
      return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
   }

   sip_pvt_unlock(dialog);

   return 0;
}
static struct sip_pvt* dialog_ref ( struct sip_pvt p,
char *  tag 
) [static, read]

when we create or delete references, make sure to use these functions so we keep track of the refcounts. To simplify the code, we allow a NULL to be passed to dialog_unref().

Definition at line 1776 of file chan_sip.c.

References ao2_ref, ast_log(), and LOG_ERROR.

Referenced by __sip_reliable_xmit(), dialog_unlink_all(), handle_request_invite(), handle_request_subscribe(), handle_response_invite(), manager_sipnotify(), queue_request(), sip_call(), sip_cli_notify(), sip_new(), sip_poke_peer(), sip_scheddestroy(), sip_send_mwi_to_peer(), start_session_timer(), transmit_register(), and update_provisional_keepalive().

{
   if (p)
      ao2_ref(p, 1);
   else
      ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
   return p;
}
static void * dialog_unlink_all ( struct sip_pvt dialog,
int  lockowner,
int  lockdialoglist 
) [static]

Unlink a dialog from the dialogs container, as well as any other places that it may be currently stored.

Note:
A reference to the dialog must be held before calling this function, and this function does not release that reference.

Definition at line 3320 of file chan_sip.c.

References ao2_t_unlink, ast_channel_lock, ast_channel_unlock, ast_debug, ast_extension_state_del(), ast_free, AST_SCHED_DEL, AST_SCHED_DEL_UNREF, sip_pvt::autokillid, sip_peer::call, sip_registry::call, sip_pkt::data, dialog_ref(), dialog_unref(), sip_pvt::initid, sip_peer::mwipvt, ast_channel::name, sip_pkt::next, sip_pkt::owner, sip_pvt::owner, sip_pvt::packets, sip_pvt::provisional_keepalive_sched_id, sip_pvt::registry, registry_unref(), sip_pvt::relatedpeer, sip_pvt::request_queue_sched_id, sip_pkt::retransid, sip_pvt::stateid, sip_pvt::t38id, ast_channel::tech_pvt, and sip_pvt::waitid.

Referenced by __sip_autodestruct(), __sip_subscribe_mwi_do(), dialog_needdestroy(), handle_request_subscribe(), manager_sipnotify(), reload_config(), sip_cli_notify(), sip_destroy_peer(), sip_poke_noanswer(), sip_poke_peer(), sip_registry_destroy(), sip_request_call(), sip_send_mwi_to_peer(), transmit_register(), and unload_module().

{
   struct sip_pkt *cp;

   dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");

   ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");

   /* Unlink us from the owner (channel) if we have one */
   if (dialog->owner) {
      if (lockowner)
         ast_channel_lock(dialog->owner);
      ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
      dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
      if (lockowner)
         ast_channel_unlock(dialog->owner);
   }
   if (dialog->registry) {
      if (dialog->registry->call == dialog)
         dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
      dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
   }
   if (dialog->stateid > -1) {
      ast_extension_state_del(dialog->stateid, NULL);
      dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
      dialog->stateid = -1; /* shouldn't we 'zero' this out? */
   }
   /* Remove link from peer to subscription of MWI */
   if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
      dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
   if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
      dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");

   /* remove all current packets in this dialog */
   while((cp = dialog->packets)) {
      dialog->packets = dialog->packets->next;
      AST_SCHED_DEL(sched, cp->retransid);
      dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
      if (cp->data) {
         ast_free(cp->data);
      }
      ast_free(cp);
   }

   AST_SCHED_DEL_UNREF(sched, dialog->waitid, dialog_unref(dialog, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));

   AST_SCHED_DEL_UNREF(sched, dialog->initid, dialog_unref(dialog, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
   
   if (dialog->autokillid > -1)
      AST_SCHED_DEL_UNREF(sched, dialog->autokillid, dialog_unref(dialog, "when you delete the autokillid sched, you should dec the refcount for the stored dialog ptr"));

   if (dialog->request_queue_sched_id > -1) {
      AST_SCHED_DEL_UNREF(sched, dialog->request_queue_sched_id, dialog_unref(dialog, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
   }

   AST_SCHED_DEL_UNREF(sched, dialog->provisional_keepalive_sched_id, dialog_unref(dialog, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));

   if (dialog->t38id > -1) {
      AST_SCHED_DEL_UNREF(sched, dialog->t38id, dialog_unref(dialog, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
   }

   dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
   return NULL;
}
static int do_magic_pickup ( struct ast_channel channel,
const char *  extension,
const char *  context 
) [static]

Definition at line 20184 of file chan_sip.c.

References ast_debug, ast_log(), AST_MAX_CONTEXT, AST_MAX_EXTENSION, ast_str_alloca, ast_str_set(), IGNORE_CONTEXT, LOG_ERROR, sip_settings::notifycid, pbx_exec(), pbx_findapp(), sip_cfg, and str.

Referenced by handle_request_invite().

{
   struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
   struct ast_app *pickup = pbx_findapp("Pickup");

   if (!pickup) {
      ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
      return -1;
   }

   ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);

   ast_debug(2, "About to call Pickup(%s)\n", str->str);

   /* There is no point in capturing the return value since pickup_exec
      doesn't return anything meaningful unless the passed data is an empty
      string (which in our case it will not be) */
   pbx_exec(channel, pickup, str->str);

   return 0;
}
static void * do_monitor ( void *  data) [static]

The SIP monitoring thread.

Note:
This thread monitors all the SIP sessions and peers that needs notification of mwi (and thus do not have a separate thread) indefinitely

Definition at line 23074 of file chan_sip.c.

References ao2_t_callback, ast_debug, ast_io_add(), ast_io_change(), AST_IO_IN, ast_io_remove(), ast_io_wait(), ast_mutex_lock(), ast_mutex_unlock(), ast_sched_runq(), ast_sched_wait(), ast_verb, dialog_needdestroy(), FALSE, monlock, OBJ_MULTIPLE, OBJ_NODATA, OBJ_UNLINK, sip_do_reload(), sip_reload_lock, sip_reloading, and sipsock_read().

Referenced by restart_monitor().

{
   int res;
   time_t t;
   int reloading;

   /* Add an I/O event to our SIP UDP socket */
   if (sipsock > -1) 
      sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);

   /* From here on out, we die whenever asked */
   for(;;) {
      /* Check for a reload request */
      ast_mutex_lock(&sip_reload_lock);
      reloading = sip_reloading;
      sip_reloading = FALSE;
      ast_mutex_unlock(&sip_reload_lock);
      if (reloading) {
         ast_verb(1, "Reloading SIP\n");
         sip_do_reload(sip_reloadreason);

         /* Change the I/O fd of our UDP socket */
         if (sipsock > -1) {
            if (sipsock_read_id)
               sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
            else
               sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
         } else if (sipsock_read_id) {
            ast_io_remove(io, sipsock_read_id);
            sipsock_read_id = NULL;
         }
      }

      /* Check for dialogs needing to be killed */
      t = time(NULL);
      /* don't scan the dialogs list if it hasn't been a reasonable period
         of time since the last time we did it (when MWI is being sent, we can
         get back to this point every millisecond or less)
      */
      ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
            "callback to remove dialogs w/needdestroy");

      /* the old methodology would be to restart the search for dialogs to delete with every 
         dialog that was found and destroyed, probably because the list contents would change,
         so we'd need to restart. This isn't the best thing to do with callbacks. */

      /* XXX TODO The scheduler usage in this module does not have sufficient 
       * synchronization being done between running the scheduler and places 
       * scheduling tasks.  As it is written, any scheduled item may not run 
       * any sooner than about  1 second, regardless of whether a sooner time 
       * was asked for. */

      pthread_testcancel();
      /* Wait for sched or io */
      res = ast_sched_wait(sched);
      if ((res < 0) || (res > 1000))
         res = 1000;
      res = ast_io_wait(io, res);
      if (res > 20)
         ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
      ast_mutex_lock(&monlock);
      res = ast_sched_runq(sched);
      if (res >= 20)
         ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
      ast_mutex_unlock(&monlock);
   }

   /* Never reached */
   return NULL;
}
static int do_proxy_auth ( struct sip_pvt p,
struct sip_request req,
enum sip_auth_type  code,
int  sipmethod,
int  init 
) [static]

Add authentication on outbound SIP packet.

Definition at line 17590 of file chan_sip.c.

References ast_calloc, ast_debug, sip_invite_param::auth, auth_headers(), sip_invite_param::authheader, sip_pvt::authtries, sip_request::header, sip_pvt::options, reply_digest(), SIP_INVITE, sip_methods, cfsip_methods::text, and transmit_invite().

Referenced by handle_response(), handle_response_invite(), handle_response_notify(), handle_response_refer(), and handle_response_subscribe().

{
   char *header, *respheader;
   char digest[1024];

   if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
      return -2;

   p->authtries++;
   auth_headers(code, &header, &respheader);
   ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
   memset(digest, 0, sizeof(digest));
   if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
      /* No way to authenticate */
      return -1;
   }
   /* Now we have a reply digest */
   p->options->auth = digest;
   p->options->authheader = respheader;
   return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init); 
}
static int do_register_auth ( struct sip_pvt p,
struct sip_request req,
enum sip_auth_type  code 
) [static]

Authenticate for outbound registration.

Definition at line 17566 of file chan_sip.c.

References append_history, ast_verbose(), auth_headers(), sip_pvt::authtries, sip_pvt::do_history, sip_request::header, sip_registry::hostname, sip_pvt::registry, reply_digest(), sip_debug_test_pvt(), SIP_REGISTER, and transmit_register().

Referenced by handle_response_register().

{
   char *header, *respheader;
   char digest[1024];

   p->authtries++;
   auth_headers(code, &header, &respheader);
   memset(digest, 0, sizeof(digest));
   if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
      /* There's nothing to use for authentication */
      /* No digest challenge in request */
      if (sip_debug_test_pvt(p) && p->registry)
         ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
         /* No old challenge */
      return -1;
   }
   if (p->do_history)
      append_history(p, "RegistryAuth", "Try: %d", p->authtries);
   if (sip_debug_test_pvt(p) && p->registry)
      ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
   return transmit_register(p->registry, SIP_REGISTER, digest, respheader); 
}
static void do_setnat ( struct sip_pvt p,
int  natflags 
) [static]

Set nat mode on the various data sockets.

Definition at line 5209 of file chan_sip.c.

References ast_debug, ast_rtp_setnat(), ast_udptl_setnat(), sip_pvt::rtp, sip_pvt::trtp, sip_pvt::udptl, and sip_pvt::vrtp.

Referenced by check_peer_ok(), create_addr(), create_addr_from_peer(), sip_alloc(), and transmit_response_using_temp().

{
   const char *mode = natflags ? "On" : "Off";

   if (p->rtp) {
      ast_debug(1, "Setting NAT on RTP to %s\n", mode);
      ast_rtp_setnat(p->rtp, natflags);
   }
   if (p->vrtp) {
      ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
      ast_rtp_setnat(p->vrtp, natflags);
   }
   if (p->udptl) {
      ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
      ast_udptl_setnat(p->udptl, natflags);
   }
   if (p->trtp) {
      ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
      ast_rtp_setnat(p->trtp, natflags);
   }
}
static const char * domain_mode_to_text ( const enum domain_mode  mode) [static]

Print domain mode to cli.

Definition at line 15747 of file chan_sip.c.

References SIP_DOMAIN_AUTO, and SIP_DOMAIN_CONFIG.

Referenced by sip_show_domains().

{
   switch (mode) {
   case SIP_DOMAIN_AUTO:
      return "[Automatic]";
   case SIP_DOMAIN_CONFIG:
      return "[Configured]";
   }

   return "";
}
static const char * dtmfmode2str ( int  mode) [static]

Convert DTMF mode to printable string.

Definition at line 15488 of file chan_sip.c.

References map_x_s().

Referenced by _sip_show_peer(), sip_show_channel(), and sip_show_settings().

{
   return map_x_s(dtmfstr, mode, "<error>");
}
static int expire_register ( const void *  data) [static]

Expire registration of SIP peer.

Definition at line 12513 of file chan_sip.c.

References sip_peer::addr, ao2_ref, ast_debug, AST_DEVICE_UNKNOWN, ast_devstate_changed(), ast_test_flag, sip_peer::default_outbound_transport, destroy_association(), EVENT_FLAG_SYSTEM, sip_peer::expire, FALSE, sip_peer::flags, sip_peer::is_realtime, manager_event, sip_peer::name, sip_peer::portinuri, register_peer_exten(), sip_peer::selfdestruct, set_socket_transport(), SIP_PAGE2_RTAUTOCLEAR, sip_peer::socket, sip_socket::tcptls_session, unlink_peer_from_tables(), and unref_peer().

Referenced by parse_register_contact(), realtime_peer(), reg_source_db(), sip_show_sched(), and sip_unregister().

{
   struct sip_peer *peer = (struct sip_peer *)data;

   if (!peer)     /* Hmmm. We have no peer. Weird. */
      return 0;

   peer->expire = -1;
   peer->portinuri = 0;

   destroy_association(peer); /* remove registration data from storage */
   set_socket_transport(&peer->socket, peer->default_outbound_transport);

   if (peer->socket.tcptls_session) {
      ao2_ref(peer->socket.tcptls_session, -1);
      peer->socket.tcptls_session = NULL;
   }

   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
   register_peer_exten(peer, FALSE);   /* Remove regexten */
   ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);

   /* Do we need to release this peer from memory? 
      Only for realtime peers and autocreated peers
   */
   if (peer->is_realtime)
      ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);

   if (peer->selfdestruct ||
       ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
      unlink_peer_from_tables(peer);
   }

   /* Only clear the addr after we check for destruction.  The addr must remain
    * in order to unlink from the peers_by_ip container correctly */
   memset(&peer->addr, 0, sizeof(peer->addr));

   unref_peer(peer, "removing peer ref for expire_register");

   return 0;
}
static void extract_uri ( struct sip_pvt p,
struct sip_request req 
) [static]

Check Contact: URI of SIP message.

Definition at line 11043 of file chan_sip.c.

References ast_copy_string(), ast_string_field_set, ast_strlen_zero(), get_header(), get_in_brackets(), remove_uri_parameters(), and SIPBUFSIZE.

Referenced by handle_incoming(), and handle_request_invite().

{
   char stripped[SIPBUFSIZE];
   char *c;

   ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
   c = get_in_brackets(stripped);
   /* Cut the URI at the at sign after the @, not in the username part */
   c = remove_uri_parameters(c);
   if (!ast_strlen_zero(c))
      ast_string_field_set(p, uri, c);

}
static const char* faxec2str ( int  faxec) [static]

Definition at line 15917 of file chan_sip.c.

References map_x_s().

Referenced by _sip_show_peer(), and sip_show_settings().

{
   return map_x_s(faxecmodes, faxec, "Unknown");
}
static int finalize_content ( struct sip_request req) [static]

Add 'Content-Length' header and content to SIP message.

Definition at line 9502 of file chan_sip.c.

References add_header(), ast_log(), ast_str_append(), ast_str_buffer(), ast_str_strlen(), sip_request::content, sip_request::data, sip_request::len, sip_request::lines, and LOG_WARNING.

Referenced by send_request(), and send_response().

{
   char clen[10];

   if (req->lines) {
      ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
      return -1;
   }

   snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
   add_header(req, "Content-Length", clen);

   if (ast_str_strlen(req->content)) {
      ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
      req->len = ast_str_strlen(req->data);
   }
   req->lines = ast_str_strlen(req->content) ? 1 : 0;
   return 0;
}
static const char * find_alias ( const char *  name,
const char *  _default 
) [static]

Find compressed SIP alias.

Structure for conversion between compressed SIP and "normal" SIP

Definition at line 7116 of file chan_sip.c.

References aliases, and ARRAY_LEN.

Referenced by __get_header(), and add_header().

{
   /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
   static const struct cfalias {
      char * const fullname;
      char * const shortname;
   } aliases[] = {
      { "Content-Type",  "c" },
      { "Content-Encoding",    "e" },
      { "From",       "f" },
      { "Call-ID",       "i" },
      { "Contact",       "m" },
      { "Content-Length",   "l" },
      { "Subject",       "s" },
      { "To",         "t" },
      { "Supported",     "k" },
      { "Refer-To",      "r" },
      { "Referred-By",   "b" },
      { "Allow-Events",  "u" },
      { "Event",      "o" },
      { "Via",     "v" },
      { "Accept-Contact",      "a" },
      { "Reject-Contact",      "j" },
      { "Request-Disposition", "d" },
      { "Session-Expires",     "x" },
      { "Identity",            "y" },
      { "Identity-Info",       "n" },
   };
   int x;

   for (x = 0; x < ARRAY_LEN(aliases); x++) {
      if (!strcasecmp(aliases[x].fullname, name))
         return aliases[x].shortname;
   }

   return _default;
}
static int find_by_name ( void *  obj,
void *  arg,
void *  data,
int  flags 
) [static]

Definition at line 5119 of file chan_sip.c.

References CMP_MATCH, CMP_STOP, sip_request::data, FINDALLDEVICES, FINDPEERS, FINDUSERS, match(), sip_peer::name, SIP_TYPE_PEER, SIP_TYPE_USER, and sip_peer::type.

Referenced by find_peer().

{
   struct sip_peer *search = obj, *match = arg;
   int *which_objects = data;

   /* Usernames in SIP uri's are case sensitive. Domains are not */
   if (strcmp(search->name, match->name)) {
      return 0;
   }

   switch (*which_objects) {
   case FINDUSERS:
      if (!(search->type & SIP_TYPE_USER)) {
         return 0;
      }
      break;
   case FINDPEERS:
      if (!(search->type & SIP_TYPE_PEER)) {
         return 0;
      }
      break;
   case FINDALLDEVICES:
      break;
   }

   return CMP_MATCH | CMP_STOP;
}
static struct sip_pvt * find_call ( struct sip_request req,
struct sockaddr_in *  sin,
const int  intended_method 
) [static, read]

find or create a dialog structure for an incoming SIP message. Connect incoming SIP message to current dialog or create new dialog structure Returns a reference to the sip_pvt object, remember to give it back once done. Called by handle_incoming(), sipsock_read

Definition at line 7770 of file chan_sip.c.

References ao2_lock(), ao2_t_callback, ao2_t_find, ao2_unlock(), ast_debug, ast_strlen_zero(), sip_pvt::callid, find_call_cb_arg::callid, CAN_CREATE_DIALOG, CAN_CREATE_DIALOG_UNSUPPORTED_METHOD, find_call_cb(), find_call_cb_arg::fromtag, get_header(), gettag(), sip_request::has_to_tag, sip_request::method, find_call_cb_arg::method, OBJ_POINTER, sip_settings::pedanticsipchecking, SIP_ACK, sip_alloc(), SIP_BYE, sip_cfg, SIP_INFO, sip_methods, SIP_NOTIFY, sip_pvt_lock, sip_pvt_trylock, SIP_REFER, SIP_RESPONSE, find_call_cb_arg::tag, cfsip_methods::text, find_call_cb_arg::totag, and transmit_response_using_temp().

Referenced by handle_request_do().

{
   struct sip_pvt *p = NULL;
   char *tag = "";   /* note, tag is never NULL */
   char totag[128];
   char fromtag[128];
   struct find_call_cb_arg arg;
   const char *callid = get_header(req, "Call-ID");
   const char *from = get_header(req, "From");
   const char *to = get_header(req, "To");
   const char *cseq = get_header(req, "Cseq");
   struct sip_pvt *sip_pvt_ptr;

   /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
   /* get_header always returns non-NULL so we must use ast_strlen_zero() */
   if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
         ast_strlen_zero(from) || ast_strlen_zero(cseq))
      return NULL;   /* Invalid packet */

   arg.method = req->method;
   arg.callid = callid;
   arg.fromtag = fromtag;
   arg.totag = totag;
   arg.tag = ""; /* make sure tag is never NULL */

   if (sip_cfg.pedanticsipchecking) {
      /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
         we need more to identify a branch - so we have to check branch, from
         and to tags to identify a call leg.
         For Asterisk to behave correctly, you need to turn on pedanticsipchecking
         in sip.conf
         */
      if (gettag(req, "To", totag, sizeof(totag)))
         req->has_to_tag = 1; /* Used in handle_request/response */
      gettag(req, "From", fromtag, sizeof(fromtag));

      tag = (req->method == SIP_RESPONSE) ? totag : fromtag;

      ast_debug(5, "= Looking for  Call ID: %s (Checking %s) --From tag %s --To-tag %s  \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);

      /* All messages must always have From: tag */
      if (ast_strlen_zero(fromtag)) {
         ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
         return NULL;
      }
      /* reject requests that must always have a To: tag */
      if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
         ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
         return NULL;
      }
   }

restartsearch:
   if (!sip_cfg.pedanticsipchecking) {
      struct sip_pvt tmp_dialog = {
         .callid = callid,
      };       
      sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
      if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
         /* Found the call */
         sip_pvt_lock(sip_pvt_ptr);
         return sip_pvt_ptr;
      }
   } else { /* in pedantic mode! -- do the fancy linear search */
      ao2_lock(dialogs);
      p = ao2_t_callback(dialogs, 0 /* single, data */, find_call_cb, &arg, "pedantic linear search for dialog");
      if (p) {
         if (sip_pvt_trylock(p)) {
            ao2_unlock(dialogs);
            usleep(1);
            goto restartsearch;
         }
         ao2_unlock(dialogs);
         return p;
      }
      ao2_unlock(dialogs);
   }
 
   /* See if the method is capable of creating a dialog */
   if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
      if (intended_method == SIP_REFER) {
         /* We do support REFER, but not outside of a dialog yet */
         transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
      } else if (intended_method == SIP_NOTIFY) {
         /* We do not support out-of-dialog NOTIFY either,
            like voicemail notification, so cancel that early */
         transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 No subscription");
      } else {
         /* Ok, time to create a new SIP dialog object, a pvt */
         if ((p = sip_alloc(callid, sin, 1, intended_method, req)))  {
            /* Ok, we've created a dialog, let's go and process it */
            sip_pvt_lock(p);
         } else {
            /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
               getting a dialog from sip_alloc. 
   
               Without a dialog we can't retransmit and handle ACKs and all that, but at least
               send an error message.
   
               Sorry, we apologize for the inconvienience
            */
            transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
            ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
         }
      }
      return p; /* can be NULL */
   } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
      /* A method we do not support, let's take it on the volley */
      transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
      ast_debug(2, "Got a request with unsupported SIP method.\n");
   } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
      /* This is a request outside of a dialog that we don't know about */
      transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
      ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
   }
   /* We do not respond to responses for dialogs that we don't know about, we just drop
      the session quickly */
   if (intended_method == SIP_RESPONSE)
      ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");

   return NULL;
}
static int find_call_cb ( void *  __pvt,
void *  __arg,
int  flags 
) [static]

code to determine whether this is the pvt that we are looking for. Return FALSE if not found, true otherwise. p is unlocked.

Definition at line 7729 of file chan_sip.c.

References ast_debug, ast_strlen_zero(), ast_test_flag, find_call_cb_arg::callid, sip_pvt::callid, FALSE, sip_pvt::flags, find_call_cb_arg::method, sip_settings::pedanticsipchecking, sip_cfg, sip_methods, SIP_PAGE2_DIALOG_ESTABLISHED, SIP_REGISTER, SIP_RESPONSE, sip_pvt::tag, find_call_cb_arg::tag, cfsip_methods::text, sip_pvt::theirtag, and find_call_cb_arg::totag.

Referenced by find_call().

{
   struct sip_pvt *p = __pvt;
   struct find_call_cb_arg *arg = __arg;
   /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
   int found = FALSE;
   
   if (!ast_strlen_zero(p->callid)) { /* XXX double check, do we allow match on empty p->callid ? */
      if (arg->method == SIP_REGISTER)
         found = (!strcmp(p->callid, arg->callid));
      else {
         found = !strcmp(p->callid, arg->callid);
         if (sip_cfg.pedanticsipchecking && found) {
            found = ast_strlen_zero(arg->tag) || ast_strlen_zero(p->theirtag) || !ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED) || !strcmp(p->theirtag, arg->tag);
         } 
      }
      
      ast_debug(5, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
      
      /* If we get a new request within an existing to-tag - check the to tag as well */
      if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) { /* SIP Request */
         if (p->tag[0] == '\0' && arg->totag[0]) {
            /* We have no to tag, but they have. Wrong dialog */
            found = FALSE;
         } else if (arg->totag[0]) { /* Both have tags, compare them */
            if (strcmp(arg->totag, p->tag)) {
               found = FALSE; /* This is not our packet */
            }
         }
         if (!found)
            ast_debug(5, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, arg->totag, sip_methods[arg->method].text);
      }
   }
   return found;
}
static int find_calling_channel ( struct ast_channel c,
void *  data 
) [static]

Definition at line 11534 of file chan_sip.c.

References sip_pvt::context, ast_channel::context, sip_request::data, ast_channel::exten, sip_pvt::exten, IGNORE_CONTEXT, ast_channel::macroexten, sip_settings::notifycid, ast_channel::pbx, and sip_cfg.

Referenced by transmit_state_notify().

                                                                   {
   struct sip_pvt *p = data;

   return (c->pbx &&
         (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
         (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
}
static const char* find_closing_quote ( const char *  start,
const char *  lim 
) [static]

Locate closing quote in a string, skipping escaped quotes. optionally with a limit on the search. start must be past the first quote.

Definition at line 4516 of file chan_sip.c.

References s.

Referenced by get_in_brackets().

{
   char last_char = '\0';
   const char *s;
   for (s = start; *s && s != lim; last_char = *s++) {
      if (*s == '"' && last_char != '\\')
         break;
   }
   return s;
}
static struct sip_peer * find_peer ( const char *  peer,
struct sockaddr_in *  sin,
int  realtime,
int  which_objects,
int  devstate_only,
int  transport 
) [static, read]

Locate device by name or ip address.

Parameters:
which_objectsDefine which objects should be matched when doing a lookup by name. Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES. Note that this option is not used at all when doing a lookup by IP.

This is used on find matching device on name or ip/port. If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.

Note:
Avoid using this function in new functions if there is a way to avoid it, since it might cause a database lookup.

Definition at line 5160 of file chan_sip.c.

References sip_peer::addr, ao2_t_callback_data, ao2_t_find, ast_copy_string(), ast_set_flag, find_by_name(), FINDALLDEVICES, FINDPEERS, FINDUSERS, ast_flags::flags, sip_peer::flags, sip_peer::name, OBJ_POINTER, realtime_peer(), SIP_INSECURE_PORT, SIP_TYPE_PEER, SIP_TYPE_USER, sip_peer::transports, sip_peer::type, and unref_peer().

Referenced by _sip_qualify_peer(), _sip_show_peer(), check_peer_ok(), create_addr(), function_sippeer(), register_verify(), sip_devicestate(), sip_do_debug_peer(), sip_peer_hold(), sip_show_user(), sip_unregister(), st_get_mode(), st_get_refresher(), st_get_se(), transmit_register(), and update_call_counter().

{
   struct sip_peer *p = NULL;
   struct sip_peer tmp_peer;

   if (peer) {
      ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
      p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
   } else if (sin) { /* search by addr? */
      tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
      tmp_peer.addr.sin_port = sin->sin_port;
      tmp_peer.flags[0].flags = 0;
      tmp_peer.transports = transport;
      p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table"); /* WAS:  p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
      if (!p) {
         ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
         p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2"); /* WAS:  p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
         if (p) {
            return p;
         }
      }
   }

   if (!p && (realtime || devstate_only)) {
      p = realtime_peer(peer, sin, devstate_only);
      if (p) {
         switch (which_objects) {
         case FINDUSERS:
            if (!(p->type & SIP_TYPE_USER)) {
               unref_peer(p, "Wrong type of realtime SIP endpoint");
               return NULL;
            }
            break;
         case FINDPEERS:
            if (!(p->type & SIP_TYPE_PEER)) {
               unref_peer(p, "Wrong type of realtime SIP endpoint");
               return NULL;
            }
            break;
         case FINDALLDEVICES:
            break;
         }
      }
   }

   return p;
}
static struct sip_auth * find_realm_authentication ( struct sip_auth authlist,
const char *  realm 
) [static, read]

Find authentication for a specific realm.

Definition at line 24238 of file chan_sip.c.

References sip_auth::next, and sip_auth::realm.

Referenced by build_reply_digest().

{
   struct sip_auth *a;

   for (a = authlist; a; a = a->next) {
      if (!strcasecmp(a->realm, realm))
         break;
   }

   return a;
}
static int find_sdp ( struct sip_request req) [static]

Determine whether a SIP message contains an SDP in its body.

Parameters:
reqthe SIP request to process
Returns:
1 if SDP found, 0 if not found

Also updates req->sdp_start and req->sdp_count to indicate where the SDP lives in the message body.

Definition at line 8306 of file chan_sip.c.

References ast_log(), ast_strdupa, ast_strlen_zero(), FALSE, get_header(), sip_request::lines, LOG_WARNING, REQ_OFFSET_TO_STR, sip_request::sdp_count, sip_request::sdp_start, strcasestr(), and TRUE.

Referenced by handle_incoming(), handle_request_invite(), handle_response(), and handle_response_invite().

{
   const char *content_type;
   const char *content_length;
   const char *search;
   char *boundary;
   unsigned int x;
   int boundaryisquoted = FALSE;
   int found_application_sdp = FALSE;
   int found_end_of_headers = FALSE;

   content_length = get_header(req, "Content-Length");

   if (!ast_strlen_zero(content_length)) {
      if (sscanf(content_length, "%30u", &x) != 1) {
         ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
         return 0;
      }

      /* Content-Length of zero means there can't possibly be an
         SDP here, even if the Content-Type says there is */
      if (x == 0)
         return 0;
   }

   content_type = get_header(req, "Content-Type");

   /* if the body contains only SDP, this is easy */
   if (!strncasecmp(content_type, "application/sdp", 15)) {
      req->sdp_start = 0;
      req->sdp_count = req->lines;
      return req->lines ? 1 : 0;
   }

   /* if it's not multipart/mixed, there cannot be an SDP */
   if (strncasecmp(content_type, "multipart/mixed", 15))
      return 0;

   /* if there is no boundary marker, it's invalid */
   if ((search = strcasestr(content_type, ";boundary=")))
      search += 10;
   else if ((search = strcasestr(content_type, "; boundary=")))
      search += 11;
   else
      return 0;

   if (ast_strlen_zero(search))
      return 0;

   /* If the boundary is quoted with ", remove quote */
   if (*search == '\"')  {
      search++;
      boundaryisquoted = TRUE;
   }

   /* make a duplicate of the string, with two extra characters
      at the beginning */
   boundary = ast_strdupa(search - 2);
   boundary[0] = boundary[1] = '-';
   /* Remove final quote */
   if (boundaryisquoted)
      boundary[strlen(boundary) - 1] = '\0';

   /* search for the boundary marker, the empty line delimiting headers from
      sdp part and the end boundry if it exists */

   for (x = 0; x < (req->lines); x++) {
      char *line = REQ_OFFSET_TO_STR(req, line[x]);
      if (!strncasecmp(line, boundary, strlen(boundary))){
         if (found_application_sdp && found_end_of_headers) {
            req->sdp_count = (x - 1) - req->sdp_start;
            return 1;
         }
         found_application_sdp = FALSE;
      }
      if (!strcasecmp(line, "Content-Type: application/sdp"))
         found_application_sdp = TRUE;
      
      if (ast_strlen_zero(line)) {
         if (found_application_sdp && !found_end_of_headers){
            req->sdp_start = x;
            found_end_of_headers = TRUE;
         }
      }
   }
   if (found_application_sdp && found_end_of_headers) {
      req->sdp_count = x - req->sdp_start;
      return TRUE;
   }
   return FALSE;
}
static int find_sip_method ( const char *  msg) [static]

find_sip_method: Find SIP method from header

Definition at line 3532 of file chan_sip.c.

References ARRAY_LEN, ast_strlen_zero(), method_match(), and sip_methods.

Referenced by __sip_pretend_ack(), handle_request_do(), handle_response(), and sip_hangup().

{
   int i, res = 0;
   
   if (ast_strlen_zero(msg))
      return 0;
   for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
      if (method_match(i, msg))
         res = sip_methods[i].id;
   }
   return res;
}
static struct cfsubscription_types * find_subscription_type ( enum subscriptiontype  subtype) [static, read]

Find subscription type in array.

Definition at line 16741 of file chan_sip.c.

References ARRAY_LEN, and subscription_types.

Referenced by transmit_state_notify().

{
   int i;

   for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
      if (subscription_types[i].type == subtype) {
         return &subscription_types[i];
      }
   }
   return &subscription_types[0];
}
static void free_old_route ( struct sip_route route) [static]

Remove route from route list.

Definition at line 12956 of file chan_sip.c.

References ast_free, sip_route::next, and sip_request::next.

Referenced by __sip_destroy(), and build_route().

{
   struct sip_route *next;

   while (route) {
      next = route->next;
      ast_free(route);
      route = next;
   }
}
static void free_via ( struct sip_via v) [static]

Definition at line 7545 of file chan_sip.c.

References ast_free, and sip_via::via.

Referenced by parse_via(), and process_via().

{
   if (!v) {
      return;
   }

   if (v->via) {
      ast_free(v->via);
   }

   ast_free(v);
}
static int func_check_sipdomain ( struct ast_channel chan,
const char *  cmd,
char *  data,
char *  buf,
size_t  len 
) [static]

Dial plan function to check if domain is local.

Definition at line 17827 of file chan_sip.c.

References ast_copy_string(), ast_log(), ast_strlen_zero(), check_sip_domain(), and LOG_WARNING.

{
   if (ast_strlen_zero(data)) {
      ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
      return -1;
   }
   if (check_sip_domain(data, NULL, 0))
      ast_copy_string(buf, data, len);
   else
      buf[0] = '\0';
   return 0;
}
static int func_header_read ( struct ast_channel chan,
const char *  function,
char *  data,
char *  buf,
size_t  len 
) [static]

Read SIP header (dialplan function)

Definition at line 17768 of file chan_sip.c.

References __get_header(), AST_APP_ARG, ast_channel_lock, ast_channel_unlock, ast_copy_string(), AST_DECLARE_APP_ARGS, ast_log(), AST_STANDARD_APP_ARGS, ast_strlen_zero(), sip_request::content, sip_request::header, sip_pvt::initreq, IS_SIP_TECH, LOG_WARNING, ast_channel::tech, and ast_channel::tech_pvt.

{
   struct sip_pvt *p;
   const char *content = NULL;
   AST_DECLARE_APP_ARGS(args,
      AST_APP_ARG(header);
      AST_APP_ARG(number);
   );
   int i, number, start = 0;

   if (ast_strlen_zero(data)) {
      ast_log(LOG_WARNING, "This function requires a header name.\n");
      return -1;
   }

   ast_channel_lock(chan);
   if (!IS_SIP_TECH(chan->tech)) {
      ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
      ast_channel_unlock(chan);
      return -1;
   }

   AST_STANDARD_APP_ARGS(args, data);
   if (!args.number) {
      number = 1;
   } else {
      sscanf(args.number, "%30d", &number);
      if (number < 1)
         number = 1;
   }

   p = chan->tech_pvt;

   /* If there is no private structure, this channel is no longer alive */
   if (!p) {
      ast_channel_unlock(chan);
      return -1;
   }

   for (i = 0; i < number; i++)
      content = __get_header(&p->initreq, args.header, &start);

   if (ast_strlen_zero(content)) {
      ast_channel_unlock(chan);
      return -1;
   }

   ast_copy_string(buf, content, len);
   ast_channel_unlock(chan);

   return 0;
}
static int function_sipchaninfo_read ( struct ast_channel chan,
const char *  cmd,
char *  data,
char *  buf,
size_t  len 
) [static]

${SIPCHANINFO()} Dialplan function - reads sip channel data

Definition at line 17941 of file chan_sip.c.

References ast_channel_lock, ast_channel_unlock, ast_copy_string(), ast_inet_ntoa(), ast_log(), sip_pvt::from, IS_SIP_TECH, LOG_WARNING, sip_pvt::peername, sip_pvt::recv, sip_pvt::sa, t38properties::state, sip_pvt::t38, T38_DISABLED, ast_channel::tech, ast_channel::tech_pvt, sip_pvt::uri, and sip_pvt::useragent.

{
   struct sip_pvt *p;
   static int deprecated = 0;

   *buf = 0;
   
   if (!data) {
      ast_log(LOG_WARNING, "This function requires a parameter name.\n");
      return -1;
   }

   ast_channel_lock(chan);
   if (!IS_SIP_TECH(chan->tech)) {
      ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
      ast_channel_unlock(chan);
      return -1;
   }

   if (deprecated++ % 20 == 0) {
      /* Deprecated in 1.6.1 */
      ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
   }

   p = chan->tech_pvt;

   /* If there is no private structure, this channel is no longer alive */
   if (!p) {
      ast_channel_unlock(chan);
      return -1;
   }

   if (!strcasecmp(data, "peerip")) {
      ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
   } else  if (!strcasecmp(data, "recvip")) {
      ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
   } else  if (!strcasecmp(data, "from")) {
      ast_copy_string(buf, p->from, len);
   } else  if (!strcasecmp(data, "uri")) {
      ast_copy_string(buf, p->uri, len);
   } else  if (!strcasecmp(data, "useragent")) {
      ast_copy_string(buf, p->useragent, len);
   } else  if (!strcasecmp(data, "peername")) {
      ast_copy_string(buf, p->peername, len);
   } else if (!strcasecmp(data, "t38passthrough")) {
      if (p->t38.state == T38_DISABLED) {
         ast_copy_string(buf, "0", len);
      } else { /* T38 is offered or enabled in this call */
         ast_copy_string(buf, "1", len);
      }
   } else {
      ast_channel_unlock(chan);
      return -1;
   }
   ast_channel_unlock(chan);

   return 0;
}
static int function_sippeer ( struct ast_channel chan,
const char *  cmd,
char *  data,
char *  buf,
size_t  len 
) [static]

${SIPPEER()} Dialplan function - reads peer data

Todo:
Will be deprecated after 1.4

Definition at line 17846 of file chan_sip.c.

References sip_peer::accountcode, sip_peer::addr, ast_codec_pref_index(), ast_copy_string(), ast_getformatname(), ast_getformatname_multiple(), ast_inet_ntoa(), ast_log(), ast_print_group(), ast_str_alloca, sip_peer::busy_level, sip_peer::call_limit, sip_peer::callgroup, sip_peer::capability, chanvar, sip_peer::chanvars, sip_peer::cid_name, sip_peer::cid_num, sip_peer::context, sip_peer::expire, FALSE, find_peer(), FINDPEERS, sip_peer::host_dynamic, sip_peer::inUse, sip_peer::language, LOG_WARNING, ast_variable::name, ast_variable::next, peer_mailboxes_to_str(), peer_status(), sip_peer::pickupgroup, sip_peer::prefs, sip_peer::regexten, strsep(), TRUE, unref_peer(), sip_peer::useragent, and ast_variable::value.

{
   struct sip_peer *peer;
   char *colname;

   if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
      static int deprecation_warning = 0;
      *colname++ = '\0';
      if (deprecation_warning++ % 10 == 0)
         ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
   } else if ((colname = strchr(data, ',')))
      *colname++ = '\0';
   else
      colname = "ip";

   if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
      return -1;

   if (!strcasecmp(colname, "ip")) {
      ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
   } else  if (!strcasecmp(colname, "port")) {
      snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
   } else  if (!strcasecmp(colname, "status")) {
      peer_status(peer, buf, len);
   } else  if (!strcasecmp(colname, "language")) {
      ast_copy_string(buf, peer->language, len);
   } else  if (!strcasecmp(colname, "regexten")) {
      ast_copy_string(buf, peer->regexten, len);
   } else  if (!strcasecmp(colname, "limit")) {
      snprintf(buf, len, "%d", peer->call_limit);
   } else  if (!strcasecmp(colname, "busylevel")) {
      snprintf(buf, len, "%d", peer->busy_level);
   } else  if (!strcasecmp(colname, "curcalls")) {
      snprintf(buf, len, "%d", peer->inUse);
   } else  if (!strcasecmp(colname, "accountcode")) {
      ast_copy_string(buf, peer->accountcode, len);
   } else  if (!strcasecmp(colname, "callgroup")) {
      ast_print_group(buf, len, peer->callgroup);
   } else  if (!strcasecmp(colname, "pickupgroup")) {
      ast_print_group(buf, len, peer->pickupgroup);
   } else  if (!strcasecmp(colname, "useragent")) {
      ast_copy_string(buf, peer->useragent, len);
   } else  if (!strcasecmp(colname, "mailbox")) {
      struct ast_str *mailbox_str = ast_str_alloca(512);
      peer_mailboxes_to_str(&mailbox_str, peer);
      ast_copy_string(buf, mailbox_str->str, len);
   } else  if (!strcasecmp(colname, "context")) {
      ast_copy_string(buf, peer->context, len);
   } else  if (!strcasecmp(colname, "expire")) {
      snprintf(buf, len, "%d", peer->expire);
   } else  if (!strcasecmp(colname, "dynamic")) {
      ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
   } else  if (!strcasecmp(colname, "callerid_name")) {
      ast_copy_string(buf, peer->cid_name, len);
   } else  if (!strcasecmp(colname, "callerid_num")) {
      ast_copy_string(buf, peer->cid_num, len);
   } else  if (!strcasecmp(colname, "codecs")) {
      ast_getformatname_multiple(buf, len -1, peer->capability);
   } else  if (!strncasecmp(colname, "chanvar[", 8)) {
      char *chanvar=colname + 8;
      struct ast_variable *v;
   
      chanvar = strsep(&chanvar, "]");
      for (v = peer->chanvars ; v ; v = v->next) {
         if (!strcasecmp(v->name, chanvar)) {
            ast_copy_string(buf, v->value, len);
         }
      }
   } else  if (!strncasecmp(colname, "codec[", 6)) {
      char *codecnum;
      int codec = 0;
      
      codecnum = colname + 6; /* move past the '[' */
      codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
      if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
         ast_copy_string(buf, ast_getformatname(codec), len);
      } else {
         buf[0] = '\0';
      }
   } else {
      buf[0] = '\0';
   }

   unref_peer(peer, "unref_peer from function_sippeer, just before return");

   return 0;
}
static char * generate_random_string ( char *  buf,
size_t  size 
) [static]

Generate 32 byte random string for callid's etc.

Definition at line 7333 of file chan_sip.c.

References ast_random(), and buf.

Referenced by build_callid_pvt(), and build_callid_registry().

{
   long val[4];
   int x;

   for (x=0; x<4; x++)
      val[x] = ast_random();
   snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);

   return buf;
}
static int get_also_info ( struct sip_pvt p,
struct sip_request oreq 
) [static]

Call transfer support (old way, deprecated by the IETF)

Note:
does not account for SIPS: uri requirements, nor check transport

Definition at line 14250 of file chan_sip.c.

References ast_canmatch_extension(), ast_copy_string(), ast_debug, ast_exists_extension(), ast_log(), ast_string_field_set, ast_strlen_zero(), ast_uri_decode(), ast_verbose(), context, sip_pvt::context, sip_settings::default_context, dialog_unref(), get_header(), get_in_brackets(), sip_pvt::initreq, LOG_WARNING, ast_channel::macrocontext, sip_pvt::owner, pbx_builtin_getvar_helper(), sip_settings::pedanticsipchecking, sip_pvt::refer, sip_refer::refer_call, sip_refer::refer_contact, sip_refer::refer_to, sip_refer::refer_to_domain, sip_refer::referred_by, S_OR, sip_cfg, sip_debug_test_pvt(), and sip_refer_allocate().

Referenced by handle_request_bye().

{
   char tmp[256] = "", *c, *a;
   struct sip_request *req = oreq ? oreq : &p->initreq;
   struct sip_refer *referdata = NULL;
   const char *transfer_context = NULL;
   
   if (!p->refer && !sip_refer_allocate(p))
      return -1;

   referdata = p->refer;

   ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
   c = get_in_brackets(tmp);

   if (sip_cfg.pedanticsipchecking)
      ast_uri_decode(c);

   if (!strncasecmp(c, "sip:", 4)) {
      c += 4;
   } else if (!strncasecmp(c, "sips:", 5)) {
      c += 5;
   } else {
      ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
      return -1;
   }

   if ((a = strchr(c, ';')))  /* Remove arguments */
      *a = '\0';
   
   if ((a = strchr(c, '@'))) {   /* Separate Domain */
      *a++ = '\0';
      ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
   }
   
   if (sip_debug_test_pvt(p))
      ast_verbose("Looking for %s in %s\n", c, p->context);

   if (p->owner)  /* Mimic behaviour in res_features.c */
      transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");

   /* By default, use the context in the channel sending the REFER */
   if (ast_strlen_zero(transfer_context)) {
      transfer_context = S_OR(p->owner->macrocontext,
               S_OR(p->context, sip_cfg.default_context));
   }
   if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
      /* This is a blind transfer */
      ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
      ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
      ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
      ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
      referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
      /* Set new context */
      ast_string_field_set(p, context, transfer_context);
      return 0;
   } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
      return 1;
   }

   return -1;
}
static char* get_body ( struct sip_request req,
char *  name,
char  delimiter 
) [static]

Get a specific line from the message body.

Definition at line 7100 of file chan_sip.c.

References get_body_by_line(), sip_request::lines, and REQ_OFFSET_TO_STR.

Referenced by handle_request_info(), and handle_request_notify().

{
   int x;
   int len = strlen(name);
   char *r;

   for (x = 0; x < req->lines; x++) {
      r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
      if (r[0] != '\0')
         return r;
   }

   return "";
}
static char* get_body_by_line ( const char *  line,
const char *  name,
int  nameLen,
char  delimiter 
) [static]

Reads one line of SIP message body.

Definition at line 7045 of file chan_sip.c.

References ast_skip_blanks().

Referenced by get_body(), and get_sdp_iterate().

{
   if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
      return ast_skip_blanks(line + nameLen + 1);

   return "";
}
static int get_cached_mwi ( struct sip_peer peer,
int *  new,
int *  old 
) [static]
static char * get_calleridname ( const char *  input,
char *  output,
size_t  outputsize 
) [static]

Get caller id name from SIP headers.

Definition at line 14416 of file chan_sip.c.

References ast_copy_string(), and ast_skip_blanks().

Referenced by check_user_full().

{
   const char *end = strchr(input, '<');  /* first_bracket */
   const char *tmp = strchr(input, '"');  /* first quote */
   int bytes = 0;
   int maxbytes = outputsize - 1;

   if (!end || end == input)  /* we require a part in brackets */
      return NULL;

   end--; /* move just before "<" */

   if (tmp && tmp <= end) {
      /* The quote (tmp) precedes the bracket (end+1).
       * Find the matching quote and return the content.
       */
      end = strchr(tmp+1, '"');
      if (!end)
         return NULL;
      bytes = (int) (end - tmp);
      /* protect the output buffer */
      if (bytes > maxbytes)
         bytes = maxbytes;
      ast_copy_string(output, tmp + 1, bytes);
   } else {
      /* No quoted string, or it is inside brackets. */
      /* clear the empty characters in the begining*/
      input = ast_skip_blanks(input);
      /* clear the empty characters in the end */
      while(*end && *end < 33 && end > input)
         end--;
      if (end >= input) {
         bytes = (int) (end - input) + 2;
         /* protect the output buffer */
         if (bytes > maxbytes)
            bytes = maxbytes;
         ast_copy_string(output, input, bytes);
      } else
         return NULL;
   }
   return output;
}
static int get_destination ( struct sip_pvt p,
struct sip_request oreq 
) [static]

Find out who the call is for. We use the request uri as a destination. This code assumes authentication has been done, so that the device (peer/user) context is already set.

Returns:
0 on success (found a matching extension), 1 for pickup extension or overlap dialling support (if we support it), -1 on error.
Note:
If the incoming uri is a SIPS: uri, we are required to carry this across the dialplan, so that the outbound call also is a sips: call or encrypted IAX2 call. If that's not available, the call should FAIL.

Definition at line 13830 of file chan_sip.c.

References sip_settings::allow_external_domains, ast_canmatch_extension(), ast_copy_string(), ast_debug, ast_exists_extension(), ast_get_hint(), AST_LIST_EMPTY, ast_log(), AST_MAX_EXTENSION, ast_pickup_ext(), ast_strdupa, ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_uri_decode(), ast_verbose(), check_sip_domain(), sip_pvt::cid_num, sip_pvt::context, context, sip_pvt::domain, exten, sip_pvt::flags, get_header(), get_in_brackets(), sip_pvt::initreq, LOG_WARNING, sip_request::method, sip_settings::pedanticsipchecking, REQ_OFFSET_TO_STR, sip_request::rlPart2, S_OR, sip_cfg, sip_debug_test_pvt(), SIP_INVITE, sip_methods, SIP_PAGE2_ALLOWOVERLAP, SIP_PAGE2_HAVEPEERCONTEXT, SIP_REFER, SIP_SUBSCRIBE, strsep(), sip_pvt::subscribecontext, and cfsip_methods::text.

Referenced by handle_request_invite(), handle_request_options(), and handle_request_subscribe().

{
   char tmp[256] = "", *uri, *a;
   char tmpf[256] = "", *from = NULL;
   struct sip_request *req;
   char *colon;
   char *decoded_uri;
   
   req = oreq;
   if (!req)
      req = &p->initreq;

   /* Find the request URI */
   if (req->rlPart2)
      ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
   
   if (sip_cfg.pedanticsipchecking)
      ast_uri_decode(tmp);

   uri = get_in_brackets(tmp);
   
   if (!strncasecmp(uri, "sip:", 4)) {
      uri += 4;
   } else if (!strncasecmp(uri, "sips:", 5)) {
      uri += 5;
   } else {
      ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
      return -1;
   }

   /* Now find the From: caller ID and name */
   /* XXX Why is this done in get_destination? Isn't it already done?
      Needs to be checked 
        */
   ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
   if (!ast_strlen_zero(tmpf)) {
      if (sip_cfg.pedanticsipchecking)
         ast_uri_decode(tmpf);
      from = get_in_brackets(tmpf);
   } 
   
   if (!ast_strlen_zero(from)) {
      if (!strncasecmp(from, "sip:", 4)) {
         from += 4;
      } else if (!strncasecmp(from, "sips:", 5)) {
         from += 5;
      } else {
         ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
         return -1;
      }
      if ((a = strchr(from, '@')))
         *a++ = '\0';
      else
         a = from;   /* just a domain */
      from = strsep(&from, ";"); /* Remove userinfo options */
      a = strsep(&a, ";");    /* Remove URI options */
      ast_string_field_set(p, fromdomain, a);
   }

   /* Skip any options and find the domain */

   /* Get the target domain */
   if ((a = strchr(uri, '@'))) {
      *a++ = '\0';
   } else { /* No username part */
      a = uri;
      uri = "s";  /* Set extension to "s" */
   }
   colon = strchr(a, ':'); /* Remove :port */
   if (colon)
      *colon = '\0';

   uri = strsep(&uri, ";");   /* Remove userinfo options */
   a = strsep(&a, ";");    /* Remove URI options */

   ast_string_field_set(p, domain, a);

   if (!AST_LIST_EMPTY(&domain_list)) {
      char domain_context[AST_MAX_EXTENSION];

      domain_context[0] = '\0';
      if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
         if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
            ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
            return -2;
         }
      }
      /* If we don't have a peer (i.e. we're a guest call),
       * overwrite the original context */
      if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
         ast_string_field_set(p, context, domain_context);
   }

   /* If the request coming in is a subscription and subscribecontext has been specified use it */
   if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
      ast_string_field_set(p, context, p->subscribecontext);

   if (sip_debug_test_pvt(p))
      ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);

   /* Since extensions.conf can have unescaped characters, try matching a
    * decoded uri in addition to the non-decoded uri. */
   decoded_uri = ast_strdupa(uri);
   ast_uri_decode(decoded_uri);

   /* If this is a subscription we actually just need to see if a hint exists for the extension */
   if (req->method == SIP_SUBSCRIBE) {
      char hint[AST_MAX_EXTENSION];
      int which = 0;
      if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
          (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
         if (!oreq) {
            ast_string_field_set(p, exten, which ? decoded_uri : uri);
         }
         return 0;
      } else {
         return -1;
      }
   } else {
      int which = 0;
      /* Check the dialplan for the username part of the request URI,
         the domain will be stored in the SIPDOMAIN variable
         Return 0 if we have a matching extension */
      if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) ||
          (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) && (which = 1)) ||
          !strcmp(decoded_uri, ast_pickup_ext())) {
         if (!oreq) {
            ast_string_field_set(p, exten, which ? decoded_uri : uri);
         }
         return 0;
      }
   }

   /* Return 1 for pickup extension or overlap dialling support (if we support it) */
   if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) && 
       ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
       !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
      return 1;
   }
   
   return -1;
}
static char * get_in_brackets ( char *  tmp) [static]

Pick out text in brackets from character string.

Returns:
pointer to terminated stripped string
Parameters:
tmpinput string that will be modified Examples:

	"foo" <bar>	valid input, returns bar
	foo		returns the whole string
	< "foo ... >	returns the string between brackets
	< "foo...	bogus (missing closing bracket), returns the whole string
			XXX maybe should still skip the opening bracket

Definition at line 4539 of file chan_sip.c.

References ast_log(), find_closing_quote(), LOG_WARNING, and parse().

Referenced by check_user_full(), extract_uri(), get_also_info(), get_destination(), get_rdnis(), get_refer_info(), parse_moved_contact(), parse_ok_contact(), parse_register_contact(), register_verify(), reqprep(), transmit_refer(), and transmit_state_notify().

{
   const char *parse = tmp;
   char *first_bracket;

   /*
    * Skip any quoted text until we find the part in brackets.
   * On any error give up and return the full string.
   */
   while ( (first_bracket = strchr(parse, '<')) ) {
      char *first_quote = strchr(parse, '"');

      if (!first_quote || first_quote > first_bracket)
         break; /* no need to look at quoted part */
      /* the bracket is within quotes, so ignore it */
      parse = find_closing_quote(first_quote + 1, NULL);
      if (!*parse) { /* not found, return full string ? */
         /* XXX or be robust and return in-bracket part ? */
         ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
         break;
      }
      parse++;
   }
   if (first_bracket) {
      char *second_bracket = strchr(first_bracket + 1, '>');
      if (second_bracket) {
         *second_bracket = '\0';
         tmp = first_bracket + 1;
      } else {
         ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
      }
   }
   
   return tmp;
}
static struct ast_variable * get_insecure_variable_from_config ( struct ast_config config) [static, read]

Definition at line 4911 of file chan_sip.c.

References ast_category_browse(), ast_category_root(), ast_test_flag, ast_variable_retrieve(), set_insecure_flags(), SIP_INSECURE_PORT, and var.

Referenced by realtime_peer().

{
   struct ast_variable *var = NULL;
   struct ast_flags flags = {0};
   char *cat = NULL;
   const char *insecure;
   while ((cat = ast_category_browse(cfg, cat))) {
      insecure = ast_variable_retrieve(cfg, cat, "insecure");
      set_insecure_flags(&flags, insecure, -1);
      if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
         var = ast_category_root(cfg, cat);
         break;
      }
   }
   return var;
}
static int get_ip_and_port_from_sdp ( struct sip_request req,
const enum media_type  media,
struct sockaddr_in *  sin 
) [static]

Definition at line 8434 of file chan_sip.c.

References ast_gethostbyname(), ast_log(), ast_strlen_zero(), get_sdp_iterate(), hp, sip_request::len, LOG_WARNING, SDP_AUDIO, sip_request::sdp_start, and SDP_VIDEO.

Referenced by handle_request_invite().

{
   const char *m;
   const char *c;
   int miterator = req->sdp_start;
   int citerator = req->sdp_start;
   int x = 0;
   int numberofports;
   int len;
   char host[258] = ""; /*Initialize to empty so we will know if we have any input */
   struct ast_hostent audiohp;
   struct hostent *hp;

   c = get_sdp_iterate(&citerator, req, "c");
   if (sscanf(c, "IN IP4 %256s", host) != 1) {
      ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
      /* Continue since there may be a valid host in a c= line specific to the audio stream */
   }
   /* We only want the m and c lines for audio */
   for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
      if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
          (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
         (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
          (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
         /* See if there's a c= line for this media stream.
          * XXX There is no guarantee that we'll be grabbing the c= line for this
          * particular media stream here. However, this is the same logic used in process_sdp.
          */
         c = get_sdp_iterate(&citerator, req, "c");
         if (!ast_strlen_zero(c)) {
            sscanf(c, "IN IP4 %256s", host);
         }
         break;
      }
   }

   if (ast_strlen_zero(host) || x == 0) {
      ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
      return -1;
   }

   hp = ast_gethostbyname(host, &audiohp);
   if (!hp) {
      ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
      return -1;
   }

   memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
   sin->sin_port = htons(x);
   return 0;
}
static int get_msg_text ( char *  buf,
int  len,
struct sip_request req,
int  addnewline 
) [static]

Get text out of a SIP MESSAGE packet.

Definition at line 14793 of file chan_sip.c.

References sip_request::lines, and REQ_OFFSET_TO_STR.

Referenced by handle_request_info(), handle_request_notify(), and receive_message().

{
   int x;
   int y;

   buf[0] = '\0';
   /*XXX isn't strlen(buf) going to always be 0? */
   y = len - strlen(buf) - 5;
   if (y < 0)
      y = 0;
   for (x = 0; x < req->lines; x++) {
      char *line = REQ_OFFSET_TO_STR(req, line[x]);
      strncat(buf, line, y); /* safe */
      y -= strlen(line) + 1;
      if (y < 0)
         y = 0;
      if (y != 0 && addnewline)
         strcat(buf, "\n"); /* safe */
   }
   return 0;
}
static const char * get_name_from_variable ( struct ast_variable var,
const char *  newpeername 
) [static]

Definition at line 4928 of file chan_sip.c.

References ast_variable::name, ast_variable::next, and ast_variable::value.

Referenced by realtime_peer().

{
   struct ast_variable *tmp;
   for (tmp = var; tmp; tmp = tmp->next) {
      if (!newpeername && !strcasecmp(tmp->name, "name"))
         newpeername = tmp->value;
   }
   return newpeername;
}
static void get_our_media_address ( struct sip_pvt p,
int  needvideo,
struct sockaddr_in *  sin,
struct sockaddr_in *  vsin,
struct sockaddr_in *  tsin,
struct sockaddr_in *  dest,
struct sockaddr_in *  vdest 
) [static]

Set all IP media addresses for this call.

Note:
called from add_sdp()

Definition at line 10475 of file chan_sip.c.

References ast_rtp_get_us(), sip_pvt::ourip, sip_pvt::redirip, sip_pvt::rtp, sip_pvt::trtp, sip_pvt::vredirip, and sip_pvt::vrtp.

Referenced by add_sdp().

{
   /* First, get our address */
   ast_rtp_get_us(p->rtp, sin);
   if (p->vrtp)
      ast_rtp_get_us(p->vrtp, vsin);
   if (p->trtp)
      ast_rtp_get_us(p->trtp, tsin);

   /* Now, try to figure out where we want them to send data */
   /* Is this a re-invite to move the media out, then use the original offer from caller  */
   if (p->redirip.sin_addr.s_addr) {   /* If we have a redirection IP, use it */
      dest->sin_port = p->redirip.sin_port;
      dest->sin_addr = p->redirip.sin_addr;
   } else {
      dest->sin_addr = p->ourip.sin_addr;
      dest->sin_port = sin->sin_port;
   }
   if (needvideo) {
      /* Determine video destination */
      if (p->vredirip.sin_addr.s_addr) {
         vdest->sin_addr = p->vredirip.sin_addr;
         vdest->sin_port = p->vredirip.sin_port;
      } else {
         vdest->sin_addr = p->ourip.sin_addr;
         vdest->sin_port = vsin->sin_port;
      }
   }

}
static int get_rdnis ( struct sip_pvt p,
struct sip_request oreq 
) [static]

Get referring dnis.

Todo:
This function does not take user-parameters into consideration. First look for @, then start looking for ; to find uri-parameters.

Definition at line 13756 of file chan_sip.c.

References ast_copy_string(), ast_log(), ast_string_field_set, ast_strip_quoted(), ast_strlen_zero(), ast_verbose(), exten, get_header(), get_in_brackets(), sip_pvt::initreq, LOG_WARNING, sip_pvt::owner, pbx_builtin_setvar_helper(), sip_pvt::redircause, sip_debug_test_pvt(), sip_set_redirstr(), strcasestr(), and strsep().

Referenced by handle_request_invite().

{
   char tmp[256], *exten, *rexten, *rdomain;
   char *params, *reason = NULL;
   struct sip_request *req;
   
   req = oreq ? oreq : &p->initreq;

   ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
   if (ast_strlen_zero(tmp))
      return 0;

   /*! \todo This function does not take user-parameters into consideration.
      First look for @, then start looking for ; to find uri-parameters.
   */
   params = strchr(tmp, ';');

   exten = get_in_brackets(tmp);
   if (!strncasecmp(exten, "sip:", 4)) {
      exten += 4;
   } else if (!strncasecmp(exten, "sips:", 5)) {
      exten += 5;
   } else {
      ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
      return -1;
   }

   /* Get diversion-reason param if present */
   if (params) {
      *params = '\0';   /* Cut off parameters  */
      params++;
      while (*params == ';' || *params == ' ')
         params++;
      /* Check if we have a reason parameter */
      if ((reason = strcasestr(params, "reason="))) {
         reason+=7;
         /* Remove enclosing double-quotes */
         if (*reason == '"') 
            ast_strip_quoted(reason, "\"", "\"");
         if (!ast_strlen_zero(reason)) {
            sip_set_redirstr(p, reason);
            if (p->owner) {
               pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
               pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
            }
         }
      }
   }

   rdomain = exten;
   rexten = strsep(&rdomain, "@");  /* trim anything after @ */
   if (p->owner) 
      pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);

   if (sip_debug_test_pvt(p))
      ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");

   ast_string_field_set(p, rdnis, rexten);

   return 0;
}
static int get_refer_info ( struct sip_pvt transferer,
struct sip_request outgoing_req 
) [static]

Call transfer support (the REFER method) Extracts Refer headers into pvt dialog structure.

Note:
If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path to that extension. As a minimum, this needs to be added to a channel variable, if not a channel flag.

Definition at line 14064 of file chan_sip.c.

References ast_bridged_channel(), ast_copy_string(), ast_debug, ast_exists_extension(), ast_log(), ast_strdupa, ast_strlen_zero(), ast_uri_decode(), ast_verbose(), sip_refer::attendedtransfer, sip_pvt::callid, sip_pvt::context, sip_settings::default_context, get_header(), get_in_brackets(), sip_pvt::initreq, LOG_WARNING, ast_channel::macrocontext, sip_pvt::owner, pbx_builtin_getvar_helper(), pbx_builtin_setvar_helper(), sip_settings::pedanticsipchecking, sip_pvt::refer, sip_refer::refer_to, sip_refer::refer_to_context, sip_refer::refer_to_domain, sip_refer::refer_to_urioption, sip_refer::referred_by, sip_refer::referred_by_name, sip_refer::replaces_callid, sip_refer::replaces_callid_fromtag, sip_refer::replaces_callid_totag, S_OR, sip_cfg, sip_debug_test_pvt(), strcasestr(), sip_pvt::tag, and sip_pvt::theirtag.

Referenced by handle_request_refer().

{

   const char *p_referred_by = NULL;
   char *h_refer_to = NULL; 
   char *h_referred_by = NULL;
   char *refer_to;
   const char *p_refer_to;
   char *referred_by_uri = NULL;
   char *ptr;
   struct sip_request *req = NULL;
   const char *transfer_context = NULL;
   struct sip_refer *referdata;


   req = outgoing_req;
   referdata = transferer->refer;

   if (!req)
      req = &transferer->initreq;

   p_refer_to = get_header(req, "Refer-To");
   if (ast_strlen_zero(p_refer_to)) {
      ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
      return -2;  /* Syntax error */
   }
   h_refer_to = ast_strdupa(p_refer_to);
   refer_to = get_in_brackets(h_refer_to);
   if (sip_cfg.pedanticsipchecking)
      ast_uri_decode(refer_to);

   if (!strncasecmp(refer_to, "sip:", 4)) {
      refer_to += 4;       /* Skip sip: */
   } else if (!strncasecmp(refer_to, "sips:", 5)) {
      refer_to += 5;
   } else {
      ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
      return -3;
   }

   /* Get referred by header if it exists */
   p_referred_by = get_header(req, "Referred-By");

   /* Give useful transfer information to the dialplan */
   if (transferer->owner) {
      struct ast_channel *peer = ast_bridged_channel(transferer->owner);
      if (peer) {
         pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
         pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
      }
   }

   if (!ast_strlen_zero(p_referred_by)) {
      char *lessthan;
      h_referred_by = ast_strdupa(p_referred_by);
      if (sip_cfg.pedanticsipchecking)
         ast_uri_decode(h_referred_by);

      /* Store referrer's caller ID name */
      ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
      if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
         *(lessthan - 1) = '\0'; /* Space */
      }

      referred_by_uri = get_in_brackets(h_referred_by);
      if (!strncasecmp(referred_by_uri, "sip:", 4)) {
         referred_by_uri += 4;      /* Skip sip: */
      } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
         referred_by_uri += 5;      /* Skip sips: */
      } else {
         ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
         referred_by_uri = NULL;
      }
   }

   /* Check for arguments in the refer_to header */
   if ((ptr = strcasestr(refer_to, "replaces="))) {
      char *to = NULL, *from = NULL;
      
      /* This is an attended transfer */
      referdata->attendedtransfer = 1;
      ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
      ast_uri_decode(referdata->replaces_callid);
      if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
         *ptr++ = '\0';
      }
      
      if (ptr) {
         /* Find the different tags before we destroy the string */
         to = strcasestr(ptr, "to-tag=");
         from = strcasestr(ptr, "from-tag=");
      }
      
      /* Grab the to header */
      if (to) {
         ptr = to + 7;
         if ((to = strchr(ptr, '&')))
            *to = '\0';
         if ((to = strchr(ptr, ';')))
            *to = '\0';
         ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
      }
      
      if (from) {
         ptr = from + 9;
         if ((to = strchr(ptr, '&')))
            *to = '\0';
         if ((to = strchr(ptr, ';')))
            *to = '\0';
         ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
      }

      if (!strcmp(referdata->replaces_callid, transferer->callid) &&
         (!sip_cfg.pedanticsipchecking ||
         (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
         !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
            ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
            return -4;
      }

      if (!sip_cfg.pedanticsipchecking)
         ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
      else
         ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", referdata->replaces_callid, referdata->replaces_callid_fromtag ? referdata->replaces_callid_fromtag : "<none>", referdata->replaces_callid_totag ? referdata->replaces_callid_totag : "<none>" );
   }
   
   if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
      char *urioption = NULL, *domain;
      *ptr++ = '\0';

      if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
         *urioption++ = '\0';
      
      domain = ptr;
      if ((ptr = strchr(domain, ':'))) /* Remove :port */
         *ptr = '\0';
      
      /* Save the domain for the dial plan */
      ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
      if (urioption)
         ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
   }

   if ((ptr = strchr(refer_to, ';')))  /* Remove options */
      *ptr = '\0';
   ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
   
   if (referred_by_uri) {
      if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
         *ptr = '\0';
      ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
   } else {
      referdata->referred_by[0] = '\0';
   }

   /* Determine transfer context */
   if (transferer->owner)  /* Mimic behaviour in res_features.c */
      transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");

   /* By default, use the context in the channel sending the REFER */
   if (ast_strlen_zero(transfer_context)) {
      transfer_context = S_OR(transferer->owner->macrocontext,
               S_OR(transferer->context, sip_cfg.default_context));
   }

   ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
   
   /* Either an existing extension or the parking extension */
   if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
      if (sip_debug_test_pvt(transferer)) {
         ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
      }
      /* We are ready to transfer to the extension */
      return 0;
   } 
   if (sip_debug_test_pvt(transferer))
      ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);

   /* Failure, we can't find this extension */
   return -1;
}
static int get_rpid_num ( const char *  input,
char *  output,
int  maxlen 
) [static]

Get caller id number from Remote-Party-ID header field Returns true if number should be restricted (privacy setting found) output is set to NULL if no number found.

Definition at line 14463 of file chan_sip.c.

References ast_copy_string(), and AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED.

Referenced by check_user_full().

{
   char *start;
   char *end;

   start = strchr(input, ':');
   if (!start) {
      output[0] = '\0';
      return 0;
   }
   start++;

   /* we found "number" */
   ast_copy_string(output, start, maxlen);
   output[maxlen-1] = '\0';

   end = strchr(output, '@');
   if (end)
      *end = '\0';
   else
      output[0] = '\0';
   if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
      return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;

   return 0;
}
static const char * get_sdp_iterate ( int *  start,
struct sip_request req,
const char *  name 
) [static]

Lookup 'name' in the SDP starting at the 'start' line. Returns the matching line, and 'start' is updated with the next line number.

Definition at line 7057 of file chan_sip.c.

References get_body_by_line(), REQ_OFFSET_TO_STR, sip_request::sdp_count, and sip_request::sdp_start.

Referenced by get_ip_and_port_from_sdp(), and process_sdp().

{
   int len = strlen(name);

   while (*start < (req->sdp_start + req->sdp_count)) {
      const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
      if (r[0] != '\0')
         return r;
   }

   /* if the line was not found, ensure that *start points past the SDP */
   (*start)++;

   return "";
}
static char get_sdp_line ( int *  start,
int  stop,
struct sip_request req,
const char **  value 
) [static]

Fetches the next valid SDP line between the 'start' line (inclusive) and the 'stop' line (exclusive). Returns the type ('a', 'c', ...) and matching line in reference 'start' is updated with the next line number.

Definition at line 7078 of file chan_sip.c.

References ast_skip_blanks(), REQ_OFFSET_TO_STR, sip_request::sdp_count, sip_request::sdp_start, and type.

Referenced by process_sdp().

{
   char type = '\0';
   const char *line = NULL;

   if (stop > (req->sdp_start + req->sdp_count)) {
      stop = req->sdp_start + req->sdp_count;
   }

   while (*start < stop) {
      line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
      if (line[1] == '=') {
         type = line[0];
         *value = ast_skip_blanks(line + 2);
         break;
      }
   }

   return type;
}
static struct sip_pvt * get_sip_pvt_byid_locked ( const char *  callid,
const char *  totag,
const char *  fromtag 
) [static, read]

Lock dialog lock and find matching pvt lock.

Returns:
a reference, remember to release it when done

Definition at line 13976 of file chan_sip.c.

References ao2_t_find, ast_channel_trylock, ast_debug, ast_strlen_zero(), sip_pvt::callid, OBJ_POINTER, sip_pvt::outgoing_call, sip_pvt::owner, sip_settings::pedanticsipchecking, sip_cfg, sip_pvt_lock, sip_pvt_unlock, sip_pvt::tag, sip_pvt::theirtag, and TRUE.

Referenced by handle_request_invite(), and local_attended_transfer().

{
   struct sip_pvt *sip_pvt_ptr;
   struct sip_pvt tmp_dialog = {
      .callid = callid,
   };

   if (totag)
      ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");

   /* Search dialogs and find the match */
   
   sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
   if (sip_pvt_ptr) {
      /* Go ahead and lock it (and its owner) before returning */
      sip_pvt_lock(sip_pvt_ptr);
      if (sip_cfg.pedanticsipchecking) {
         unsigned char frommismatch = 0, tomismatch = 0;

         if (ast_strlen_zero(fromtag)) {
            sip_pvt_unlock(sip_pvt_ptr);
            ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
                 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
            return NULL;
         }

         if (ast_strlen_zero(totag)) {
            sip_pvt_unlock(sip_pvt_ptr);
            ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
                 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
            return NULL;
         }
         /* RFC 3891
          * > 3.  User Agent Server Behavior: Receiving a Replaces Header
          * > The Replaces header contains information used to match an existing
          * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
          * > with a Replaces header, the User Agent (UA) attempts to match this
          * > information with a confirmed or early dialog.  The User Agent Server
          * > (UAS) matches the to-tag and from-tag parameters as if they were tags
          * > present in an incoming request.  In other words, the to-tag parameter
          * > is compared to the local tag, and the from-tag parameter is compared
          * > to the remote tag.
          *
          * Thus, the totag is always compared to the local tag, regardless if
          * this our call is an incoming or outgoing call.
          */
         frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
         tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);

         if (frommismatch || tomismatch) {
            sip_pvt_unlock(sip_pvt_ptr);
            if (frommismatch) {
               ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
                    sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
                    fromtag, sip_pvt_ptr->theirtag);
            }
            if (tomismatch) {
               ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
                    sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
                    totag, sip_pvt_ptr->tag);
            }
            return NULL;
         }
      }
      
      if (totag)
         ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
                 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
                 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);

      /* deadlock avoidance... */
      while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
         sip_pvt_unlock(sip_pvt_ptr);
         usleep(1);
         sip_pvt_lock(sip_pvt_ptr);
      }
   }
   
   return sip_pvt_ptr;
}
static const char* get_srv_protocol ( enum sip_transport  t) [inline, static]

Return protocol string for srv dns query.

Definition at line 3693 of file chan_sip.c.

References SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, and SIP_TRANSPORT_UDP.

Referenced by __sip_subscribe_mwi_do(), build_peer(), create_addr(), and transmit_register().

{
   switch (t) {
   case SIP_TRANSPORT_UDP:
      return "udp";
   case SIP_TRANSPORT_TLS:
   case SIP_TRANSPORT_TCP:
      return "tcp";
   }

   return "udp";
}
static const char* get_srv_service ( enum sip_transport  t) [inline, static]

Return service string for srv dns query.

Definition at line 3707 of file chan_sip.c.

References SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, and SIP_TRANSPORT_UDP.

Referenced by __sip_subscribe_mwi_do(), build_peer(), create_addr(), and transmit_register().

{
   switch (t) {
   case SIP_TRANSPORT_TCP:
   case SIP_TRANSPORT_UDP:
      return "sip";
   case SIP_TRANSPORT_TLS:
      return "sips";
   }
   return "sip";
}
static const char* get_transport ( enum sip_transport  t) [inline, static]

Return transport as string.

Definition at line 3678 of file chan_sip.c.

References SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, and SIP_TRANSPORT_UDP.

Referenced by _sip_show_peer(), ast_sip_ouraddrfor(), build_contact(), get_transport_pvt(), handle_request_do(), parse_moved_contact(), sip_show_settings(), sip_show_tcp(), and transmit_notify_with_mwi().

{
   switch (t) {
   case SIP_TRANSPORT_UDP:
      return "UDP";
   case SIP_TRANSPORT_TCP:
      return "TCP";
   case SIP_TRANSPORT_TLS:
      return "TLS";
   }

   return "UNKNOWN";
}
static const char* get_transport_list ( unsigned int  transports) [inline, static]

Return configuration of transports for a device.

Definition at line 3657 of file chan_sip.c.

References SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, and SIP_TRANSPORT_UDP.

Referenced by _sip_show_peer(), and sip_show_settings().

                                                                      {
   switch (transports) {
      case SIP_TRANSPORT_UDP:
         return "UDP";
      case SIP_TRANSPORT_TCP:
         return "TCP";
      case SIP_TRANSPORT_TLS:
         return "TLS";
      case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
         return "TCP,UDP";
      case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
         return "TLS,UDP";
      case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
         return "TLS,TCP";
      default:
         return transports ? 
            "TLS,TCP,UDP" : "UNKNOWN"; 
   }
}
static const char* get_transport_pvt ( struct sip_pvt p) [inline, static]

Return transport of dialog.

Note:
this is based on a false assumption. We don't always use the outbound proxy for all requests in a dialog. It depends on the "force" parameter. The FIRST request is always sent to the ob proxy.
Todo:
Fix this function to work correctly

Definition at line 3725 of file chan_sip.c.

References get_transport(), sip_pvt::outboundproxy, set_socket_transport(), sip_pvt::socket, sip_proxy::transport, and sip_socket::type.

Referenced by __sip_xmit(), and build_via().

static int get_transport_str2enum ( const char *  transport) [static]

Return int representing a bit field of transport types found in const char *transport.

Definition at line 3635 of file chan_sip.c.

References ast_strlen_zero(), SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, and SIP_TRANSPORT_UDP.

Referenced by __set_address_from_contact(), and parse_register_contact().

{
   int res = 0;

   if (ast_strlen_zero(transport)) {
      return res;
   }

   if (!strcasecmp(transport, "udp")) {
      res |= SIP_TRANSPORT_UDP;
   }
   if (!strcasecmp(transport, "tcp")) {
      res |= SIP_TRANSPORT_TCP;
   }
   if (!strcasecmp(transport, "tls")) {
      res |= SIP_TRANSPORT_TLS;
   }

   return res;
}
static const char * gettag ( const struct sip_request req,
const char *  header,
char *  tagbuf,
int  tagbufsize 
) [static]

Get tag from packet.

Returns:
Returns the pointer to the provided tag buffer, or NULL if the tag was not found.

Definition at line 19559 of file chan_sip.c.

References ast_copy_string(), get_header(), strcasestr(), and strsep().

Referenced by find_call(), handle_incoming(), handle_request_subscribe(), and handle_response().

{
   const char *thetag;

   if (!tagbuf)
      return NULL;
   tagbuf[0] = '\0';    /* reset the buffer */
   thetag = get_header(req, header);
   thetag = strcasestr(thetag, ";tag=");
   if (thetag) {
      thetag += 5;
      ast_copy_string(tagbuf, thetag, tagbufsize);
      return strsep(&tagbuf, ";");
   }
   return NULL;
}
static int handle_common_options ( struct ast_flags flags,
struct ast_flags mask,
struct ast_variable v 
) [static]

Handle flag-type options common to configuration of devices - peers.

Parameters:
flagsarray of two struct ast_flags
maskarray of two struct ast_flags
vlinked list of config variables to process
Returns:
non-zero if any config options were handled, zero otherwise

Definition at line 23971 of file chan_sip.c.

References ast_clear_flag, ast_copy_string(), ast_false(), ast_log(), ast_set2_flag, ast_set_flag, ast_strdupa, ast_true(), buf, ast_variable::lineno, LOG_WARNING, ast_variable::name, set_insecure_flags(), SIP_DIRECT_MEDIA, SIP_DIRECT_MEDIA_NAT, SIP_DTMF, SIP_DTMF_AUTO, SIP_DTMF_INBAND, SIP_DTMF_INFO, SIP_DTMF_RFC2833, SIP_DTMF_SHORTINFO, SIP_G726_NONSTANDARD, SIP_INSECURE, SIP_NAT, SIP_NAT_ALWAYS, SIP_NAT_NEVER, SIP_NAT_RFC3581, SIP_NAT_ROUTE, SIP_PAGE2_ALLOWOVERLAP, SIP_PAGE2_ALLOWSUBSCRIBE, SIP_PAGE2_BUGGY_MWI, SIP_PAGE2_FAX_DETECT, SIP_PAGE2_FAX_DETECT_BOTH, SIP_PAGE2_FAX_DETECT_CNG, SIP_PAGE2_FAX_DETECT_T38, SIP_PAGE2_IGNORESDPVERSION, SIP_PAGE2_RFC2833_COMPENSATE, SIP_PAGE2_TEXTSUPPORT, SIP_PAGE2_VIDEOSUPPORT, SIP_PAGE2_VIDEOSUPPORT_ALWAYS, SIP_PROG_INBAND, SIP_PROG_INBAND_NO, SIP_PROG_INBAND_YES, SIP_PROMISCREDIR, SIP_REINVITE, SIP_REINVITE_UPDATE, SIP_SENDRPID, SIP_TRUSTRPID, SIP_USECLIENTCODE, strsep(), ast_variable::value, and word.

Referenced by build_peer(), and reload_config().

{
   int res = 1;

   if (!strcasecmp(v->name, "trustrpid")) {
      ast_set_flag(&mask[0], SIP_TRUSTRPID);
      ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
   } else if (!strcasecmp(v->name, "sendrpid")) {
      ast_set_flag(&mask[0], SIP_SENDRPID);
      ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
   } else if (!strcasecmp(v->name, "g726nonstandard")) {
      ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
      ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
   } else if (!strcasecmp(v->name, "useclientcode")) {
      ast_set_flag(&mask[0], SIP_USECLIENTCODE);
      ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
   } else if (!strcasecmp(v->name, "dtmfmode")) {
      ast_set_flag(&mask[0], SIP_DTMF);
      ast_clear_flag(&flags[0], SIP_DTMF);
      if (!strcasecmp(v->value, "inband"))
         ast_set_flag(&flags[0], SIP_DTMF_INBAND);
      else if (!strcasecmp(v->value, "rfc2833"))
         ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
      else if (!strcasecmp(v->value, "info"))
         ast_set_flag(&flags[0], SIP_DTMF_INFO);
      else if (!strcasecmp(v->value, "shortinfo"))
         ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
      else if (!strcasecmp(v->value, "auto"))
         ast_set_flag(&flags[0], SIP_DTMF_AUTO);
      else {
         ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
         ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
      }
   } else if (!strcasecmp(v->name, "nat")) {
      ast_set_flag(&mask[0], SIP_NAT);
      ast_clear_flag(&flags[0], SIP_NAT);
      if (!strcasecmp(v->value, "never"))
         ast_set_flag(&flags[0], SIP_NAT_NEVER);
      else if (!strcasecmp(v->value, "route"))
         ast_set_flag(&flags[0], SIP_NAT_ROUTE);
      else if (ast_true(v->value))
         ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
      else
         ast_set_flag(&flags[0], SIP_NAT_RFC3581);
   } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
      ast_set_flag(&mask[0], SIP_REINVITE);
      ast_clear_flag(&flags[0], SIP_REINVITE);
      if (ast_true(v->value)) {
         ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
      } else if (!ast_false(v->value)) {
         char buf[64];
         char *word, *next = buf;

         ast_copy_string(buf, v->value, sizeof(buf));
         while ((word = strsep(&next, ","))) {
            if (!strcasecmp(word, "update")) {
               ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
            } else if (!strcasecmp(word, "nonat")) {
               ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
               ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
            } else {
               ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
            }
         }
      }
   } else if (!strcasecmp(v->name, "insecure")) {
      ast_set_flag(&mask[0], SIP_INSECURE);
      ast_clear_flag(&flags[0], SIP_INSECURE);
      set_insecure_flags(&flags[0], v->value, v->lineno);   
   } else if (!strcasecmp(v->name, "progressinband")) {
      ast_set_flag(&mask[0], SIP_PROG_INBAND);
      ast_clear_flag(&flags[0], SIP_PROG_INBAND);
      if (ast_true(v->value))
         ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
      else if (strcasecmp(v->value, "never"))
         ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
   } else if (!strcasecmp(v->name, "promiscredir")) {
      ast_set_flag(&mask[0], SIP_PROMISCREDIR);
      ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
   } else if (!strcasecmp(v->name, "videosupport")) {
      if (!strcasecmp(v->value, "always")) {
         ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
         ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
      } else {
         ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
         ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
      }
   } else if (!strcasecmp(v->name, "textsupport")) {
      ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
      ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
      res = 1;
   } else if (!strcasecmp(v->name, "allowoverlap")) {
      ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
      ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
   } else if (!strcasecmp(v->name, "allowsubscribe")) {
      ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
      ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
   } else if (!strcasecmp(v->name, "ignoresdpversion")) {
      ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
      ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
   } else if (!strcasecmp(v->name, "faxdetect")) {
      ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
      if (ast_true(v->value)) {
         ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
      } else if (ast_false(v->value)) {
         ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
      } else {
         char *buf = ast_strdupa(v->value);
         char *word, *next = buf;

         while ((word = strsep(&next, ","))) {
            if (!strcasecmp(word, "cng")) {
               ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
            } else if (!strcasecmp(word, "t38")) {
               ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
            } else {
               ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
            }
         }
      }
   } else if (!strcasecmp(v->name, "rfc2833compensate")) {
      ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
      ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
   } else if (!strcasecmp(v->name, "buggymwi")) {
      ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
      ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
   } else
      res = 0;

   return res;
}
static int handle_incoming ( struct sip_pvt p,
struct sip_request req,
struct sockaddr_in *  sin,
int *  recount,
int *  nounlock 
) [static]

Handle incoming SIP requests (methods)

Note:
This is where all incoming requests go first.
called with p and p->owner locked

Definition at line 22196 of file chan_sip.c.

References __get_header(), __sip_ack(), sip_pvt::alreadygone, ast_debug, ast_inet_ntoa(), ast_log(), ast_skip_blanks(), ast_string_field_set, ast_strlen_zero(), ast_verbose(), check_pendings(), sip_request::debug, DEFAULT_TRANS_TIMEOUT, extract_uri(), find_sdp(), get_header(), gettag(), sip_pvt::glareinvite, handle_request_bye(), handle_request_cancel(), handle_request_info(), handle_request_invite(), handle_request_message(), handle_request_notify(), handle_request_options(), handle_request_refer(), handle_request_register(), handle_request_subscribe(), handle_response(), sip_request::has_to_tag, sip_request::header, sip_request::headers, sip_pvt::icseq, cfsip_methods::id, sip_request::ignore, sip_pvt::initreq, INV_TERMINATED, sip_pvt::invitestate, sip_pvt::lastinvite, sip_pvt::lastmsg, sip_request::len, LOG_DEBUG, LOG_ERROR, LOG_NOTICE, LOG_WARNING, sip_request::method, sip_pvt::method, sip_pvt::ocseq, option_debug, sip_settings::pedanticsipchecking, sip_pvt::pendinginvite, process_sdp(), pvt_set_needdestroy(), sip_pvt::randdata, REQ_OFFSET_TO_STR, sip_request::rlPart1, sip_request::rlPart2, sip_pvt::sa, SDP_T38_NONE, SIP_ACK, SIP_BYE, SIP_CANCEL, sip_cfg, sip_debug_test_pvt(), SIP_INFO, SIP_INVITE, SIP_MESSAGE, sip_methods, SIP_NOTIFY, SIP_OPTIONS, SIP_REFER, SIP_REGISTER, SIP_RESPONSE, sip_scheddestroy(), SIP_SUBSCRIBE, cfsip_methods::text, sip_pvt::theirtag, transmit_response(), transmit_response_reliable(), transmit_response_with_allow(), and sip_peer::useragent.

Referenced by handle_request_do(), and process_request_queue().

{
   /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
      relatively static */
   const char *cmd;
   const char *cseq;
   const char *useragent;
   const char *via;
   const char *callid;
   int via_pos = 0;
   int seqno;
   int len;
   int respid;
   int res = 0;
   int debug = sip_debug_test_pvt(p);
   char *e;
   int error = 0;
   int oldmethod = p->method;
   int acked = 0;

   /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
    * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
    * so we can check to make sure these fields exist for all requests and responses */
   cseq = get_header(req, "Cseq");
   cmd = REQ_OFFSET_TO_STR(req, header[0]);
   /* Save the via_pos so we can check later that responses only have 1 Via header */
   via = __get_header(req, "Via", &via_pos);
   /* This must exist already because we've called find_call by now */
   callid = get_header(req, "Call-ID");

   /* Must have Cseq */
   if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
      ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
      error = 1;
   }
   if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
      ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
      error = 1;
   }
   if (error) {
      if (!p->initreq.headers) { /* New call */
         pvt_set_needdestroy(p, "no headers");
      }
      return -1;
   }
   /* Get the command XXX */

   cmd = REQ_OFFSET_TO_STR(req, rlPart1);
   e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));

   /* Save useragent of the client */
   useragent = get_header(req, "User-Agent");
   if (!ast_strlen_zero(useragent))
      ast_string_field_set(p, useragent, useragent);

   /* Find out SIP method for incoming request */
   if (req->method == SIP_RESPONSE) {  /* Response to our request */
      /* ignore means "don't do anything with it" but still have to 
       * respond appropriately.
       * But in this case this is a response already, so we really
       * have nothing to do with this message, and even setting the
       * ignore flag is pointless.
       */
      if (ast_strlen_zero(e)) {
         return 0;
      }
      if (sscanf(e, "%30d %n", &respid, &len) != 1) {
         ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
         return 0;
      }
      if (respid <= 0) {
         ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
         return 0;
      }
      /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
       * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
       * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
      if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
         ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
         return 0;
      }
      if (p->ocseq && (p->ocseq < seqno)) {
         if (option_debug)
            ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
         return -1;
      } else {
         if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
            extract_uri(p, req);
         }
         handle_response(p, respid, e + len, req, seqno);
      }
      return 0;
   }

   /* New SIP request coming in 
      (could be new request in existing SIP dialog as well...) 
    */         
   
   p->method = req->method;   /* Find out which SIP method they are using */
   ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd); 

   if (p->icseq && (p->icseq > seqno) ) {
      if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
         ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
      }  else {
         ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
         if (req->method != SIP_ACK)
            transmit_response(p, "500 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
         return -1;
      }
   } else if (p->icseq &&
         p->icseq == seqno &&
         req->method != SIP_ACK &&
         (p->method != SIP_CANCEL || p->alreadygone)) {
      /* ignore means "don't do anything with it" but still have to 
         respond appropriately.  We do this if we receive a repeat of
         the last sequence number  */
      req->ignore = 1;
      ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
   }
      
   if (seqno >= p->icseq)
      /* Next should follow monotonically (but not necessarily 
         incrementally -- thanks again to the genius authors of SIP --
         increasing */
      p->icseq = seqno;

   /* Find their tag if we haven't got it */
   if (ast_strlen_zero(p->theirtag)) {
      char tag[128];

      gettag(req, "From", tag, sizeof(tag));
      ast_string_field_set(p, theirtag, tag);
   }
   snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);

   if (sip_cfg.pedanticsipchecking) {
      /* If this is a request packet without a from tag, it's not
         correct according to RFC 3261  */
      /* Check if this a new request in a new dialog with a totag already attached to it,
         RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
      if (!p->initreq.headers && req->has_to_tag) {
         /* If this is a first request and it got a to-tag, it is not for us */
         if (!req->ignore && req->method == SIP_INVITE) {
            transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
            /* Will cease to exist after ACK */
         } else if (req->method != SIP_ACK) {
            transmit_response(p, "481 Call/Transaction Does Not Exist", req);
            sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
         } else {
            ast_debug(1, "Got ACK for unknown dialog... strange.\n");
         }
         return res;
      }
   }

   if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
      transmit_response(p, "400 Bad request", req);
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      return -1;
   }

   /* Handle various incoming SIP methods in requests */
   switch (p->method) {
   case SIP_OPTIONS:
      res = handle_request_options(p, req);
      break;
   case SIP_INVITE:
      res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
      break;
   case SIP_REFER:
      res = handle_request_refer(p, req, debug, seqno, nounlock);
      break;
   case SIP_CANCEL:
      res = handle_request_cancel(p, req);
      break;
   case SIP_BYE:
      res = handle_request_bye(p, req);
      break;
   case SIP_MESSAGE:
      res = handle_request_message(p, req);
      break;
   case SIP_SUBSCRIBE:
      res = handle_request_subscribe(p, req, sin, seqno, e);
      break;
   case SIP_REGISTER:
      res = handle_request_register(p, req, sin, e);
      break;
   case SIP_INFO:
      if (req->debug)
         ast_verbose("Receiving INFO!\n");
      if (!req->ignore) 
         handle_request_info(p, req);
      else  /* if ignoring, transmit response */
         transmit_response(p, "200 OK", req);
      break;
   case SIP_NOTIFY:
      res = handle_request_notify(p, req, sin, seqno, e);
      break;
   case SIP_ACK:
      /* Make sure we don't ignore this */
      if (seqno == p->pendinginvite) {
         p->invitestate = INV_TERMINATED;
         p->pendinginvite = 0;
         acked = __sip_ack(p, seqno, 1 /* response */, 0);
         if (find_sdp(req)) {
            if (process_sdp(p, req, SDP_T38_NONE))
               return -1;
         }
         check_pendings(p);
      } else if (p->glareinvite == seqno) {
         /* handle ack for the 491 pending sent for glareinvite */
         p->glareinvite = 0;
         acked = __sip_ack(p, seqno, 1, 0);
      }
      if (!acked) {
         /* Got an ACK that did not match anything. Ignore
          * silently and restore previous method */
         p->method = oldmethod;
      }
      if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
         pvt_set_needdestroy(p, "unmatched ACK");
      }
      break;
   default:
      transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
      ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
         cmd, ast_inet_ntoa(p->sa.sin_addr));
      /* If this is some new method, and we don't have a call, destroy it now */
      if (!p->initreq.headers) {
         pvt_set_needdestroy(p, "unimplemented method");
      }
      break;
   }
   return res;
}
static int handle_invite_replaces ( struct sip_pvt p,
struct sip_request req,
int  debug,
int  seqno,
struct sockaddr_in *  sin,
int *  nounlock 
) [static]

Handle the transfer part of INVITE with a replaces: header, meaning a target pickup or an attended transfer. Used only once. XXX 'ignore' is unused.

Note:
this function is called by handle_request_invite(). Four locks held at the beginning of this function, p, p->owner, p->refer->refer_call->owner... only p's lock should remain at the end of this function. p's lock is held by sipsock_read()

Definition at line 19781 of file chan_sip.c.

References ast_channel::_state, append_history, ast_bridged_channel(), AST_CAUSE_SWITCH_CONGESTION, ast_channel_masquerade(), ast_channel_unlock, ast_debug, ast_do_masquerade(), ast_hangup(), ast_log(), ast_quiet_chan(), ast_set_flag, ast_setstate(), ast_state2str(), AST_STATE_DOWN, AST_STATE_RING, AST_STATE_RINGING, AST_STATE_UP, DEFAULT_TRANS_TIMEOUT, dialog_unref(), FALSE, sip_pvt::flags, ast_channel::hangupcause, sip_request::ignore, LOG_ERROR, LOG_NOTICE, LOG_WARNING, ast_channel::name, sip_pvt::owner, sip_pvt::refer, sip_refer::refer_call, SIP_DEFER_BYE_ON_TRANSFER, sip_pvt_lock, sip_pvt_unlock, sip_scheddestroy(), ast_channel::tech_pvt, transmit_response(), transmit_response_reliable(), transmit_response_with_sdp(), and XMIT_RELIABLE.

Referenced by handle_request_invite().

{
   int earlyreplace = 0;
   int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
   struct ast_channel *c = p->owner;   /* Our incoming call */
   struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
   struct ast_channel *targetcall;     /* The bridge to the take-over target */

   struct ast_channel *test;

   /* Check if we're in ring state */
   if (replacecall->_state == AST_STATE_RING)
      earlyreplace = 1;

   /* Check if we have a bridge */
   if (!(targetcall = ast_bridged_channel(replacecall))) {
      /* We have no bridge */
      if (!earlyreplace) {
         ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
         oneleggedreplace = 1;
      }
   } 
   if (targetcall && targetcall->_state == AST_STATE_RINGING)
      ast_debug(4, "SIP transfer: Target channel is in ringing state\n");

   if (targetcall) 
      ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name); 
   else
      ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name); 

   if (req->ignore) {
      ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
      /* We should answer something here. If we are here, the
         call we are replacing exists, so an accepted 
         can't harm */
      transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
      /* Do something more clever here */
      if (c) {
         *nounlock = 1;
         ast_channel_unlock(c);
      }
      ast_channel_unlock(replacecall);
      sip_pvt_unlock(p->refer->refer_call);
      return 1;
   } 
   if (!c) {
      /* What to do if no channel ??? */
      ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
      transmit_response_reliable(p, "503 Service Unavailable", req);
      append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      ast_channel_unlock(replacecall);
      sip_pvt_unlock(p->refer->refer_call);
      return 1;
   }
   append_history(p, "Xfer", "INVITE/Replace received");
   /* We have three channels to play with
      channel c: New incoming call
      targetcall: Call from PBX to target
      p->refer->refer_call: SIP pvt dialog from transferer to pbx.
      replacecall: The owner of the previous
      We need to masq C into refer_call to connect to 
      targetcall;
      If we are talking to internal audio stream, target call is null.
   */

   /* Fake call progress */
   transmit_response(p, "100 Trying", req);
   ast_setstate(c, AST_STATE_RING);

   /* Masquerade the new call into the referred call to connect to target call 
      Targetcall is not touched by the masq */

   /* Answer the incoming call and set channel to UP state */
   transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
      
   ast_setstate(c, AST_STATE_UP);
   
   /* Stop music on hold and other generators */
   ast_quiet_chan(replacecall);
   ast_quiet_chan(targetcall);
   ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);

   /* Make sure that the masq does not free our PVT for the old call */
   if (! earlyreplace && ! oneleggedreplace )
      ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */

   /* Prepare the masquerade - if this does not happen, we will be gone */
   if(ast_channel_masquerade(replacecall, c))
      ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
   else
      ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);

   /* C should now be in place of replacecall */
   if (ast_do_masquerade(replacecall)) {
      ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
   }

   if (earlyreplace || oneleggedreplace ) {
      c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
   }

   ast_setstate(c, AST_STATE_DOWN);
   ast_debug(4, "After transfer:----------------------------\n");
   ast_debug(4, " -- C:        %s State %s\n", c->name, ast_state2str(c->_state));
   if (replacecall)
      ast_debug(4, " -- replacecall:        %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
   if (p->owner) {
      ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
      test = ast_bridged_channel(p->owner);
      if (test)
         ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
      else
         ast_debug(4, " -- No call bridged to C->owner \n");
   } else 
      ast_debug(4, " -- No channel yet \n");
   ast_debug(4, "End After transfer:----------------------------\n");

   /* unlock sip pvt and owner so hangup can do its thing */
   ast_channel_unlock(replacecall);
   ast_channel_unlock(c);
   sip_pvt_unlock(p->refer->refer_call);
   sip_pvt_unlock(p);
   *nounlock = 1;

   /* The call should be down with no ast_channel, so hang it up */
   c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
   ast_hangup(c);
   sip_pvt_lock(p); /* lock PVT structure again after hangup */

   return 0;
}
static int handle_request_bye ( struct sip_pvt p,
struct sip_request req 
) [static]

Handle incoming BYE request.

Definition at line 21636 of file chan_sip.c.

References __sip_pretend_ack(), append_history, ast_async_goto(), ast_bridged_channel(), AST_CAUSE_PROTOCOL_ERROR, ast_channel_trylock, ast_channel_unlock, ast_clear_flag, AST_CONTROL_UNHOLD, ast_debug, ast_inet_ntoa(), ast_log(), ast_queue_control(), ast_queue_hangup(), ast_queue_hangup_with_cause(), ast_rtp_get_quality(), ast_rtp_set_vars(), ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_channel::bridge, sip_pvt::callid, check_via(), context, sip_pvt::context, copy_request(), sip_settings::default_context, DEFAULT_TRANS_TIMEOUT, sip_pvt::do_history, sip_pvt::flags, get_also_info(), get_header(), sip_request::ignore, sip_pvt::initreq, INV_TERMINATED, sip_pvt::invitestate, IS_SIP_TECH, LOG_NOTICE, LOG_WARNING, sip_request::method, sip_pvt::owner, pbx_builtin_setvar_helper(), sip_pvt::pendinginvite, sip_pvt::recv, sip_pvt::refer, sip_refer::refer_to, sip_pvt::rtp, RTPQOS_JITTER, RTPQOS_LOSS, RTPQOS_RTT, RTPQOS_SUMMARY, sip_alreadygone(), sip_cfg, sip_methods, SIP_OUTGOING, SIP_PAGE2_DIALOG_ESTABLISHED, sip_pvt_lock, sip_pvt_unlock, sip_scheddestroy(), stop_media_flows(), stop_session_timer(), ast_channel::tech, ast_channel::tech_pvt, cfsip_methods::text, transmit_response(), transmit_response_reliable(), sip_pvt::trtp, and sip_pvt::vrtp.

Referenced by handle_incoming().

{
   struct ast_channel *c=NULL;
   int res;
   struct ast_channel *bridged_to;
   
   /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
   if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
      transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
   }

   __sip_pretend_ack(p);

   p->invitestate = INV_TERMINATED;

   copy_request(&p->initreq, req);
   if (sipdebug)
      ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
   check_via(p, req);
   sip_alreadygone(p);

   /* Get RTCP quality before end of call */
   if (p->do_history || p->owner) {
      struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
      char *videoqos, *textqos;

      /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
       * to lock the bridge. This may get hairy...
       */
      while (bridge && ast_channel_trylock(bridge)) {
         ast_channel_unlock(p->owner);
         do {
            /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
            sip_pvt_unlock(p);
            usleep(1);
            sip_pvt_lock(p);
         } while (p->owner && ast_channel_trylock(p->owner));
         bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
      }

      if (p->rtp) {  
         if (p->do_history) {
            char *audioqos,
                 *audioqos_jitter,
                 *audioqos_loss,
                 *audioqos_rtt;

            audioqos        = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
            audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
            audioqos_loss   = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
            audioqos_rtt    = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);

            append_history(p, "RTCPaudio", "Quality:%s", audioqos);
            append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
            append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
            append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
         }
         
         if (p->owner) {
            ast_rtp_set_vars(p->owner, p->rtp);
         }
      }

      if (bridge) {
         struct sip_pvt *q = bridge->tech_pvt;

         if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
            ast_rtp_set_vars(bridge, q->rtp);
         ast_channel_unlock(bridge);
      }

      if (p->vrtp) {
         videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
         if (p->do_history)
            append_history(p, "RTCPvideo", "Quality:%s", videoqos);
         if (p->owner)
            pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
      }

      if (p->trtp) {
         textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
         if (p->do_history)
            append_history(p, "RTCPtext", "Quality:%s", textqos);
         if (p->owner)
            pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
      }
   }

   stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
   stop_session_timer(p); /* Stop Session-Timer */

   if (!ast_strlen_zero(get_header(req, "Also"))) {
      ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
         ast_inet_ntoa(p->recv.sin_addr));
      if (ast_strlen_zero(p->context))
         ast_string_field_set(p, context, sip_cfg.default_context);
      res = get_also_info(p, req);
      if (!res) {
         c = p->owner;
         if (c) {
            bridged_to = ast_bridged_channel(c);
            if (bridged_to) {
               /* Don't actually hangup here... */
               ast_queue_control(c, AST_CONTROL_UNHOLD);
               ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
            } else
               ast_queue_hangup(p->owner);
         }
      } else {
         ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
         if (p->owner)
            ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
      }
   } else if (p->owner) {
      ast_queue_hangup(p->owner);
      ast_debug(3, "Received bye, issuing owner hangup\n");
   } else {
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
   }
   ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
   transmit_response(p, "200 OK", req);

   return 1;
}
static int handle_request_cancel ( struct sip_pvt p,
struct sip_request req 
) [static]

Handle incoming CANCEL request.

Definition at line 21460 of file chan_sip.c.

References __sip_pretend_ack(), ast_channel::_state, ast_debug, ast_free, ast_queue_hangup(), AST_SCHED_DEL, AST_STATE_UP, ast_test_flag, check_via(), DEC_CALL_LIMIT, DEFAULT_TRANS_TIMEOUT, sip_pvt::flags, sip_pvt::initreq, INV_CANCELLED, INV_TERMINATED, sip_pvt::invitestate, sip_pvt::lastinvite, sip_request::len, sip_pkt::next, sip_pvt::owner, sip_pvt::packets, sip_pkt::response_code, sip_pkt::retransid, sip_pkt::seqno, sip_alreadygone(), SIP_INC_COUNT, SIP_PAGE2_CALL_ONHOLD, sip_scheddestroy(), stop_media_flows(), transmit_response(), transmit_response_reliable(), UNLINK, and update_call_counter().

Referenced by handle_incoming().

{
      
   check_via(p, req);
   sip_alreadygone(p);

   /* At this point, we could have cancelled the invite at the same time
      as the other side sends a CANCEL. Our final reply with error code
      might not have been received by the other side before the CANCEL
      was sent, so let's just give up retransmissions and waiting for
      ACK on our error code. The call is hanging up any way. */
   if (p->invitestate == INV_TERMINATED)
      __sip_pretend_ack(p);
   else
      p->invitestate = INV_CANCELLED;
   
   if (p->owner && p->owner->_state == AST_STATE_UP) {
      /* This call is up, cancel is ignored, we need a bye */
      transmit_response(p, "200 OK", req);
      ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
      return 0;
   }

   if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) 
      update_call_counter(p, DEC_CALL_LIMIT);

   stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
   if (p->owner)
      ast_queue_hangup(p->owner);
   else
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
   if (p->initreq.len > 0) {
      struct sip_pkt *pkt, *prev_pkt;
      /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
       * a reliable 487, then we don't want to schedule another one on top of the previous
       * one.
       *
       * As odd as this may sound, we can't rely on the previously-transmitted "reliable" 
       * response in this situation. What if we've sent all of our reliable responses 
       * already and now all of a sudden, we get this second CANCEL?
       *
       * The only way to do this correctly is to cancel our previously-scheduled reliably-
       * transmitted response and send a new one in its place.
       */
      for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
         if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
            AST_SCHED_DEL(sched, pkt->retransid);
            UNLINK(pkt, p->packets, prev_pkt);
            ast_free(pkt);
            break;
         }
      }
      transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
      transmit_response(p, "200 OK", req);
      return 1;
   } else {
      transmit_response(p, "481 Call Leg Does Not Exist", req);
      return 0;
   }
}
static int handle_request_do ( struct sip_request req,
struct sockaddr_in *  sin 
) [static]

Handle incoming SIP message - request or response.

This is used for all transports (udp, tcp and tcp/tls)

Definition at line 22574 of file chan_sip.c.

References ao2_t_ref, append_history, ast_channel_trylock, ast_channel_unlock, ast_debug, ast_inet_ntoa(), AST_LIST_EMPTY, ast_log(), ast_mutex_lock(), ast_mutex_unlock(), AST_SCHED_DEL_UNREF, ast_str_reset(), ast_update_use_count(), ast_verbose(), sip_request::authenticated, sip_pvt::callid, copy_socket_data(), sip_request::data, sip_request::debug, dialog_unref(), sip_pvt::do_history, find_call(), find_sip_method(), get_header(), get_transport(), handle_incoming(), sip_request::headers, sip_request::len, sip_request::lines, LOG_ERROR, lws2sws(), sip_request::method, ast_channel::name, netlock, sip_pvt::owner, parse_request(), sip_settings::pedanticsipchecking, process_request_queue(), queue_request(), sip_pvt::recv, REQ_OFFSET_TO_STR, sip_pvt::request_queue, sip_pvt::request_queue_sched_id, sip_request::rlPart1, sip_request::rlPart2, S_OR, SIP_ACK, sip_cfg, sip_debug_test_addr(), sip_pvt_unlock, sip_pvt::socket, sip_request::socket, transmit_response(), and sip_socket::type.

Referenced by _sip_tcp_helper_thread(), and sipsock_read().

{
   struct sip_pvt *p;
   int recount = 0;
   int nounlock = 0;
   int lockretry;

   if (sip_debug_test_addr(sin)) /* Set the debug flag early on packet level */
      req->debug = 1;
   if (sip_cfg.pedanticsipchecking)
      req->len = lws2sws(req->data->str, req->len);   /* Fix multiline headers */
   if (req->debug) {
      ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n", 
         get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr), 
         ntohs(sin->sin_port), req->data->str);
   }

   if (parse_request(req) == -1) { /* Bad packet, can't parse */
      ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
      return 1;
   }
   req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));

   if (req->debug)
      ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");

   if (req->headers < 2) { /* Must have at least two headers */
      ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
      return 1;
   }

   /* Process request, with netlock held, and with usual deadlock avoidance */
   for (lockretry = 10; lockretry > 0; lockretry--) {
      ast_mutex_lock(&netlock);

      /* Find the active SIP dialog or create a new one */
      p = find_call(req, sin, req->method);  /* returns p locked */
      if (p == NULL) {
         ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
         ast_mutex_unlock(&netlock);
         return 1;
      }

      copy_socket_data(&p->socket, &req->socket);

      /* Go ahead and lock the owner if it has one -- we may need it */
      /* becaues this is deadlock-prone, we need to try and unlock if failed */
      if (!p->owner || !ast_channel_trylock(p->owner))
         break;   /* locking succeeded */

      if (lockretry != 1) {
         sip_pvt_unlock(p);
         ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
         ast_mutex_unlock(&netlock);
         /* Sleep for a very short amount of time */
         usleep(1);
      }
   }
   p->recv = *sin;

   /* if we have an owner, then this request has been authenticated */
   if (p->owner) {
      req->authenticated = 1;
   }

   if (p->do_history) /* This is a request or response, note what it was for */
      append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));

   if (!lockretry) {
      if (!queue_request(p, req)) {
         /* the request has been queued for later handling */
         sip_pvt_unlock(p);
         ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
         ast_mutex_unlock(&netlock);
         return 1;
      }

      if (p->owner)
         ast_log(LOG_ERROR, "Channel lock for %s could not be obtained, and request was unable to be queued.\n", S_OR(p->owner->name, "- no channel name ??? - "));
      ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
      if (req->method != SIP_ACK)
         transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
      /* XXX We could add retry-after to make sure they come back */
      append_history(p, "LockFail", "Owner lock failed, transaction failed.");
      sip_pvt_unlock(p);
      ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
      ast_mutex_unlock(&netlock);
      return 1;
   }

   /* if there are queued requests on this sip_pvt, process them first, so that everything is
      handled in order
   */
   if (!AST_LIST_EMPTY(&p->request_queue)) {
      AST_SCHED_DEL_UNREF(sched, p->request_queue_sched_id, dialog_unref(p, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
      process_request_queue(p, &recount, &nounlock);
   }

   if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
      /* Request failed */
      ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
   }
      
   if (recount)
      ast_update_use_count();

   if (p->owner && !nounlock)
      ast_channel_unlock(p->owner);
   sip_pvt_unlock(p);
   ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
   ast_mutex_unlock(&netlock);
   return 1;
}
static void handle_request_info ( struct sip_pvt p,
struct sip_request req 
) [static]

Receive SIP INFO Message.

Todo:
Note: Doesn't read the duration of the DTMF. Should be fixed.

Definition at line 17192 of file chan_sip.c.

References ast_bridged_channel(), ast_cdr_setuserfield(), AST_CONTROL_FLASH, AST_CONTROL_VIDUPDATE, ast_copy_string(), ast_debug, ast_find_call_feature(), AST_FRAME_CONTROL, AST_FRAME_DTMF, ast_log(), ast_queue_control(), ast_queue_frame(), ast_rdlock_call_features(), ast_strlen_zero(), ast_test_flag, ast_unlock_call_features(), ast_verbose(), buf, sip_pvt::callid, ast_channel::cdr, DEFAULT_TRANS_TIMEOUT, sip_history::event, ast_call_feature::exten, sip_pvt::flags, get_body(), get_header(), get_msg_text(), ast_frame::len, LOG_WARNING, sip_pvt::owner, sip_scheddestroy(), SIP_USECLIENTCODE, ast_frame::subclass, transmit_response(), and TRUE.

Referenced by handle_incoming().

{
   char buf[1024];
   unsigned int event;
   const char *c = get_header(req, "Content-Type");

   /* Need to check the media/type */
   if (!strcasecmp(c, "application/dtmf-relay") ||
       !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
      unsigned int duration = 0;

      if (!p->owner) {  /* not a PBX call */
         transmit_response(p, "481 Call leg/transaction does not exist", req);
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
         return;
      }

      /* Try getting the "signal=" part */
      if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
         ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
         transmit_response(p, "200 OK", req); /* Should return error */
         return;
      } else {
         ast_copy_string(buf, c, sizeof(buf));
      }

      if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
         duration = atoi(c);
      if (!duration)
         duration = 100; /* 100 ms */


      if (ast_strlen_zero(buf)) {
         transmit_response(p, "200 OK", req);
         return;
      }

      if (buf[0] == '*')
         event = 10;
      else if (buf[0] == '#')
         event = 11;
      else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
         event = 12 + buf[0] - 'A';
      else if (buf[0] == '!')
         event = 16;
      else
         event = atoi(buf);
      if (event == 16) {
         /* send a FLASH event */
         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
         ast_queue_frame(p->owner, &f);
         if (sipdebug)
            ast_verbose("* DTMF-relay event received: FLASH\n");
      } else {
         /* send a DTMF event */
         struct ast_frame f = { AST_FRAME_DTMF, };
         if (event < 10) {
            f.subclass = '0' + event;
         } else if (event < 11) {
            f.subclass = '*';
         } else if (event < 12) {
            f.subclass = '#';
         } else if (event < 16) {
            f.subclass = 'A' + (event - 12);
         }
         f.len = duration;
         ast_queue_frame(p->owner, &f);
         if (sipdebug)
            ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
      }
      transmit_response(p, "200 OK", req);
      return;
   } else if (!strcasecmp(c, "application/dtmf")) {
      /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
      unsigned int duration = 0;

      if (!p->owner) {  /* not a PBX call */
         transmit_response(p, "481 Call leg/transaction does not exist", req);
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
         return;
      }

      get_msg_text(buf, sizeof(buf), req, TRUE);
      duration = 100; /* 100 ms */

      if (ast_strlen_zero(buf)) {
         transmit_response(p, "200 OK", req);
         return;
      }
      event = atoi(buf);
      if (event == 16) {
         /* send a FLASH event */
         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
         ast_queue_frame(p->owner, &f);
         if (sipdebug)
            ast_verbose("* DTMF-relay event received: FLASH\n");
      } else {
         /* send a DTMF event */
         struct ast_frame f = { AST_FRAME_DTMF, };
         if (event < 10) {
            f.subclass = '0' + event;
         } else if (event < 11) {
            f.subclass = '*';
         } else if (event < 12) {
            f.subclass = '#';
         } else if (event < 16) {
            f.subclass = 'A' + (event - 12);
         }
         f.len = duration;
         ast_queue_frame(p->owner, &f);
         if (sipdebug)
            ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
      }
      transmit_response(p, "200 OK", req);
      return;

   } else if (!strcasecmp(c, "application/media_control+xml")) {
      /* Eh, we'll just assume it's a fast picture update for now */
      if (p->owner)
         ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
      transmit_response(p, "200 OK", req);
      return;
   } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
      /* Client code (from SNOM phone) */
      if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
         if (p->owner && p->owner->cdr)
            ast_cdr_setuserfield(p->owner, c);
         if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
            ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
         transmit_response(p, "200 OK", req);
      } else {
         transmit_response(p, "403 Forbidden", req);
      }
      return;
   } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
      /* INFO messages generated by some phones to start/stop recording
         on phone calls. 
         OEJ: I think this should be something that is enabled/disabled
         per device. I don't want incoming callers to record calls in my
         pbx.
      */
      /* first, get the feature string, if it exists */
      struct ast_call_feature *feat;
      int j;
      struct ast_frame f = { AST_FRAME_DTMF, };

      ast_rdlock_call_features();
      feat = ast_find_call_feature("automon");
      if (!feat || ast_strlen_zero(feat->exten)) {
         ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
         /* 403 means that we don't support this feature, so don't request it again */
         transmit_response(p, "403 Forbidden", req);
         ast_unlock_call_features();
         return;
      } 
      /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
      f.len = 100;
      for (j=0; j < strlen(feat->exten); j++) {
         f.subclass = feat->exten[j];
         ast_queue_frame(p->owner, &f);
         if (sipdebug)
            ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
      }
      ast_unlock_call_features();

      ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
      transmit_response(p, "200 OK", req);
      return;
   } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
      /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
      transmit_response(p, "200 OK", req);
      return;
   }

   /* Other type of INFO message, not really understood by Asterisk */
   /* if (get_msg_text(buf, sizeof(buf), req)) { */

   ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
   transmit_response(p, "415 Unsupported media type", req);
   return;
}
static int handle_request_invite ( struct sip_pvt p,
struct sip_request req,
int  debug,
int  seqno,
struct sockaddr_in *  sin,
int *  recount,
char *  e,
int *  nounlock 
) [static]

Handle incoming INVITE request.

Note:
If the INVITE has a Replaces header, it is part of an attended transfer. If so, we do not go through the dial plan but tries to find the active call and masquerade into it

This is a spiral. What we need to do is to just change the outgoing INVITE so that it now routes to the new Request URI. Since we created the INVITE ourselves that should be all we need to do.

Todo:
XXX This needs to be reviewed. YOu don't change the request URI really, you route the packet correctly instead...

Definition at line 20233 of file chan_sip.c.

References __sip_ack(), ast_channel::_state, append_history, AST_CAUSE_CALL_REJECTED, AST_CAUSE_NORMAL_CLEARING, ast_channel_lock, ast_channel_unlock, ast_clear_flag, AST_CONTROL_BUSY, AST_CONTROL_SRCUPDATE, AST_CONTROL_UNHOLD, ast_copy_string(), ast_debug, ast_hangup(), ast_log(), AST_MAX_CONTEXT, AST_MAX_EXTENSION, ast_null_frame, AST_PBX_CALL_LIMIT, AST_PBX_FAILED, ast_pbx_start(), AST_PBX_SUCCESS, ast_pickup_call(), ast_pickup_ext(), ast_queue_control(), ast_queue_frame(), ast_rtp_set_alt_peer(), ast_rtp_setdtmf(), ast_rtp_setdtmfcompensate(), ast_sched_add(), ast_set_flag, ast_setstate(), ast_skip_blanks(), AST_STATE_DOWN, AST_STATE_RING, AST_STATE_RINGING, AST_STATE_UP, ast_strdupa, ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_udptl_new_with_bindaddr(), ast_uri_decode(), ast_verbose(), AUTH_CHALLENGE_SENT, AUTH_FAKE_AUTH, sip_request::authenticated, sip_pvt::autokillid, bindaddr, build_contact(), build_route(), sip_pvt::callid, sip_pvt::capability, change_hold_state(), check_user(), check_via(), sip_pvt::context, context, copy_request(), DEC_CALL_LIMIT, sip_settings::default_context, DEFAULT_TRANS_TIMEOUT, dialog_ref(), dialog_unref(), sip_pvt::do_history, do_magic_pickup(), ast_channel::exten, sip_pvt::exten, exten, extract_uri(), FALSE, find_sdp(), sip_pvt::flags, get_destination(), get_header(), get_ip_and_port_from_sdp(), get_rdnis(), get_sip_pvt_byid_locked(), sip_pvt::glareinvite, global_max_se, global_t38_maxdatagram, handle_invite_replaces(), ast_channel::hangupcause, sip_request::headers, sip_request::ignore, INC_CALL_LIMIT, sip_pvt::initreq, INV_COMPLETED, INV_CONFIRMED, INV_PROCEEDING, INV_TERMINATED, sip_pvt::invitestate, sip_pvt::jointcapability, sip_pvt::lastinvite, LOG_ERROR, LOG_NOTICE, LOG_WARNING, make_our_tag(), sip_request::method, msg, ast_channel::name, sip_pvt::owner, parse_minse(), parse_ok_contact(), parse_session_expires(), parse_sip_options(), sip_settings::pedanticsipchecking, sip_pvt::peername, sip_pvt::pendinginvite, process_sdp(), sip_pvt::refer, sip_refer::refer_call, REQ_OFFSET_TO_STR, sip_pvt::reqsipoptions, restart_session_timer(), sip_request::rlPart2, sip_pvt::rtp, S_OR, SDP_AUDIO, SDP_T38_INITIATE, SDP_VIDEO, sip_pvt::session_modify, SESSION_TIMER_MODE_ACCEPT, SESSION_TIMER_MODE_ORIGINATE, SESSION_TIMER_MODE_REFUSE, SESSION_TIMER_REFRESHER_AUTO, SESSION_TIMER_REFRESHER_UAS, set_t38_capabilities(), sip_alreadygone(), sip_cancel_destroy(), sip_cfg, SIP_DTMF, SIP_DTMF_RFC2833, SIP_INVITE, sip_methods, sip_new(), SIP_OPT_REPLACES, SIP_OPT_TIMER, SIP_OUTGOING, SIP_PAGE2_ALLOWOVERLAP, SIP_PAGE2_CALL_ONHOLD, SIP_PAGE2_DIALOG_ESTABLISHED, SIP_PAGE2_RFC2833_COMPENSATE, SIP_PAGE2_T38SUPPORT, sip_pvt_lock, sip_pvt_unlock, sip_refer_allocate(), sip_scheddestroy(), sip_st_alloc(), sip_t38_abort(), sip_uri_cmp(), sip_pvt::sipoptions, sip_st_dlg::st_active, sip_st_dlg::st_active_peer_ua, sip_st_dlg::st_expirys, st_get_mode(), st_get_refresher(), st_get_se(), sip_st_dlg::st_interval, sip_st_dlg::st_ref, start_session_timer(), t38properties::state, sip_pvt::stimer, strcasestr(), strsep(), sip_pvt::t38, T38_DISABLED, T38_ENABLED, sip_pvt::t38_maxdatagram, T38_PEER_REINVITE, sip_pvt::t38id, sip_pvt::tag, cfsip_methods::text, sip_pvt::theirtag, transmit_fake_auth_response(), transmit_provisional_response(), transmit_response(), transmit_response_reliable(), transmit_response_with_minse(), transmit_response_with_sdp(), transmit_response_with_t38_sdp(), transmit_response_with_unsupported(), TRUE, sip_pvt::udptl, update_call_counter(), sip_pvt::username, sip_pvt::vrtp, XMIT_CRITICAL, XMIT_RELIABLE, and XMIT_UNRELIABLE.

Referenced by handle_incoming().

{
   int res = 1;
   int gotdest;
   const char *p_replaces;
   char *replace_id = NULL;
   int refer_locked = 0;
   const char *required;
   unsigned int required_profile = 0;
   struct ast_channel *c = NULL;    /* New channel */
   int reinvite = 0;
   int rtn;

   const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
   const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
   int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
   int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
   int st_active = FALSE;          /* Session-Timer on/off boolean                             */
   int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
   enum st_refresher st_ref;       /* Session-Timer session refresher                          */
   int dlg_min_se = -1;
   struct {
      char exten[AST_MAX_EXTENSION];
      char context[AST_MAX_CONTEXT];
   } pickup = {
      .exten = "",
   };
   st_ref = SESSION_TIMER_REFRESHER_AUTO;

   /* Find out what they support */
   if (!p->sipoptions) {
      const char *supported = get_header(req, "Supported");
      if (!ast_strlen_zero(supported))
         parse_sip_options(p, supported);
   }

   /* Find out what they require */
   required = get_header(req, "Require");
   if (!ast_strlen_zero(required)) {
      required_profile = parse_sip_options(NULL, required);
      if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
         /* At this point we only support REPLACES and Session-Timer */
         transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
         ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
         p->invitestate = INV_COMPLETED;
         if (!p->lastinvite)
            sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
         res = -1;
         goto request_invite_cleanup;
      }
   }

   /* The option tags may be present in Supported: or Require: headers.
   Include the Require: option tags for further processing as well */
   p->sipoptions |= required_profile;
   p->reqsipoptions = required_profile;

   /* Check if this is a loop */
   if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
      /* This is a call to ourself.  Send ourselves an error code and stop
         processing immediately, as SIP really has no good mechanism for
         being able to call yourself */
      /* If pedantic is on, we need to check the tags. If they're different, this is
         in fact a forked call through a SIP proxy somewhere. */
      int different;
      char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
      char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
      if (sip_cfg.pedanticsipchecking)
         different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
      else
         different = strcmp(initial_rlPart2, this_rlPart2);
      if (!different) {
         transmit_response(p, "482 Loop Detected", req);
         p->invitestate = INV_COMPLETED;
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
         res = 0;
         goto request_invite_cleanup;
      } else {
         /*! This is a spiral. What we need to do is to just change the outgoing INVITE
          * so that it now routes to the new Request URI. Since we created the INVITE ourselves
          * that should be all we need to do.
          * 
          * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
          * correctly instead...
          */
         char *uri = ast_strdupa(this_rlPart2);
         char *at = strchr(uri, '@');
         char *peerorhost;
         ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
         transmit_response(p, "100 Trying", req);
         if (at) {
            *at = '\0';
         }
         /* Parse out "sip:" */
         if ((peerorhost = strchr(uri, ':'))) {
            *peerorhost++ = '\0';
         }
         ast_string_field_set(p, theirtag, NULL);
         /* Treat this as if there were a call forward instead...
          */
         ast_string_field_set(p->owner, call_forward, peerorhost);
         ast_queue_control(p->owner, AST_CONTROL_BUSY);
         res = 0;
         goto request_invite_cleanup;
      }
   }

   if (!req->ignore && p->pendinginvite) {
      if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
         /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
          * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
          * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
          * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
          * credentials based on one we challenged earlier.
          *
          * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
          * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
          * from the previous transaction from the list of outstanding packets.
          */
         __sip_ack(p, p->pendinginvite, 1, 0);
      } else {
         /* We already have a pending invite. Sorry. You are on hold. */
         p->glareinvite = seqno;     /* must hold on to this seqno to process ack and retransmit correctly */
         if (p->rtp && find_sdp(req)) {
            struct sockaddr_in sin;
            if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
               ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
            } else {
               ast_rtp_set_alt_peer(p->rtp, &sin);
            }
            if (p->vrtp) {
               if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
                  ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
               } else {
                  ast_rtp_set_alt_peer(p->vrtp, &sin);
               }
            }
         }
         transmit_response_reliable(p, "491 Request Pending", req);
         ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
         /* Don't destroy dialog here */
         res = 0;
         goto request_invite_cleanup;
      }
   }

   p_replaces = get_header(req, "Replaces");
   if (!ast_strlen_zero(p_replaces)) {
      /* We have a replaces header */
      char *ptr;
      char *fromtag = NULL;
      char *totag = NULL;
      char *start, *to;
      int error = 0;

      if (p->owner) {
         ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
         transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
         /* Do not destroy existing call */
         res = -1;
         goto request_invite_cleanup;
      }

      if (sipdebug)
         ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
      /* Create a buffer we can manipulate */
      replace_id = ast_strdupa(p_replaces);
      ast_uri_decode(replace_id);

      if (!p->refer && !sip_refer_allocate(p)) {
         transmit_response_reliable(p, "500 Server Internal Error", req);
         append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
         p->invitestate = INV_COMPLETED;
         res = -1;
         goto request_invite_cleanup;
      }

      /*  Todo: (When we find phones that support this)
         if the replaces header contains ";early-only"
         we can only replace the call in early
         stage, not after it's up.

         If it's not in early mode, 486 Busy.
      */

      /* Skip leading whitespace */
      replace_id = ast_skip_blanks(replace_id);

      start = replace_id;
      while ( (ptr = strsep(&start, ";")) ) {
         ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
         if ( (to = strcasestr(ptr, "to-tag=") ) )
            totag = to + 7;   /* skip the keyword */
         else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
            fromtag = to + 9; /* skip the keyword */
            fromtag = strsep(&fromtag, "&"); /* trim what ? */
         }
      }

      if (sipdebug)
         ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
                 replace_id,
                 fromtag ? fromtag : "<no from tag>",
                 totag ? totag : "<no to tag>");

      /* Try to find call that we are replacing.
         If we have a Replaces header, we need to cancel that call if we succeed with this call.
         First we cheat a little and look for a magic call-id from phones that support
         dialog-info+xml so we can do technology independent pickup... */
      if (strncmp(replace_id, "pickup-", 7) == 0) {
         struct sip_pvt *subscription = NULL;
         replace_id += 7; /* Worst case we are looking at \0 */

         if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
            ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
            transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
            error = 1;
         } else {
            ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
            ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
            ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
            sip_pvt_unlock(subscription);
            if (subscription->owner) {
               ast_channel_unlock(subscription->owner);
            }
         }
      }

      /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
      if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
         ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
         transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
         error = 1;
      } else {
         refer_locked = 1;
      }

      /* The matched call is the call from the transferer to Asterisk .
         We want to bridge the bridged part of the call to the 
         incoming invite, thus taking over the refered call */

      if (p->refer->refer_call == p) {
         ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
         p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
         transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
         error = 1;
      }

      if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
         /* Oops, someting wrong anyway, no owner, no call */
         ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
         /* Check for better return code */
         transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
         error = 1;
      }

      if (!error && ast_strlen_zero(pickup.exten) && p->refer->refer_call->owner->_state != AST_STATE_RINGING && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP) {
         ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
         transmit_response_reliable(p, "603 Declined (Replaces)", req);
         error = 1;
      }

      if (error) {   /* Give up this dialog */
         append_history(p, "Xfer", "INVITE/Replace Failed.");
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
         sip_pvt_unlock(p);
         if (p->refer->refer_call) {
            sip_pvt_unlock(p->refer->refer_call);
            if (p->refer->refer_call->owner) {
               ast_channel_unlock(p->refer->refer_call->owner);
            }
         }
         refer_locked = 0;
         p->invitestate = INV_COMPLETED;
         res = -1;
         goto request_invite_cleanup;
      }
   }

   /* Check if this is an INVITE that sets up a new dialog or
      a re-invite in an existing dialog */

   if (!req->ignore) {
      int newcall = (p->initreq.headers ? TRUE : FALSE);

      if (sip_cancel_destroy(p))
         ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
      /* This also counts as a pending invite */
      p->pendinginvite = seqno;
      check_via(p, req);

      copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
      if (sipdebug)
         ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
      if (!p->owner) {  /* Not a re-invite */
         if (debug)
            ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
         if (newcall)
            append_history(p, "Invite", "New call: %s", p->callid);
         parse_ok_contact(p, req);
      } else { /* Re-invite on existing call */
         ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
         /* Handle SDP here if we already have an owner */
         if (find_sdp(req)) {
            if (process_sdp(p, req, SDP_T38_INITIATE)) {
               transmit_response_reliable(p, "488 Not acceptable here", req);
               if (!p->lastinvite)
                  sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
               res = -1;
               goto request_invite_cleanup;
            }
            ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
         } else {
            p->jointcapability = p->capability;
            ast_debug(1, "Hm....  No sdp for the moment\n");
            /* Some devices signal they want to be put off hold by sending a re-invite
               *without* an SDP, which is supposed to mean "Go back to your state"
               and since they put os on remote hold, we go back to off hold */
            if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
               ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
               /* Activate a re-invite */
               ast_queue_frame(p->owner, &ast_null_frame);
               change_hold_state(p, req, FALSE, 0);
            }
         }
         if (p->do_history) /* This is a response, note what it was for */
            append_history(p, "ReInv", "Re-invite received");
      }
   } else if (debug)
      ast_verbose("Ignoring this INVITE request\n");

   if (!p->lastinvite && !req->ignore && !p->owner) {
      /* This is a new invite */
      /* Handle authentication if this is our first invite */
      res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
      if (res == AUTH_CHALLENGE_SENT) {
         p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
         res = 0;
         goto request_invite_cleanup;
      }
      if (res < 0) { /* Something failed in authentication */
         if (res == AUTH_FAKE_AUTH) {
            ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
            transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
         } else {
            ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
            transmit_response_reliable(p, "403 Forbidden", req);
         }
         p->invitestate = INV_COMPLETED;
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
         ast_string_field_set(p, theirtag, NULL);
         res = 0;
         goto request_invite_cleanup;
      }

      /* If T38 is needed but not present, then make it magically appear */
      if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
         if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
            p->t38_maxdatagram = global_t38_maxdatagram;
            set_t38_capabilities(p);
         } else {
            /* udptl creation failed, T38 can not be supported on this dialog */
            ast_debug(1, "UDPTL creation failed on dialog.\n");
            ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
         }
      }

      req->authenticated = 1;

      /* We have a succesful authentication, process the SDP portion if there is one */
      if (find_sdp(req)) {
         if (process_sdp(p, req, SDP_T38_INITIATE)) {
            /* Unacceptable codecs */
            transmit_response_reliable(p, "488 Not acceptable here", req);
            p->invitestate = INV_COMPLETED;
            sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
            ast_debug(1, "No compatible codecs for this SIP call.\n");
            res = -1;
            goto request_invite_cleanup;
         }
      } else { /* No SDP in invite, call control session */
         p->jointcapability = p->capability;
         ast_debug(2, "No SDP in Invite, third party call control\n");
      }

      /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
      /* This seems redundant ... see !p-owner above */
      if (p->owner)
         ast_queue_frame(p->owner, &ast_null_frame);


      /* Initialize the context if it hasn't been already */
      if (ast_strlen_zero(p->context))
         ast_string_field_set(p, context, sip_cfg.default_context);


      /* Check number of concurrent calls -vs- incoming limit HERE */
      ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
      if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
         if (res < 0) {
            ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
            transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
            sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
            p->invitestate = INV_COMPLETED;
         }
         res = 0;
         goto request_invite_cleanup;
      }
      gotdest = get_destination(p, NULL); /* Get destination right away */
      get_rdnis(p, NULL);        /* Get redirect information */
      extract_uri(p, req);       /* Get the Contact URI */
      build_contact(p);       /* Build our contact header */

      if (p->rtp) {
         ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
         ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
      }

      if (!replace_id && gotdest) { /* No matching extension found */
         if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
            transmit_response_reliable(p, "484 Address Incomplete", req);
         else {
            char *decoded_exten = ast_strdupa(p->exten);

            transmit_response_reliable(p, "404 Not Found", req);
            ast_uri_decode(decoded_exten);
            ast_log(LOG_NOTICE, "Call from '%s' to extension"
               " '%s' rejected because extension not found in context '%s'.\n",
               S_OR(p->username, p->peername), decoded_exten, p->context);
         }
         p->invitestate = INV_COMPLETED;
         update_call_counter(p, DEC_CALL_LIMIT);
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
         res = 0;
         goto request_invite_cleanup;
      } else {

         /* If no extension was specified, use the s one */
         /* Basically for calling to IP/Host name only */
         if (ast_strlen_zero(p->exten))
            ast_string_field_set(p, exten, "s");
         /* Initialize our tag */

         make_our_tag(p->tag, sizeof(p->tag));
         /* First invitation - create the channel.  Allocation
          * failures are handled below. */
         c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
         *recount = 1;

         /* Save Record-Route for any later requests we make on this dialogue */
         build_route(p, req, 0);

         if (c) {
            /* Pre-lock the call */
            ast_channel_lock(c);
         }
      }
   } else {
      if (sipdebug) {
         if (!req->ignore)
            ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
         else
            ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
      }
      if (!req->ignore)
         reinvite = 1;
      c = p->owner;
   }

   /* Session-Timers */
   if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
      /* The UAC has requested session-timers for this session. Negotiate
      the session refresh interval and who will be the refresher */
      ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");

      /* Allocate Session-Timers struct w/in the dialog */
      if (!p->stimer)
         sip_st_alloc(p);

      /* Parse the Session-Expires header */
      p_uac_se_hdr = get_header(req, "Session-Expires");
      rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
      if (rtn != 0) {
         transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
         p->invitestate = INV_COMPLETED;
         if (!p->lastinvite) {
            sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
         }
         res = -1;
         goto request_invite_cleanup;
      }

      /* Parse the Min-SE header */
      p_uac_min_se = get_header(req, "Min-SE");
      if (!ast_strlen_zero(p_uac_min_se)) {
         rtn = parse_minse(p_uac_min_se, &uac_min_se); 
         if (rtn != 0) {
            transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
            p->invitestate = INV_COMPLETED;
            if (!p->lastinvite) {
               sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
            }
            res = -1;
            goto request_invite_cleanup;
         }
      }

      dlg_min_se = st_get_se(p, FALSE);
      switch (st_get_mode(p)) {
      case SESSION_TIMER_MODE_ACCEPT:
      case SESSION_TIMER_MODE_ORIGINATE:
         if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
            transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
            p->invitestate = INV_COMPLETED;
            if (!p->lastinvite) {
               sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
            }
            res = -1;
            goto request_invite_cleanup;
         }

         p->stimer->st_active_peer_ua = TRUE;
         st_active = TRUE;
         if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
            st_ref = st_get_refresher(p);
         }

         if (uac_max_se > 0) {
            int dlg_max_se = st_get_se(p, TRUE);
            if (dlg_max_se >= uac_min_se) {
               st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
            } else {
               st_interval = uac_max_se;
            }
         } else {
            /* Set to default max value */
            st_interval = global_max_se;
         }
         break;

      case SESSION_TIMER_MODE_REFUSE:
         if (p->reqsipoptions & SIP_OPT_TIMER) {
            transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
            ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
            p->invitestate = INV_COMPLETED;
            if (!p->lastinvite) {
               sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
            }
            res = -1;
            goto request_invite_cleanup;
         }
         break;

      default:
         ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
         break;
      }
   } else {
      /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
      (based on session-timer-mode in sip.conf) whether to run session-timers for
      this session or not. */
      switch (st_get_mode(p)) {
      case SESSION_TIMER_MODE_ORIGINATE:
         st_active = TRUE;
         st_interval = st_get_se(p, TRUE);
         st_ref = SESSION_TIMER_REFRESHER_UAS;
         p->stimer->st_active_peer_ua = FALSE;
         break;

      default:
         break;
      }
   }

   if (reinvite == 0) {
      /* Session-Timers: Start session refresh timer based on negotiation/config */
      if (st_active == TRUE) {
         p->stimer->st_active   = TRUE;
         p->stimer->st_interval = st_interval;
         p->stimer->st_ref      = st_ref;
         start_session_timer(p);
      }
   } else {
      if (p->stimer->st_active == TRUE) {
         /* Session-Timers:  A re-invite request sent within a dialog will serve as 
         a refresh request, no matter whether the re-invite was sent for refreshing 
         the session or modifying it.*/
         ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);

         /* The UAC may be adjusting the session-timers mid-session */
         if (st_interval > 0) {
            p->stimer->st_interval = st_interval;
            p->stimer->st_ref      = st_ref;
         }

         restart_session_timer(p);
         if (p->stimer->st_expirys > 0) {
            p->stimer->st_expirys--;
         }
      }
   }

   if (!req->ignore && p)
      p->lastinvite = seqno;

   if (c && replace_id) {  /* Attended transfer or call pickup - we're the target */
      if (!ast_strlen_zero(pickup.exten)) {
         append_history(p, "Xfer", "INVITE/Replace received");

         /* Let the caller know we're giving it a shot */
         transmit_response(p, "100 Trying", req);
         p->invitestate = INV_PROCEEDING;
         ast_setstate(c, AST_STATE_RING);

         /* Do the pickup itself */
         ast_channel_unlock(c);
         *nounlock = 1;
         do_magic_pickup(c, pickup.exten, pickup.context);

         /* Now we're either masqueraded or we failed to pickup, in either case we... */
         sip_pvt_unlock(p);
         ast_hangup(c);
         sip_pvt_lock(p);

         res = 0;
         goto request_invite_cleanup;
      } else {
         /* Go and take over the target call */
         if (sipdebug)
            ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
         res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
         refer_locked = 0;
         goto request_invite_cleanup;
      }
   }


   if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
      enum ast_channel_state c_state = c->_state;

      if (c_state != AST_STATE_UP && reinvite &&
         (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
         /* If these conditions are true, and the channel is still in the 'ringing'
          * state, then this likely means that we have a situation where the initial
          * INVITE transaction has completed *but* the channel's state has not yet been
          * changed to UP. The reason this could happen is if the reinvite is received
          * on the SIP socket prior to an application calling ast_read on this channel
          * to read the answer frame we earlier queued on it. In this case, the reinvite
          * is completely legitimate so we need to handle this the same as if the channel 
          * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
          */
         c_state = AST_STATE_UP;
      }

      switch(c_state) {
      case AST_STATE_DOWN:
         ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
         transmit_provisional_response(p, "100 Trying", req, 0);
         p->invitestate = INV_PROCEEDING;
         ast_setstate(c, AST_STATE_RING);
         if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
            enum ast_pbx_result result;

            result = ast_pbx_start(c);

            switch(result) {
            case AST_PBX_FAILED:
               ast_log(LOG_WARNING, "Failed to start PBX :(\n");
               p->invitestate = INV_COMPLETED;
               transmit_response_reliable(p, "503 Unavailable", req);
               break;
            case AST_PBX_CALL_LIMIT:
               ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
               p->invitestate = INV_COMPLETED;
               transmit_response_reliable(p, "480 Temporarily Unavailable", req);
               break;
            case AST_PBX_SUCCESS:
               /* nothing to do */
               break;
            }

            if (result) {

               /* Unlock locks so ast_hangup can do its magic */
               ast_channel_unlock(c);
               sip_pvt_unlock(p);
               ast_hangup(c);
               sip_pvt_lock(p);
               c = NULL;
            }
         } else { /* Pickup call in call group */
            ast_channel_unlock(c);
            *nounlock = 1;
            if (ast_pickup_call(c)) {
               ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
               transmit_response_reliable(p, "503 Unavailable", req);
               sip_alreadygone(p);
               /* Unlock locks so ast_hangup can do its magic */
               sip_pvt_unlock(p);
               c->hangupcause = AST_CAUSE_CALL_REJECTED;
            } else {
               sip_pvt_unlock(p);
               ast_setstate(c, AST_STATE_DOWN);
               c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
            }
            p->invitestate = INV_COMPLETED;
            ast_hangup(c);
            sip_pvt_lock(p);
            c = NULL;
         }
         break;
      case AST_STATE_RING:
         transmit_provisional_response(p, "100 Trying", req, 0);
         p->invitestate = INV_PROCEEDING;
         break;
      case AST_STATE_RINGING:
         transmit_provisional_response(p, "180 Ringing", req, 0);
         p->invitestate = INV_PROCEEDING;
         break;
      case AST_STATE_UP:
         ast_debug(2, "%s: This call is UP.... \n", c->name);

         transmit_response(p, "100 Trying", req);

         if (p->t38.state == T38_PEER_REINVITE) {
            p->t38id = ast_sched_add(sched, 5000, sip_t38_abort, dialog_ref(p, "passing dialog ptr into sched structure based on t38id for sip_t38_abort."));
         } else if (p->t38.state == T38_ENABLED) {
            ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
            transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
         } else if (p->t38.state == T38_DISABLED) {
            /* If this is not a re-invite or something to ignore - it's critical */
            ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
            transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE); 
         }

         p->invitestate = INV_TERMINATED;
         break;
      default:
         ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
         transmit_response(p, "100 Trying", req);
         break;
      }
   } else {
      if (p && (p->autokillid == -1)) {
         const char *msg;

         if (!p->jointcapability)
            msg = "488 Not Acceptable Here (codec error)";
         else {
            ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
            msg = "503 Unavailable";
         }
         transmit_response_reliable(p, msg, req);
         p->invitestate = INV_COMPLETED;
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      }
   }

request_invite_cleanup:

   if (refer_locked && p->refer && p->refer->refer_call) {
      sip_pvt_unlock(p->refer->refer_call);
      if (p->refer->refer_call->owner) {
         ast_channel_unlock(p->refer->refer_call->owner);
      }
   }

   return res;
}
static int handle_request_message ( struct sip_pvt p,
struct sip_request req 
) [static]

Handle incoming MESSAGE request.

Definition at line 21763 of file chan_sip.c.

References ast_verbose(), sip_request::debug, sip_request::ignore, receive_message(), and transmit_response().

Referenced by handle_incoming().

{
   if (!req->ignore) {
      if (req->debug)
         ast_verbose("Receiving message!\n");
      receive_message(p, req);
   } else
      transmit_response(p, "202 Accepted", req);
   return 1;
}
static int handle_request_notify ( struct sip_pvt p,
struct sip_request req,
struct sockaddr_in *  sin,
int  seqno,
char *  e 
) [static]

Handle incoming notifications.

Definition at line 19577 of file chan_sip.c.

References ast_debug, AST_EVENT_IE_CONTEXT, AST_EVENT_IE_END, AST_EVENT_IE_MAILBOX, AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_STR, AST_EVENT_IE_PLTYPE_UINT, AST_EVENT_MWI, ast_event_new(), ast_event_queue_and_cache(), ast_log(), ast_skip_blanks(), ast_strdupa, ast_strlen_zero(), buf, sip_pvt::callid, DEFAULT_TRANS_TIMEOUT, FALSE, get_body(), get_header(), get_msg_text(), sip_pvt::lastinvite, LOG_NOTICE, LOG_WARNING, sip_subscription_mwi::mailbox, sip_pvt::mwi, sip_scheddestroy(), strsep(), transmit_response(), and TRUE.

Referenced by handle_incoming().

{
   /* This is mostly a skeleton for future improvements */
   /* Mostly created to return proper answers on notifications on outbound REFER's */
   int res = 0;
   const char *event = get_header(req, "Event");
   char *eventid = NULL;
   char *sep;

   if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
      *sep++ = '\0';
      eventid = sep;
   }
   
   if (sipdebug)
      ast_debug(2, "Got NOTIFY Event: %s\n", event);

   if (!strcmp(event, "refer")) {
      /* Save nesting depth for now, since there might be other events we will
         support in the future */

      /* Handle REFER notifications */

      char buf[1024];
      char *cmd, *code;
      int respcode;
      int success = TRUE;

      /* EventID for each transfer... EventID is basically the REFER cseq 

       We are getting notifications on a call that we transfered
       We should hangup when we are getting a 200 OK in a sipfrag
       Check if we have an owner of this event */
      
      /* Check the content type */
      if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
         /* We need a sipfrag */
         transmit_response(p, "400 Bad request", req);
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
         return -1;
      }

      /* Get the text of the attachment */
      if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
         ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
         transmit_response(p, "400 Bad request", req);
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
         return -1;
      }

      /*
      From the RFC...
      A minimal, but complete, implementation can respond with a single
      NOTIFY containing either the body:
         SIP/2.0 100 Trying
      
      if the subscription is pending, the body:
         SIP/2.0 200 OK
      if the reference was successful, the body:
         SIP/2.0 503 Service Unavailable
      if the reference failed, or the body:
         SIP/2.0 603 Declined

      if the REFER request was accepted before approval to follow the
      reference could be obtained and that approval was subsequently denied
      (see Section 2.4.7).
      
      If there are several REFERs in the same dialog, we need to
      match the ID of the event header...
      */
      ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
      cmd = ast_skip_blanks(buf);
      code = cmd;
      /* We are at SIP/2.0 */
      while(*code && (*code > 32)) {   /* Search white space */
         code++;
      }
      *code++ = '\0';
      code = ast_skip_blanks(code);
      sep = code;
      sep++;
      while(*sep && (*sep > 32)) {  /* Search white space */
         sep++;
      }
      *sep++ = '\0';       /* Response string */
      respcode = atoi(code);
      switch (respcode) {
      case 100:   /* Trying: */
      case 101:   /* dialog establishment */
         /* Don't do anything yet */
         break;
      case 183:   /* Ringing: */
         /* Don't do anything yet */
         break;
      case 200:   /* OK: The new call is up, hangup this call */
         /* Hangup the call that we are replacing */
         break;
      case 301: /* Moved permenantly */
      case 302: /* Moved temporarily */
         /* Do we get the header in the packet in this case? */
         success = FALSE;
         break;
      case 503:   /* Service Unavailable: The new call failed */
            /* Cancel transfer, continue the call */
         success = FALSE;
         break;
      case 603:   /* Declined: Not accepted */
            /* Cancel transfer, continue the current call */
         success = FALSE;
         break;
      }
      if (!success) {
         ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
      }
      
      /* Confirm that we received this packet */
      transmit_response(p, "200 OK", req);
   } else if (p->mwi && !strcmp(event, "message-summary")) {
      char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));

      if (!ast_strlen_zero(c)) {
         char *old = strsep(&c, " ");
         char *new = strsep(&old, "/");
         struct ast_event *event;

         if ((event = ast_event_new(AST_EVENT_MWI,
                     AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
                     AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
                     AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
                     AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
                     AST_EVENT_IE_END))) {
            ast_event_queue_and_cache(event);
         }
      }

      transmit_response(p, "200 OK", req);
   } else if (!strcmp(event, "keep-alive")) {
       /* Used by Sipura/Linksys for NAT pinhole,
        * just confirm that we received the packet. */
      transmit_response(p, "200 OK", req);
   } else {
      /* We don't understand this event. */
      transmit_response(p, "489 Bad event", req);
      res = -1;
   }

   if (!p->lastinvite)
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);

   return res;
}
static int handle_request_options ( struct sip_pvt p,
struct sip_request req 
) [static]

Handle incoming OPTIONS request An OPTIONS request should be answered like an INVITE from the same UA, including SDP.

XXX get_destination assumes we're already authenticated. This means that a request from a known device (peer) will end up in the wrong context if this is out-of-dialog. However, we want to handle OPTIONS as light as possible, so we might want to have a configuration option whether we care or not. Some devices use this for testing capabilities, which means that we need to match device to answer with proper capabilities (including SDP).

Todo:
Fix handle_request_options device handling with optional authentication (this needs to be fixed in 1.4 as well)

Definition at line 19732 of file chan_sip.c.

References ast_shutting_down(), ast_string_field_set, ast_strlen_zero(), build_contact(), context, sip_pvt::context, sip_settings::default_context, DEFAULT_TRANS_TIMEOUT, get_destination(), sip_pvt::lastinvite, sip_cfg, sip_scheddestroy(), and transmit_response_with_allow().

Referenced by handle_incoming().

{
   int res;

   /*! XXX get_destination assumes we're already authenticated. This means that a request from
      a known device (peer) will end up in the wrong context if this is out-of-dialog.
      However, we want to handle OPTIONS as light as possible, so we might want to have
      a configuration option whether we care or not. Some devices use this for testing
      capabilities, which means that we need to match device to answer with proper 
      capabilities (including SDP).
      \todo Fix handle_request_options device handling with optional authentication
         (this needs to be fixed in 1.4 as well)
   */

   if (p->lastinvite) {
      /* if this is a request in an active dialog, just confirm that the dialog exists. */
      transmit_response_with_allow(p, "200 OK", req, 0);
      return 0;
   }

   res = get_destination(p, req);
   build_contact(p);

   if (ast_strlen_zero(p->context))
      ast_string_field_set(p, context, sip_cfg.default_context);

   if (ast_shutting_down())
      transmit_response_with_allow(p, "503 Unavailable", req, 0);
   else if (res < 0)
      transmit_response_with_allow(p, "404 Not Found", req, 0);
   else 
      transmit_response_with_allow(p, "200 OK", req, 0);

   /* Destroy if this OPTIONS was the opening request, but not if
      it's in the middle of a normal call flow. */
   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);

   return res;
}
static int handle_request_refer ( struct sip_pvt p,
struct sip_request req,
int  debug,
int  seqno,
int *  nounlock 
) [static]

Definition at line 21171 of file chan_sip.c.

References sip_settings::allow_external_domains, sip_pvt::allowtransfer, append_history, ast_async_goto(), ast_bridged_channel(), AST_CAUSE_NORMAL_CLEARING, ast_channel_unlock, ast_clear_flag, AST_CONTROL_UNHOLD, ast_debug, ast_indicate(), AST_LIST_EMPTY, ast_parking_ext(), ast_queue_control(), ast_set_flag, ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_verbose(), sip_refer::attendedtransfer, sip_pvt::callid, sip_dual::chan1, sip_dual::chan2, check_sip_domain(), context, sip_pvt::context, copy_request(), sip_request::data, sip_request::debug, sip_settings::default_context, EVENT_FLAG_CALL, FALSE, sip_pvt::flags, get_refer_info(), ast_channel::hangupcause, sip_request::ignore, local_attended_transfer(), sip_refer::localtransfer, manager_event, ast_channel::name, sip_pvt::owner, pbx_builtin_setvar_helper(), pvt_set_needdestroy(), sip_pvt::refer, REFER_200OK, REFER_FAILED, REFER_SENT, sip_refer::refer_to, sip_refer::refer_to_context, sip_refer::refer_to_domain, sip_refer::referred_by, sip_refer::replaces_callid, sip_refer::replaces_callid_fromtag, sip_refer::replaces_callid_totag, sip_dual::req, sip_alreadygone(), sip_cfg, SIP_DEFER_BYE_ON_TRANSFER, SIP_GOTREFER, SIP_OUTGOING, sip_park(), sip_refer_allocate(), SIPBUFSIZE, sip_refer::status, TRANSFER_CLOSED, transmit_notify_with_sipfrag(), transmit_response(), TRUE, and ast_channel::uniqueid.

Referenced by handle_incoming().

{
   struct sip_dual current;   /* Chan1: Call between asterisk and transferer */
               /* Chan2: Call between asterisk and transferee */

   int res = 0;
   current.req.data = NULL;

   if (req->debug)
      ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n", p->callid, ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");

   if (!p->owner) {
      /* This is a REFER outside of an existing SIP dialog */
      /* We can't handle that, so decline it */
      ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
      transmit_response(p, "603 Declined (No dialog)", req);
      if (!req->ignore) {
         append_history(p, "Xfer", "Refer failed. Outside of dialog.");
         sip_alreadygone(p);
         pvt_set_needdestroy(p, "outside of dialog");
      }
      return 0;
   }


   /* Check if transfer is allowed from this device */
   if (p->allowtransfer == TRANSFER_CLOSED ) {
      /* Transfer not allowed, decline */
      transmit_response(p, "603 Declined (policy)", req);
      append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
      /* Do not destroy SIP session */
      return 0;
   }

   if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
      /* Already have a pending REFER */
      transmit_response(p, "491 Request pending", req);
      append_history(p, "Xfer", "Refer failed. Request pending.");
      return 0;
   }

   /* Allocate memory for call transfer data */
   if (!p->refer && !sip_refer_allocate(p)) {
      transmit_response(p, "500 Internal Server Error", req);
      append_history(p, "Xfer", "Refer failed. Memory allocation error.");
      return -3;
   }

   res = get_refer_info(p, req); /* Extract headers */

   p->refer->status = REFER_SENT;

   if (res != 0) {
      switch (res) {
      case -2: /* Syntax error */
         transmit_response(p, "400 Bad Request (Refer-to missing)", req);
         append_history(p, "Xfer", "Refer failed. Refer-to missing.");
         if (req->debug)
            ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
         break;
      case -3:
         transmit_response(p, "603 Declined (Non sip: uri)", req);
         append_history(p, "Xfer", "Refer failed. Non SIP uri");
         if (req->debug)
            ast_debug(1, "SIP transfer to non-SIP uri denied\n");
         break;
      default:
         /* Refer-to extension not found, fake a failed transfer */
         transmit_response(p, "202 Accepted", req);
         append_history(p, "Xfer", "Refer failed. Bad extension.");
         transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
         ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
         if (req->debug)
            ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
         break;
      } 
      return 0;
   }
   if (ast_strlen_zero(p->context))
      ast_string_field_set(p, context, sip_cfg.default_context);

   /* If we do not support SIP domains, all transfers are local */
   if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
      p->refer->localtransfer = 1;
      if (sipdebug)
         ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
   } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
      /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
      p->refer->localtransfer = 1;
   } else if (sipdebug)
         ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);

   /* Is this a repeat of a current request? Ignore it */
   /* Don't know what else to do right now. */
   if (req->ignore) 
      return res;

   /* If this is a blind transfer, we have the following
   channels to work with:
   - chan1, chan2: The current call between transferer and transferee (2 channels)
   - target_channel: A new call from the transferee to the target (1 channel)
   We need to stay tuned to what happens in order to be able
   to bring back the call to the transferer */

   /* If this is a attended transfer, we should have all call legs within reach:
   - chan1, chan2: The call between the transferer and transferee (2 channels)
   - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
   We want to bridge chan2 with targetcall_pvt!
   
   The replaces call id in the refer message points
   to the call leg between Asterisk and the transferer.
   So we need to connect the target and the transferee channel
   and hangup the two other channels silently 
   
   If the target is non-local, the call ID could be on a remote
   machine and we need to send an INVITE with replaces to the
   target. We basically handle this as a blind transfer
   and let the sip_call function catch that we need replaces
   header in the INVITE.
   */


   /* Get the transferer's channel */
   current.chan1 = p->owner;

   /* Find the other part of the bridge (2) - transferee */
   current.chan2 = ast_bridged_channel(current.chan1);
   
   if (sipdebug)
      ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n", p->refer->attendedtransfer ? "attended" : "blind", current.chan1->name, current.chan2 ? current.chan2->name : "<none>");

   if (!current.chan2 && !p->refer->attendedtransfer) {
      /* No bridged channel, propably IVR or echo or similar... */
      /* Guess we should masquerade or something here */
      /* Until we figure it out, refuse transfer of such calls */
      if (sipdebug)
         ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
      p->refer->status = REFER_FAILED;
      append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
      transmit_response(p, "603 Declined", req);
      return -1;
   }

   if (current.chan2) {
      if (sipdebug)
         ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);

      ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
   }

   ast_set_flag(&p->flags[0], SIP_GOTREFER);

   /* From here on failures will be indicated with NOTIFY requests */
   transmit_response(p, "202 Accepted", req);

   /* Attended transfer: Find all call legs and bridge transferee with target*/
   if (p->refer->attendedtransfer) {
      if ((res = local_attended_transfer(p, &current, req, seqno)))
         return res; /* We're done with the transfer */
      /* Fall through for remote transfers that we did not find locally */
      if (sipdebug)
         ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
      /* Fallthrough if we can't find the call leg internally */
   }


   /* Parking a call */
   if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
      /* Must release c's lock now, because it will not longer be accessible after the transfer! */
      *nounlock = 1;
      ast_channel_unlock(current.chan1);
      copy_request(&current.req, req);
      ast_clear_flag(&p->flags[0], SIP_GOTREFER);
      p->refer->status = REFER_200OK;
      append_history(p, "Xfer", "REFER to call parking.");
      manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransfer2Parking: Yes\r\n",
         current.chan1->name,
         current.chan1->uniqueid,
         p->callid,
         current.chan2->name,
         current.chan2->uniqueid,
         p->refer->refer_to);
      if (sipdebug)
         ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
      if ((res = sip_park(current.chan2, current.chan1, req, seqno))) {
         transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
      }
      return res;
   } 

   /* Blind transfers and remote attended xfers */
   if (current.chan1 && current.chan2) {
      ast_debug(3, "chan1->name: %s\n", current.chan1->name);
      pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
   }
   if (current.chan2) {
      pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
      pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
      pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
      /* One for the new channel */
      pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
      /* Attended transfer to remote host, prepare headers for the INVITE */
      if (p->refer->referred_by) 
         pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
   }
   /* Generate a Replaces string to be used in the INVITE during attended transfer */
   if (!ast_strlen_zero(p->refer->replaces_callid)) {
      char tempheader[SIPBUFSIZE];
      snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid, 
            p->refer->replaces_callid_totag ? ";to-tag=" : "", 
            p->refer->replaces_callid_totag, 
            p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
            p->refer->replaces_callid_fromtag);
      if (current.chan2)
         pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
   }
   /* Must release lock now, because it will not longer
      be accessible after the transfer! */
   *nounlock = 1;
   ast_channel_unlock(current.chan1);

   /* Connect the call */

   /* FAKE ringing if not attended transfer */
   if (!p->refer->attendedtransfer)
      transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE); 

   /* For blind transfer, this will lead to a new call */
   /* For attended transfer to remote host, this will lead to
      a new SIP call with a replaces header, if the dial plan allows it 
   */
   if (!current.chan2) {
      /* We have no bridge, so we're talking with Asterisk somehow */
      /* We need to masquerade this call */
      /* What to do to fix this situation:
         * Set up the new call in a new channel 
         * Let the new channel masq into this channel
         Please add that code here :-)
      */
      p->refer->status = REFER_FAILED;
      transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
      ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
      append_history(p, "Xfer", "Refer failed (only bridged calls).");
      return -1;
   }
   ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */


   /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
      servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
   /* indicate before masquerade so the indication actually makes it to the real channel
      when using local channels with MOH passthru */
   ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
   res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);

   if (!res) {
      manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransferContext: %s\r\n",
         current.chan1->name,
         current.chan1->uniqueid,
         p->callid,
         current.chan2->name,
         current.chan2->uniqueid,
         p->refer->refer_to, p->refer->refer_to_context);
      /* Success  - we have a new channel */
      ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
      transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
      if (p->refer->localtransfer)
         p->refer->status = REFER_200OK;
      if (p->owner)
         p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
      append_history(p, "Xfer", "Refer succeeded.");
      ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
      /* Do not hangup call, the other side do that when we say 200 OK */
      /* We could possibly implement a timer here, auto congestion */
      res = 0;
   } else {
      ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
      ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
      append_history(p, "Xfer", "Refer failed.");
      /* Failure of some kind */
      p->refer->status = REFER_FAILED;
      transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
      ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
      res = -1;
   }
   return res;
}
static int handle_request_register ( struct sip_pvt p,
struct sip_request req,
struct sockaddr_in *  sin,
char *  e 
) [static]

Handle incoming REGISTER request.

Definition at line 22127 of file chan_sip.c.

References append_history, ast_debug, ast_inet_ntoa(), ast_log(), AUTH_ACL_FAILED, AUTH_BAD_TRANSPORT, AUTH_NOT_FOUND, AUTH_PEER_NOT_DYNAMIC, AUTH_SECRET_FAILED, AUTH_UNKNOWN_DOMAIN, AUTH_USERNAME_MISMATCH, sip_request::authenticated, sip_pvt::callid, check_via(), copy_request(), DEFAULT_TRANS_TIMEOUT, get_header(), sip_request::headers, sip_pvt::initreq, LOG_NOTICE, LOG_WARNING, sip_request::method, register_verify(), sip_methods, SIP_REGISTER, sip_scheddestroy(), and cfsip_methods::text.

Referenced by handle_incoming().

{
   enum check_auth_result res;

   /* If this is not the intial request, and the initial request isn't
    * a register, something screwy happened, so bail */
   if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
      ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
      return -1;
   }

   /* Use this as the basis */
   copy_request(&p->initreq, req);
   if (sipdebug)
      ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
   check_via(p, req);
   if ((res = register_verify(p, sin, req, e)) < 0) {
      const char *reason;

      switch (res) {
      case AUTH_SECRET_FAILED:
         reason = "Wrong password";
         break;
      case AUTH_USERNAME_MISMATCH:
         reason = "Username/auth name mismatch";
         break;
      case AUTH_NOT_FOUND:
         reason = "No matching peer found";
         break;
      case AUTH_UNKNOWN_DOMAIN:
         reason = "Not a local domain";
         break;
      case AUTH_PEER_NOT_DYNAMIC:
         reason = "Peer is not supposed to register";
         break;
      case AUTH_ACL_FAILED:
         reason = "Device does not match ACL";
         break;
      case AUTH_BAD_TRANSPORT:
         reason = "Device not configured to use this transport type";
         break;
      default:
         reason = "Unknown failure";
         break;
      }
      ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
         get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
         reason);
      append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
   } else {
      req->authenticated = 1;
      append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
   }

   if (res < 1) {
      /* Destroy the session, but keep us around for just a bit in case they don't
         get our 200 OK */
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
   }
   return res;
}
static int handle_request_subscribe ( struct sip_pvt p,
struct sip_request req,
struct sockaddr_in *  sin,
int  seqno,
char *  e 
) [static]

Handle incoming SUBSCRIBE request.

Definition at line 21787 of file chan_sip.c.

References __get_header(), add_peer_mwi_subs(), sip_settings::allowsubscribe, ao2_lock(), ao2_unlock(), append_history, ast_debug, AST_EXTENSION_REMOVED, ast_extension_state(), ast_extension_state2str(), ast_extension_state_add(), ast_extension_state_del(), ast_inet_ntoa(), AST_LIST_EMPTY, ast_log(), ast_set_flag, ast_strdupa, ast_string_field_build, ast_strlen_zero(), ast_test_flag, ast_verbose(), AUTH_CHALLENGE_SENT, AUTH_FAKE_AUTH, sip_pvt::autokillid, build_contact(), build_route(), sip_pvt::callid, cb_extensionstate(), check_user_full(), check_via(), sip_pvt::context, copy_request(), CPIM_PIDF_XML, sip_request::debug, DIALOG_INFO_XML, dialog_ref(), dialog_unlink_all(), dialog_unref(), sip_pvt::dialogver, sip_pvt::expiry, sip_pvt::exten, FALSE, sip_peer::flags, sip_pvt::flags, get_destination(), get_header(), gettag(), sip_request::headers, sip_request::ignore, sip_pvt::initreq, sip_pvt::lastinvite, sip_pvt::laststate, LOG_DEBUG, LOG_NOTICE, LOG_WARNING, sip_peer::mailboxes, make_our_tag(), max_expiry, sip_request::method, min_expiry, MWI_NOTIFICATION, sip_peer::mwipvt, sip_peer::name, sip_pvt::needdestroy, NONE, option_debug, parse_ok_contact(), PIDF_XML, pvt_set_needdestroy(), ref_peer(), sip_pvt::relatedpeer, sip_pvt::sa, sip_cancel_destroy(), sip_cfg, sip_methods, SIP_PAGE2_ALLOWSUBSCRIBE, SIP_PAGE2_DIALOG_ESTABLISHED, SIP_PAGE2_SUBSCRIBEMWIONLY, sip_scheddestroy(), sip_send_mwi_to_peer(), SIP_SUBSCRIBE, sip_pvt::stateid, sip_pvt::subscribecontext, sip_pvt::subscribed, sip_pvt::subscribeuri, sip_pvt::tag, cfsip_methods::text, transmit_fake_auth_response(), transmit_response(), transmit_response_reliable(), transmit_state_notify(), TRUE, unref_peer(), sip_pvt::useragent, sip_pvt::username, XMIT_UNRELIABLE, and XPIDF_XML.

Referenced by handle_incoming().

{
   int gotdest = 0;
   int res = 0;
   int firststate = AST_EXTENSION_REMOVED;
   struct sip_peer *authpeer = NULL;
   const char *eventheader = get_header(req, "Event");   /* Get Event package name */
   int resubscribe = (p->subscribed != NONE) && !req->ignore;
   char *temp, *event;

   if (p->initreq.headers) {  
      /* We already have a dialog */
      if (p->initreq.method != SIP_SUBSCRIBE) {
         /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
         /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
         transmit_response(p, "403 Forbidden (within dialog)", req);
         /* Do not destroy session, since we will break the call if we do */
         ast_debug(1, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p->callid, sip_methods[p->initreq.method].text);
         return 0;
      } else if (req->debug) {
         if (resubscribe)
            ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
         else
            ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
      }
   }

   /* Check if we have a global disallow setting on subscriptions. 
      if so, we don't have to check peer settings after auth, which saves a lot of processing
   */
   if (!sip_cfg.allowsubscribe) {
      transmit_response(p, "403 Forbidden (policy)", req);
      pvt_set_needdestroy(p, "forbidden");
      return 0;
   }

   if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
      const char *to = get_header(req, "To");
      char totag[128];

      /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
      if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
         if (req->debug)
            ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
         transmit_response(p, "481 Subscription does not exist", req);
         pvt_set_needdestroy(p, "subscription does not exist");
         return 0;
      }

      /* Use this as the basis */
      if (req->debug)
         ast_verbose("Creating new subscription\n");

      copy_request(&p->initreq, req);
      if (sipdebug)
         ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
      check_via(p, req);
      build_route(p, req, 0);
   } else if (req->debug && req->ignore)
      ast_verbose("Ignoring this SUBSCRIBE request\n");

   /* Find parameters to Event: header value and remove them for now */
   if (ast_strlen_zero(eventheader)) {
      transmit_response(p, "489 Bad Event", req);
      ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
      pvt_set_needdestroy(p, "unknown event package in subscribe");
      return 0;
   }

   if ( (strchr(eventheader, ';'))) {
      event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
      temp = strchr(event, ';');       
      *temp = '\0';           /* Remove any options for now */
                     /* We might need to use them later :-) */
   } else
      event = (char *) eventheader;    /* XXX is this legal ? */

   /* Handle authentication if we're new and not a retransmission. We can't just
    * use if !req->ignore, because then we'll end up sending
    * a 200 OK if someone retransmits without sending auth */
   if (p->subscribed == NONE || resubscribe) {
      res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);

      /* if an authentication response was sent, we are done here */
      if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
         return 0;
      if (res < 0) {
         if (res == AUTH_FAKE_AUTH) {
            ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
            transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
         } else {
            ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
            transmit_response_reliable(p, "403 Forbidden", req);
         }

         pvt_set_needdestroy(p, "authentication failed");
         return 0;
      }
   }

   /* At this point, authpeer cannot be NULL. Remember we hold a reference,
    * so we must release it when done.
    * XXX must remove all the checks for authpeer == NULL.
    */

   /* Check if this device  is allowed to subscribe at all */
   if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
      transmit_response(p, "403 Forbidden (policy)", req);
      pvt_set_needdestroy(p, "subscription not allowed");
      if (authpeer)
         unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
      return 0;
   }

   if (strcmp(event, "message-summary")) {
      /* Get destination right away */
      gotdest = get_destination(p, NULL);
   }

   /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
   parse_ok_contact(p, req);

   build_contact(p);
   if (gotdest) {
      transmit_response(p, "404 Not Found", req);
      pvt_set_needdestroy(p, "subscription target not found");
      if (authpeer)
         unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
      return 0;
   }

   /* Initialize tag for new subscriptions */   
   if (ast_strlen_zero(p->tag))
      make_our_tag(p->tag, sizeof(p->tag));

   if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
      unsigned int pidf_xml;
      const char *accept;
      int start = 0;
      enum subscriptiontype subscribed = NONE;
      const char *unknown_acceptheader = NULL;

      if (authpeer)  /* We do not need the authpeer any more */
         unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");

      /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */

      accept = __get_header(req, "Accept", &start);
      while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
         pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;

         /* Older versions of Polycom firmware will claim pidf+xml, but really
          * they only support xpidf+xml. */
         if (pidf_xml && strstr(p->useragent, "Polycom")) {
            subscribed = XPIDF_XML;
         } else if (pidf_xml) {
            subscribed = PIDF_XML;         /* RFC 3863 format */
         } else if (strstr(accept, "application/dialog-info+xml")) {
            subscribed = DIALOG_INFO_XML;
            /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
         } else if (strstr(accept, "application/cpim-pidf+xml")) {
            subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
         } else if (strstr(accept, "application/xpidf+xml")) {
            subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
         } else {
            unknown_acceptheader = accept;
         }
         /* check to see if there is another Accept header present */
         accept = __get_header(req, "Accept", &start);
      }

      if (!start) {
         if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
            transmit_response(p, "489 Bad Event", req);
            ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
               "stateid: %d, laststate: %d, dialogver: %d, subscribecont: "
               "'%s', subscribeuri: '%s'\n",
               p->stateid,
               p->laststate,
               p->dialogver,
               p->subscribecontext,
               p->subscribeuri);
            pvt_set_needdestroy(p, "no Accept header");
            return 0;
         }
         /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
            so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
      } else if (subscribed == NONE) {
         /* Can't find a format for events that we know about */
         char mybuf[200];
         if (!ast_strlen_zero(unknown_acceptheader)) {
            snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
         } else {
            snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
         }
         transmit_response(p, mybuf, req);
         ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
            "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
            "dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
            unknown_acceptheader,
            (int)p->subscribed,
            p->stateid,
            p->laststate,
            p->dialogver,
            p->subscribecontext,
            p->subscribeuri);
         pvt_set_needdestroy(p, "unrecognized format");
         return 0;
      } else {
         p->subscribed = subscribed;
      }
   } else if (!strcmp(event, "message-summary")) {
      int start = 0;
      int found_supported = 0;
      const char *acceptheader;

      acceptheader = __get_header(req, "Accept", &start);
      while (!found_supported && !ast_strlen_zero(acceptheader)) {
         found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
         if (!found_supported && (option_debug > 2)) {
            ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
         }
         acceptheader = __get_header(req, "Accept", &start);
      }
      if (start && !found_supported) {
         /* Format requested that we do not support */
         transmit_response(p, "406 Not Acceptable", req);
         ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
         pvt_set_needdestroy(p, "unknown format");
         if (authpeer)
            unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
         return 0;
      }

      /* Looks like they actually want a mailbox status 
        This version of Asterisk supports mailbox subscriptions
        The subscribed URI needs to exist in the dial plan
        In most devices, this is configurable to the voicemailmain extension you use
      */
      if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
         transmit_response(p, "404 Not found (no mailbox)", req);
         pvt_set_needdestroy(p, "received 404 response");
         ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
         if (authpeer)
            unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
         return 0;
      }

      p->subscribed = MWI_NOTIFICATION;
      if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
         add_peer_mwi_subs(authpeer);
      }
      if (authpeer->mwipvt && authpeer->mwipvt != p) {   /* Destroy old PVT if this is a new one */
         /* We only allow one subscription per peer */
         dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
         authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
         /* sip_destroy(authpeer->mwipvt); */
      }
      if (authpeer->mwipvt)
         dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
      authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");      /* Link from peer to pvt UH- should this be dialog_ref()? */
      if (p->relatedpeer)
         unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
      p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");  /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
      /* Do not release authpeer here */
   } else { /* At this point, Asterisk does not understand the specified event */
      transmit_response(p, "489 Bad Event", req);
      ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
      pvt_set_needdestroy(p, "unknown event package");
      if (authpeer)
         unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
      return 0;
   }

   /* Add subscription for extension state from the PBX core */
   if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
      if (p->stateid > -1) {
         ast_extension_state_del(p->stateid, cb_extensionstate);
         /* we need to dec the refcount, now that the extensionstate is removed */
         dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
      }
      p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
   }

   if (!req->ignore && p)
      p->lastinvite = seqno;
   if (p && !p->needdestroy) {
      p->expiry = atoi(get_header(req, "Expires"));

      /* check if the requested expiry-time is within the approved limits from sip.conf */
      if (p->expiry > max_expiry)
         p->expiry = max_expiry;
      if (p->expiry < min_expiry && p->expiry > 0)
         p->expiry = min_expiry;

      if (sipdebug) {
         if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
            ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
         else
            ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
      }
      if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
         ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
      if (p->expiry > 0)
         sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */

      if (p->subscribed == MWI_NOTIFICATION) {
         ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
         transmit_response(p, "200 OK", req);
         if (p->relatedpeer) {   /* Send first notification */
            ao2_lock(p->relatedpeer); /* was WRLOCK */
            sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
            ao2_unlock(p->relatedpeer);
         }
      } else {

         if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {

            ast_log(LOG_NOTICE, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension.\n", p->exten, p->context, ast_inet_ntoa(p->sa.sin_addr));
            transmit_response(p, "404 Not found", req);
            pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
            return 0;
         }
         ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
         transmit_response(p, "200 OK", req);
         transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
         append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
         /* hide the 'complete' exten/context in the refer_to field for later display */
         ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
         /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */

      }
      if (!p->expiry) {
         pvt_set_needdestroy(p, "forcing expiration");
      }
   }
   return 1;
}
static void handle_response ( struct sip_pvt p,
int  resp,
char *  rest,
struct sip_request req,
int  seqno 
) [static]

Handle SIP response in dialogue.

Note:
only called by handle_incoming

Definition at line 18863 of file chan_sip.c.

References __sip_ack(), __sip_semi_ack(), append_history, AST_CAUSE_PROTOCOL_ERROR, ast_clear_flag, AST_CONTROL_BUSY, AST_CONTROL_CONGESTION, AST_CONTROL_PROGRESS, ast_debug, ast_inet_ntoa(), ast_log(), ast_queue_control(), ast_queue_hangup_with_cause(), ast_set_flag, ast_skip_blanks(), ast_skip_nonblanks(), ast_strdupa, ast_string_field_build, ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_verb, ast_verbose(), sip_invite_param::auth_type, sip_pvt::authname, sip_pvt::authtries, ast_channel::call_forward, sip_pvt::callid, cb_extensionstate(), sip_pvt::context, sip_request::debug, do_proxy_auth(), sip_pvt::exten, FALSE, find_sdp(), find_sip_method(), sip_pvt::flags, get_header(), gettag(), handle_response_invite(), handle_response_notify(), handle_response_peerpoke(), handle_response_refer(), handle_response_register(), handle_response_subscribe(), hangup_sip2cause(), ast_channel::hangupcause, sip_request::ignore, sip_pvt::initreq, sip_pvt::laststate, LOG_NOTICE, LOG_WARNING, MAX_AUTHTRIES, sip_pvt::method, msg, ast_channel::name, sip_pvt::options, sip_pvt::owner, parse_moved_contact(), sip_pvt::pendinginvite, process_sdp(), pvt_set_needdestroy(), sip_pvt::recv, sip_pvt::refer, sip_pvt::registry, sip_pvt::relatedpeer, sip_pvt::sa, SDP_T38_NONE, SIP_ACK, sip_alreadygone(), SIP_BYE, SIP_CANCEL, sip_cancel_destroy(), SIP_INFO, SIP_INVITE, SIP_MESSAGE, sip_methods, SIP_NOTIFY, SIP_OPTIONS, SIP_OUTGOING, SIP_PAGE2_DIALOG_ESTABLISHED, SIP_PAGE2_FORWARD_LOOP_DETECTED, SIP_PAGE2_STATECHANGEQUEUE, SIP_REFER, SIP_REGISTER, SIP_SUBSCRIBE, SIP_TRANSPORT_UDP, sip_pvt::socket, stop_media_flows(), sip_pvt::subscribed, text, sip_pvt::theirtag, transmit_request(), sip_socket::type, sip_pvt::username, and XMIT_UNRELIABLE.

Referenced by handle_incoming().

{
   struct ast_channel *owner;
   int sipmethod;
   int res = 1;
   const char *c = get_header(req, "Cseq");
   /* GCC 4.2 complains if I try to cast c as a char * when passing it to ast_skip_nonblanks, so make a copy of it */
   char *c_copy = ast_strdupa(c);
   /* Skip the Cseq and its subsequent spaces */
   const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));

   if (!msg)
      msg = "";

   sipmethod = find_sip_method(msg);

   owner = p->owner;
   if (owner) 
      owner->hangupcause = hangup_sip2cause(resp);

   if (p->socket.type == SIP_TRANSPORT_UDP) {
      int ack_res;

      /* Acknowledge whatever it is destined for */
      if ((resp >= 100) && (resp <= 199)) {
         ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
      } else {
         ack_res = __sip_ack(p, seqno, 0, sipmethod);
      }

      if (ack_res == FALSE) {
         append_history(p, "Ignore", "Ignoring this retransmit\n");
         return;
      }
   }

   /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
   if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) 
      p->pendinginvite = 0;

   /* Get their tag if we haven't already */
   if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
      char tag[128];

      gettag(req, "To", tag, sizeof(tag));
      ast_string_field_set(p, theirtag, tag);
   }
   /* This needs to be configurable on a channel/peer level,
      not mandatory for all communication. Sadly enough, NAT implementations
      are not so stable so we can always rely on these headers. 
      Temporarily disabled, while waiting for fix.
      Fix assigned to Rizzo :-)
   */
   /* check_via_response(p, req); */

   /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
    * in response to a BYE, then we should end the current dialog
    * and session.  It is known that at least one phone manufacturer
    * potentially will send a 404 in response to a BYE, so we'll be
    * liberal in what we accept and end the dialog and session if we
    * receive any of those responses to a BYE.
    */
   if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
      pvt_set_needdestroy(p, "received 4XX response to a BYE");
      return;
   }

   if (p->relatedpeer && p->method == SIP_OPTIONS) {
      /* We don't really care what the response is, just that it replied back. 
         Well, as long as it's not a 100 response...  since we might
         need to hang around for something more "definitive" */
      if (resp != 100)
         handle_response_peerpoke(p, resp, req);
   } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
      switch(resp) {
      case 100:   /* 100 Trying */
      case 101:   /* 101 Dialog establishment */
      case 183:   /* 183 Session Progress */
      case 180:   /* 180 Ringing */
      case 182:   /* 182 Queued */
         if (sipmethod == SIP_INVITE)
            handle_response_invite(p, resp, rest, req, seqno);
         break;
      case 200:   /* 200 OK */
         p->authtries = 0; /* Reset authentication counter */
         if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
            /* We successfully transmitted a message 
               or a video update request in INFO */
            /* Nothing happens here - the message is inside a dialog */
         } else if (sipmethod == SIP_INVITE) {
            handle_response_invite(p, resp, rest, req, seqno);
         } else if (sipmethod == SIP_NOTIFY) {
            handle_response_notify(p, resp, rest, req, seqno);
         } else if (sipmethod == SIP_REGISTER) {
            res = handle_response_register(p, resp, rest, req, seqno);
         } else if (sipmethod == SIP_SUBSCRIBE) {
            ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
            handle_response_subscribe(p, resp, rest, req, seqno);
         } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
            pvt_set_needdestroy(p, "received 200 response");
            ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
         }
         break;
      case 202:   /* Transfer accepted */
         if (sipmethod == SIP_REFER) 
            handle_response_refer(p, resp, rest, req, seqno);
         break;
      case 401: /* Not www-authorized on SIP method */
      case 407: /* Proxy auth required */
         if (sipmethod == SIP_INVITE)
            handle_response_invite(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_NOTIFY)
            handle_response_notify(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_REFER)
            handle_response_refer(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_SUBSCRIBE)
            handle_response_subscribe(p, resp, rest, req, seqno);
         else if (p->registry && sipmethod == SIP_REGISTER)
            res = handle_response_register(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_BYE) {
            if (p->options)
               p->options->auth_type = resp;
            if (ast_strlen_zero(p->authname)) {
               ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
                     msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
               pvt_set_needdestroy(p, "unable to authenticate BYE");
            } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
               ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
               pvt_set_needdestroy(p, "failed to authenticate BYE");
            }
         } else {
            ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
            pvt_set_needdestroy(p, "received 407 response");
         }
         break;
      case 403: /* Forbidden - we failed authentication */
         if (sipmethod == SIP_INVITE)
            handle_response_invite(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_SUBSCRIBE)
            handle_response_subscribe(p, resp, rest, req, seqno);
         else if (p->registry && sipmethod == SIP_REGISTER) 
            res = handle_response_register(p, resp, rest, req, seqno);
         else {
            ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
            pvt_set_needdestroy(p, "received 403 response");
         }
         break;
      case 404: /* Not found */
         if (p->registry && sipmethod == SIP_REGISTER)
            res = handle_response_register(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_INVITE)
            handle_response_invite(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_SUBSCRIBE)
            handle_response_subscribe(p, resp, rest, req, seqno);
         else if (owner)
            ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
         break;
      case 423: /* Interval too brief */
         if (sipmethod == SIP_REGISTER)
            res = handle_response_register(p, resp, rest, req, seqno);
         break;
      case 408: /* Request timeout - terminate dialog */
         if (sipmethod == SIP_INVITE)
            handle_response_invite(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_REGISTER) 
            res = handle_response_register(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_BYE) {
            pvt_set_needdestroy(p, "received 408 response");
            ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
         } else {
            if (owner)
               ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
            pvt_set_needdestroy(p, "received 408 response");
         }
         break;

      case 422: /* Session-Timers: Session Interval Too Small */
         if (sipmethod == SIP_INVITE) {
            handle_response_invite(p, resp, rest, req, seqno);
         }
         break;

      case 481: /* Call leg does not exist */
         if (sipmethod == SIP_INVITE) {
            handle_response_invite(p, resp, rest, req, seqno);
         } else if (sipmethod == SIP_REFER) {
            handle_response_refer(p, resp, rest, req, seqno);
         } else if (sipmethod == SIP_SUBSCRIBE) {
            handle_response_subscribe(p, resp, rest, req, seqno);
         } else if (sipmethod == SIP_NOTIFY) {
            pvt_set_needdestroy(p, "received 481 response");
         } else if (sipmethod == SIP_BYE) {
            /* The other side has no transaction to bye,
            just assume it's all right then */
            ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
         } else if (sipmethod == SIP_CANCEL) {
            /* The other side has no transaction to cancel,
            just assume it's all right then */
            ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
         } else {
            ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
            /* Guessing that this is not an important request */
         }
         break;
      case 487:
         if (sipmethod == SIP_INVITE)
            handle_response_invite(p, resp, rest, req, seqno);
         break;
      case 415: /* Unsupported media type */
      case 488: /* Not acceptable here - codec error */
      case 606: /* Not Acceptable */
         if (sipmethod == SIP_INVITE)
            handle_response_invite(p, resp, rest, req, seqno);
         break;
      case 491: /* Pending */
         if (sipmethod == SIP_INVITE)
            handle_response_invite(p, resp, rest, req, seqno);
         else {
            ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
            pvt_set_needdestroy(p, "received 491 response");
         }
         break;
      case 501: /* Not Implemented */
         if (sipmethod == SIP_INVITE)
            handle_response_invite(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_REFER)
            handle_response_refer(p, resp, rest, req, seqno);
         else
            ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
         break;
      case 603:   /* Declined transfer */
         if (sipmethod == SIP_REFER) {
            handle_response_refer(p, resp, rest, req, seqno);
            break;
         }
         /* Fallthrough */
      default:
         if ((resp >= 300) && (resp < 700)) {
            /* Fatal response */
            if ((resp != 487))
               ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
   
            if (sipmethod == SIP_INVITE)
               stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */

            /* XXX Locking issues?? XXX */
            switch(resp) {
            case 300: /* Multiple Choices */
            case 301: /* Moved permanently */
            case 302: /* Moved temporarily */
            case 305: /* Use Proxy */
               parse_moved_contact(p, req);
               /* Fall through */
            case 486: /* Busy here */
            case 600: /* Busy everywhere */
            case 603: /* Decline */
               if (p->owner)
                  ast_queue_control(p->owner, AST_CONTROL_BUSY);
               break;
            case 482: /* Loop Detected */
               /*
                  \note Asterisk has historically tried to do a call forward when it
                  gets a 482, but that behavior isn't necessarily the best course of
                  action. Go ahead and do it anyway by default, but allow the option
                  to immediately pass to the next line in the dialplan. */
               if (p->owner && ast_test_flag(&p->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)) {
                     ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
                     ast_string_field_build(p->owner, call_forward,
                           "Local/%s@%s", p->username, p->context);
               }
               /* Fall through */
            case 480: /* Temporarily Unavailable */
            case 404: /* Not Found */
            case 410: /* Gone */
            case 400: /* Bad Request */
            case 500: /* Server error */
               if (sipmethod == SIP_REFER) {
                  handle_response_refer(p, resp, rest, req, seqno);
                  break;
               } else if (sipmethod == SIP_SUBSCRIBE) {
                  handle_response_subscribe(p, resp, rest, req, seqno);
                  break;
               }
               /* Fall through */
            case 502: /* Bad gateway */
            case 503: /* Service Unavailable */
            case 504: /* Server Timeout */
               if (owner)
                  ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
               break;
            default:
               /* Send hangup */ 
               if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
                  ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
               break;
            }
            /* ACK on invite */
            if (sipmethod == SIP_INVITE) 
               transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
            if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO) 
               sip_alreadygone(p);
            if (!p->owner) {
               pvt_set_needdestroy(p, "transaction completed");
            }
         } else if ((resp >= 100) && (resp < 200)) {
            if (sipmethod == SIP_INVITE) {
               if (!req->ignore && sip_cancel_destroy(p))
                  ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
               if (find_sdp(req))
                  process_sdp(p, req, SDP_T38_NONE);
               if (p->owner) {
                  /* Queue a progress frame */
                  ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
               }
            }
         } else
            ast_log(LOG_NOTICE, "Don't know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(p->sa.sin_addr));
      }
   } else { 
      /* Responses to OUTGOING SIP requests on INCOMING calls 
         get handled here. As well as out-of-call message responses */
      if (req->debug)
         ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);

      if (sipmethod == SIP_INVITE && resp == 200) {
         /* Tags in early session is replaced by the tag in 200 OK, which is 
         the final reply to our INVITE */
         char tag[128];

         gettag(req, "To", tag, sizeof(tag));
         ast_string_field_set(p, theirtag, tag);
      }

      switch(resp) {
      case 200:
         if (sipmethod == SIP_INVITE) {
            handle_response_invite(p, resp, rest, req, seqno);
         } else if (sipmethod == SIP_CANCEL) {
            ast_debug(1, "Got 200 OK on CANCEL\n");

            /* Wait for 487, then destroy */
         } else if (sipmethod == SIP_NOTIFY) {
            /* They got the notify, this is the end */
            if (p->owner) {
               if (p->refer) {
                  ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
               } else
                  ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
               /* ast_queue_hangup(p->owner); Disabled */
            } else {
               if (!p->subscribed && !p->refer) {
                  pvt_set_needdestroy(p, "transaction completed");
               }
               if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
                  /* Ready to send the next state we have on queue */
                  ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
                  cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
               }
            }
         } else if (sipmethod == SIP_BYE) {
            pvt_set_needdestroy(p, "transaction completed");
         } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
            /* We successfully transmitted a message or
               a video update request in INFO */
            ;
         }
         break;
      case 202:   /* Transfer accepted */
         if (sipmethod == SIP_REFER) 
            handle_response_refer(p, resp, rest, req, seqno);
         break;
      case 401:   /* www-auth */
      case 407:
         if (sipmethod == SIP_REFER)
            handle_response_refer(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_INVITE) 
            handle_response_invite(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_BYE) {
            if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
               ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
               pvt_set_needdestroy(p, "failed to authenticate BYE");
            }
         }
         break;
      case 481:   /* Call leg does not exist */
         if (sipmethod == SIP_INVITE) {
            /* Re-invite failed */
            handle_response_invite(p, resp, rest, req, seqno);
         } else if (sipmethod == SIP_BYE) {
            pvt_set_needdestroy(p, "received 481 response");
         } else if (sipmethod == SIP_NOTIFY) {
            pvt_set_needdestroy(p, "received 481 response");
         } else if (sipdebug) {
            ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
         }
         break;
      case 501: /* Not Implemented */
         if (sipmethod == SIP_INVITE) 
            handle_response_invite(p, resp, rest, req, seqno);
         else if (sipmethod == SIP_REFER) 
            handle_response_refer(p, resp, rest, req, seqno);
         break;
      case 603:   /* Declined transfer */
         if (sipmethod == SIP_REFER) {
            handle_response_refer(p, resp, rest, req, seqno);
            break;
         }
         /* Fallthrough */
      default: /* Errors without handlers */
         if ((resp >= 100) && (resp < 200)) {
            if (sipmethod == SIP_INVITE) {   /* re-invite */
               if (!req->ignore && sip_cancel_destroy(p))
                  ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
            }
         }
         if ((resp >= 300) && (resp < 700)) {
            if ((resp != 487))
               ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
            switch(resp) {
            case 415: /* Unsupported media type */
            case 488: /* Not acceptable here - codec error */
            case 603: /* Decline */
            case 500: /* Server error */
            case 502: /* Bad gateway */
            case 503: /* Service Unavailable */
            case 504: /* Server timeout */

               /* re-invite failed */
               if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
                  ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
               break;
            }
         }
         break;
      }
   }
}
static void handle_response_invite ( struct sip_pvt p,
int  resp,
char *  rest,
struct sip_request req,
int  seqno 
) [static]

Handle SIP response to INVITE dialogue.

Definition at line 18167 of file chan_sip.c.

References ast_channel::_state, sip_pvt::alreadygone, append_history, AST_CAUSE_NORMAL_CLEARING, AST_CONTROL_ANSWER, AST_CONTROL_CONGESTION, AST_CONTROL_PROGRESS, AST_CONTROL_RINGING, ast_debug, ast_log(), ast_null_frame, ast_queue_control(), ast_queue_frame(), ast_queue_hangup_with_cause(), ast_random(), ast_rtp_set_rtptimers_onhold(), ast_sched_add(), AST_SCHED_DEL_UNREF, ast_set_flag, ast_setstate(), AST_STATE_RINGING, AST_STATE_UP, ast_string_field_set, ast_strlen_zero(), ast_test_flag, sip_invite_param::auth_type, sip_pvt::authtries, build_route(), sip_settings::callevents, sip_pvt::callid, change_t38_state(), check_pendings(), DEC_CALL_LIMIT, DEC_CALL_RINGING, DEFAULT_TRANS_TIMEOUT, dialog_ref(), dialog_unref(), do_proxy_auth(), EVENT_FLAG_SYSTEM, FALSE, find_sdp(), sip_pvt::flags, sip_pvt::fullcontact, get_header(), sip_request::ignore, sip_pvt::initid, sip_pvt::initreq, INV_CALLING, INV_CANCELLED, INV_COMPLETED, INV_EARLY_MEDIA, INV_PROCEEDING, INV_TERMINATED, sip_pvt::invitestate, LOG_NOTICE, LOG_WARNING, manager_event, MAX_AUTHTRIES, ast_channel::name, sip_pvt::options, sip_pvt::outgoing_call, sip_pvt::owner, parse_ok_contact(), parse_session_expires(), sip_pvt::peername, sip_pvt::pendinginvite, proc_422_rsp(), process_sdp(), pvt_set_needdestroy(), sip_pvt::route, sip_pvt::rtp, SDP_T38_ACCEPT, SDP_T38_NONE, SESSION_TIMER_MODE_ORIGINATE, SESSION_TIMER_MODE_REFUSE, SESSION_TIMER_REFRESHER_AUTO, SESSION_TIMER_REFRESHER_UAC, SESSION_TIMER_REFRESHER_UAS, set_address_from_contact(), SIP_ACK, sip_alreadygone(), sip_cancel_destroy(), sip_cfg, SIP_INVITE, SIP_OUTGOING, SIP_PAGE2_DIALOG_ESTABLISHED, SIP_PENDINGBYE, sip_reinvite_retry(), sip_scheddestroy(), sip_st_dlg::st_active, sip_st_dlg::st_active_peer_ua, st_get_mode(), sip_st_dlg::st_interval, sip_st_dlg::st_ref, start_session_timer(), t38properties::state, sip_pvt::stimer, sip_pvt::t38, T38_DISABLED, T38_LOCAL_REINVITE, transmit_reinvite_with_sdp(), transmit_request(), TRUE, sip_pvt::udptl, ast_channel::uniqueid, update_call_counter(), sip_pvt::waitid, XMIT_ERROR, and XMIT_UNRELIABLE.

Referenced by handle_response().

{
   int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
   int res = 0;
   int xmitres = 0;
   int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
   char *p_hdrval;
   int rtn;

   if (reinvite)
      ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
   else
      ast_debug(4, "SIP response %d to standard invite\n", resp);

   if (p->alreadygone) { /* This call is already gone */
      ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
      return;
   }

   /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
   /* Don't auto congest anymore since we've gotten something useful back */
   AST_SCHED_DEL_UNREF(sched, p->initid, dialog_unref(p, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));

   /* RFC3261 says we must treat every 1xx response (but not 100)
      that we don't recognize as if it was 183.
   */
   if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
      resp = 183;

   /* Any response between 100 and 199 is PROCEEDING */
   if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
      p->invitestate = INV_PROCEEDING;
 
   /* Final response, not 200 ? */
   if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
      p->invitestate = INV_COMPLETED;
   
   /* Final response, clear out pending invite */
   if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
      p->pendinginvite = 0;

   switch (resp) {
   case 100:   /* Trying */
   case 101:   /* Dialog establishment */
      if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
         ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
      check_pendings(p);
      break;

   case 180:   /* 180 Ringing */
   case 182:       /* 182 Queued */
      if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
         ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
      if (!req->ignore && p->owner) {
         ast_queue_control(p->owner, AST_CONTROL_RINGING);
         if (p->owner->_state != AST_STATE_UP) {
            ast_setstate(p->owner, AST_STATE_RINGING);
         }
      }
      if (find_sdp(req)) {
         if (p->invitestate != INV_CANCELLED)
            p->invitestate = INV_EARLY_MEDIA;
         res = process_sdp(p, req, SDP_T38_NONE);
         if (!req->ignore && p->owner) {
            /* Queue a progress frame only if we have SDP in 180 or 182 */
            ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
         }
      }
      check_pendings(p);
      break;

   case 183:   /* Session progress */
      if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
         ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
      if (find_sdp(req)) {
         if (p->invitestate != INV_CANCELLED)
            p->invitestate = INV_EARLY_MEDIA;
         res = process_sdp(p, req, SDP_T38_NONE);
         if (!req->ignore && p->owner) {
            /* Queue a progress frame */
            ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
         }
      } else {
         /* Alcatel PBXs are known to send 183s with no SDP after sending
          * a 100 Trying response. We're just going to treat this sort of thing
          * the same as we would treat a 180 Ringing
          */
         if (!req->ignore && p->owner) {
            ast_queue_control(p->owner, AST_CONTROL_RINGING);
         }
      }
      check_pendings(p);
      break;

   case 200:   /* 200 OK on invite - someone's answering our call */
      if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
         ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
      p->authtries = 0;
      if (find_sdp(req)) {
         if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
            if (!reinvite)
               /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
               /* For re-invites, we try to recover */
               ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
      }

      /* Parse contact header for continued conversation */
      /* When we get 200 OK, we know which device (and IP) to contact for this call */
      /* This is important when we have a SIP proxy between us and the phone */
      if (outgoing) {
         update_call_counter(p, DEC_CALL_RINGING);
         parse_ok_contact(p, req);
         /* Save Record-Route for any later requests we make on this dialogue */
         if (!reinvite)
            build_route(p, req, 1);

         if(set_address_from_contact(p)) {
            /* Bad contact - we don't know how to reach this device */
            /* We need to ACK, but then send a bye */
            if (!p->route && !req->ignore)
               ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
         } 

      }

      if (!req->ignore && p->owner) {
         if (!reinvite) {
            ast_queue_control(p->owner, AST_CONTROL_ANSWER);
            if (sip_cfg.callevents)
               manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
                  "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
                  p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
         } else { /* RE-invite */
            ast_queue_frame(p->owner, &ast_null_frame);
         }
      } else {
          /* It's possible we're getting an 200 OK after we've tried to disconnect
              by sending CANCEL */
         /* First send ACK, then send bye */
         if (!req->ignore)
            ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
      }

      /* Check for Session-Timers related headers */
      if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
         p_hdrval = (char*)get_header(req, "Session-Expires");
         if (!ast_strlen_zero(p_hdrval)) {
            /* UAS supports Session-Timers */
            enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
            int tmp_st_interval = 0;
            rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
            if (rtn != 0) {
               ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
            }
            if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC || 
               tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
               p->stimer->st_ref = tmp_st_ref;
            } 
            if (tmp_st_interval) {
               p->stimer->st_interval = tmp_st_interval;
            }
            p->stimer->st_active = TRUE;
            p->stimer->st_active_peer_ua = TRUE;
            start_session_timer(p);
         } else {
            /* UAS doesn't support Session-Timers */
            if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
               p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
               p->stimer->st_active_peer_ua = FALSE;
               start_session_timer(p);
            }
         }
      }


      /* If I understand this right, the branch is different for a non-200 ACK only */
      p->invitestate = INV_TERMINATED;
      ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
      xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
      check_pendings(p);
      break;

   case 407: /* Proxy authentication */
   case 401: /* Www auth */
      /* First we ACK */
      xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
      if (p->options)
         p->options->auth_type = resp;

      /* Then we AUTH */
      ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
      if (!req->ignore) {
         if (p->authtries < MAX_AUTHTRIES)
            p->invitestate = INV_CALLING;
         if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
            ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
            pvt_set_needdestroy(p, "failed to authenticate on INVITE");
            sip_alreadygone(p);
            if (p->owner)
               ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
         }
      }
      break;

   case 403: /* Forbidden */
      /* First we ACK */
      xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
      ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
      if (!req->ignore && p->owner)
         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
      pvt_set_needdestroy(p, "received 403 response");
      sip_alreadygone(p);
      break;

   case 404: /* Not found */
      xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
      if (p->owner && !req->ignore)
         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
      sip_alreadygone(p);
      break;

   case 408: /* Request timeout */
   case 481: /* Call leg does not exist */
      /* Could be REFER caused INVITE with replaces */
      ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
      xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
      if (p->owner)
         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      break;

   case 422: /* Session-Timers: Session interval too small */
      xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
      ast_string_field_set(p, theirtag, NULL);
      proc_422_rsp(p, req);
      break;

   case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
      xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
      append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
      ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
      if (p->owner)
         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
      break;

      

   case 487: /* Cancelled transaction */
      /* We have sent CANCEL on an outbound INVITE 
         This transaction is already scheduled to be killed by sip_hangup().
      */
      xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
      if (p->owner && !req->ignore) {
         ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
         append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
      } else if (!req->ignore) {
         update_call_counter(p, DEC_CALL_LIMIT);
         append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
         pvt_set_needdestroy(p, "received 487 response");
         sip_alreadygone(p);
      }
      break;
   case 415: /* Unsupported media type */
   case 488: /* Not acceptable here */
   case 606: /* Not Acceptable */
      xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
      if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
         change_t38_state(p, T38_DISABLED);
         /* Try to reset RTP timers */
         ast_rtp_set_rtptimers_onhold(p->rtp);

         /* Trigger a reinvite back to audio */
         transmit_reinvite_with_sdp(p, FALSE, FALSE);
      } else {
         /* We can't set up this call, so give up */
         if (p->owner && !req->ignore)
            ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
         pvt_set_needdestroy(p, "received 488 response");
         /* If there's no dialog to end, then mark p as already gone */
         if (!reinvite)
            sip_alreadygone(p);
      }
      break;
   case 491: /* Pending */
      xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
      if (p->owner && !req->ignore) {
         if (p->owner->_state != AST_STATE_UP) {
            ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
            pvt_set_needdestroy(p, "received 491 response");
         } else {
            /* This is a re-invite that failed. */
            /* Reset the flag after a while 
             */
            int wait;
            /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
             * if not owner of call, wait 0 to 2 seconds */
            if (p->outgoing_call) {
               wait = 2100 + ast_random() % 2000;
            } else {
               wait = ast_random() % 2000;
            }
            p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, dialog_ref(p, "passing dialog ptr into sched structure based on waitid for sip_reinvite_retry."));
            ast_log(LOG_WARNING, "just did sched_add waitid(%d) for sip_reinvite_retry for dialog %s in handle_response_invite\n", p->waitid, p->callid);
            ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
         }
      }
      break;

   case 501: /* Not implemented */
      xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
      if (p->owner)
         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
      break;
   }
   if (xmitres == XMIT_ERROR)
      ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
}
static void handle_response_notify ( struct sip_pvt p,
int  resp,
char *  rest,
struct sip_request req,
int  seqno 
) [static]

Definition at line 18488 of file chan_sip.c.

References AST_CAUSE_NORMAL_UNSPECIFIED, ast_clear_flag, ast_debug, ast_inet_ntoa(), ast_log(), ast_queue_hangup_with_cause(), ast_string_field_set, ast_strlen_zero(), ast_test_flag, sip_pvt::authname, sip_pvt::authtries, cb_extensionstate(), sip_pvt::context, do_proxy_auth(), sip_pvt::exten, sip_pvt::flags, get_header(), sip_pvt::initreq, sip_pvt::laststate, LOG_NOTICE, LOG_WARNING, ast_channel::name, NONE, sip_pvt::notify_headers, sip_pvt::owner, pvt_set_needdestroy(), sip_pvt::recv, sip_pvt::refer, SIP_NOTIFY, SIP_PAGE2_STATECHANGEQUEUE, and sip_pvt::subscribed.

Referenced by handle_response().

{
   switch (resp) {
   case 200:   /* Notify accepted */
      /* They got the notify, this is the end */
      if (p->owner) {
         if (!p->refer) {
            ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
            ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
         } else {
            ast_debug(4, "Got OK on REFER Notify message\n");
         }
      } else {
         if (p->subscribed == NONE) {
            ast_debug(4, "Got 200 accepted on NOTIFY\n");
            pvt_set_needdestroy(p, "received 200 response");
         }
         if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
            /* Ready to send the next state we have on queue */
            ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
            cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
         }
      }
      break;
   case 401:   /* Not www-authorized on SIP method */
   case 407:   /* Proxy auth */
      if (!p->notify_headers) {
         break; /* Only device notify can use NOTIFY auth */
      }
      ast_string_field_set(p, theirtag, NULL);
      if (ast_strlen_zero(p->authname)) {
         ast_log(LOG_WARNING, "Asked to authenticate NOTIFY to %s:%d but we have no matching peer or realm auth!\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
         pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
      }
      if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
         ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
         pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
      }
      break;
   }
}
static void handle_response_peerpoke ( struct sip_pvt p,
int  resp,
struct sip_request req 
) [static]

Handle qualification responses (OPTIONS)

Definition at line 18793 of file chan_sip.c.

References ast_check_realtime(), AST_DEVICE_UNKNOWN, ast_devstate_changed(), ast_log(), AST_SCHED_REPLACE_UNREF, ast_tvdiff_ms(), ast_tvnow(), ast_update_realtime(), sip_peer::call, DEFAULT_FREQ_NOTOK, dialog_unref(), EVENT_FLAG_SYSTEM, sip_peer::lastms, LOG_NOTICE, manager_event, sip_peer::maxms, sip_peer::name, sip_settings::peer_rtupdate, sip_peer::pokeexpire, sip_peer::ps, pvt_set_needdestroy(), sip_peer::qualifyfreq, ref_peer(), sip_settings::regextenonqualify, register_peer_exten(), sip_pvt::relatedpeer, s, SENTINEL, sip_cfg, sip_poke_peer_s(), TRUE, and unref_peer().

Referenced by handle_response().

{
   struct sip_peer *peer = /* ref_peer( */ p->relatedpeer /* , "bump refcount on p, as it is being used in this function(handle_response_peerpoke)")*/ ; /* hope this is already refcounted! */
   int statechanged, is_reachable, was_reachable;
   int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);

   /*
    * Compute the response time to a ping (goes in peer->lastms.)
    * -1 means did not respond, 0 means unknown,
    * 1..maxms is a valid response, >maxms means late response.
    */
   if (pingtime < 1) /* zero = unknown, so round up to 1 */
      pingtime = 1;

   /* Now determine new state and whether it has changed.
    * Use some helper variables to simplify the writing
    * of the expressions.
    */
   was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
   is_reachable = pingtime <= peer->maxms;
   statechanged = peer->lastms == 0 /* yes, unknown before */
      || was_reachable != is_reachable;

   peer->lastms = pingtime;
   peer->call = dialog_unref(peer->call, "unref dialog peer->call");
   if (statechanged) {
      const char *s = is_reachable ? "Reachable" : "Lagged";
      char str_lastms[20];
      snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);

      ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
         peer->name, s, pingtime, peer->maxms);
      ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
      if (sip_cfg.peer_rtupdate) {
         ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
      }
      manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
         "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
         peer->name, s, pingtime);
      if (is_reachable && sip_cfg.regextenonqualify)
         register_peer_exten(peer, TRUE);
   }

   pvt_set_needdestroy(p, "got OPTIONS response");

   /* Try again eventually */
   AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
         is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
         sip_poke_peer_s, peer,
         unref_peer(_data, "removing poke peer ref"),
         unref_peer(peer, "removing poke peer ref"),
         ref_peer(peer, "adding poke peer ref"));
}
static void handle_response_refer ( struct sip_pvt p,
int  resp,
char *  rest,
struct sip_request req,
int  seqno 
) [static]

Definition at line 18592 of file chan_sip.c.

References AST_CONTROL_CONGESTION, ast_debug, ast_inet_ntoa(), ast_log(), ast_queue_control(), ast_strlen_zero(), sip_pvt::authname, sip_pvt::authtries, sip_pvt::callid, do_proxy_auth(), get_header(), sip_pvt::initreq, LOG_NOTICE, LOG_WARNING, sip_pvt::owner, pvt_set_needdestroy(), sip_pvt::recv, sip_pvt::refer, REFER_ACCEPTED, REFER_FAILED, REFER_NOAUTH, sip_refer::refer_to, SIP_REFER, and sip_refer::status.

Referenced by handle_response().

{
   /* If no refer structure exists, then do nothing */
   if (!p->refer)
      return;

   switch (resp) {
   case 202:   /* Transfer accepted */
      /* We need  to do something here */
      /* The transferee is now sending INVITE to target */
      p->refer->status = REFER_ACCEPTED;
      /* Now wait for next message */
      ast_debug(3, "Got 202 accepted on transfer\n");
      /* We should hang along, waiting for NOTIFY's here */
      break;

   case 401:   /* Not www-authorized on SIP method */
   case 407:   /* Proxy auth */
      if (ast_strlen_zero(p->authname)) {
         ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
            ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
         pvt_set_needdestroy(p, "unable to authenticate REFER");
      }
      if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
         ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
         p->refer->status = REFER_NOAUTH;
         pvt_set_needdestroy(p, "failed to authenticat REFER");
      }
      break;
   case 481: /* Call leg does not exist */

      /* A transfer with Replaces did not work */
      /* OEJ: We should Set flag, cancel the REFER, go back
      to original call - but right now we can't */
      ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
      if (p->owner)
         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
      pvt_set_needdestroy(p, "received 481 response");
      break;

   case 500:   /* Server error */
   case 501:   /* Method not implemented */
      /* Return to the current call onhold */
      /* Status flag needed to be reset */
      ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
      pvt_set_needdestroy(p, "received 500/501 response");
      p->refer->status = REFER_FAILED;
      break;
   case 603:   /* Transfer declined */
      ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
      p->refer->status = REFER_FAILED;
      pvt_set_needdestroy(p, "received 603 response");
      break;
   }
}
static int handle_response_register ( struct sip_pvt p,
int  resp,
char *  rest,
struct sip_request req,
int  seqno 
) [static]

Handle responses on REGISTER to services.

Definition at line 18649 of file chan_sip.c.

References __get_header(), ast_debug, ast_log(), AST_SCHED_DEL_UNREF, AST_SCHED_REPLACE_UNREF, ast_strlen_zero(), ast_tvnow(), sip_pvt::authtries, sip_registry::call, sip_pvt::callid, sip_registry::configured_expiry, default_expiry, DEFAULT_TRANS_TIMEOUT, dialog_unref(), do_register_auth(), EVENT_FLAG_SYSTEM, sip_registry::expire, sip_registry::expiry, EXPIRY_GUARD_LIMIT, EXPIRY_GUARD_MIN, EXPIRY_GUARD_PCT, EXPIRY_GUARD_SECS, get_header(), sip_registry::hostname, sip_pvt::initreq, LOG_NOTICE, LOG_WARNING, manager_event, MAX, MAX_AUTHTRIES, sip_pvt::our_contact, sip_pvt::peername, pvt_set_needdestroy(), sip_registry::refresh, REG_STATE_NOAUTH, REG_STATE_REGISTERED, REG_STATE_REJECTED, REG_STATE_UNREGISTERED, sip_registry::regattempts, sip_pvt::registry, registry_addref(), registry_unref(), sip_registry::regstate, regstate2str(), sip_registry::regtime, S_OR, SIP_REGISTER, sip_reregister(), sip_scheddestroy(), strcasestr(), sip_registry::timeout, transmit_register(), sip_pvt::username, and sip_registry::username.

Referenced by handle_response().

{
   int expires, expires_ms;
   struct sip_registry *r;
   r=p->registry;
   
   switch (resp) {
   case 401:   /* Unauthorized */
      if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
         ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
         pvt_set_needdestroy(p, "failed to authenticate REGISTER");
      }
      break;
   case 403:   /* Forbidden */
      ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
      AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
      r->regstate = REG_STATE_NOAUTH;
      pvt_set_needdestroy(p, "received 403 response");
      break;
   case 404:   /* Not found */
      ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
      pvt_set_needdestroy(p, "received 404 response");
      if (r->call)
         r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
      r->regstate = REG_STATE_REJECTED;
      AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
      break;
   case 407:   /* Proxy auth */
      if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
         ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
         pvt_set_needdestroy(p, "failed to authenticate REGISTER");
      }
      break;
   case 408:   /* Request timeout */
      /* Got a timeout response, so reset the counter of failed responses */
      if (r) {
         r->regattempts = 0;
      } else {
         ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
      }
      break;
   case 423:   /* Interval too brief */
      r->expiry = atoi(get_header(req, "Min-Expires"));
      ast_log(LOG_WARNING, "Got 423 Interval too brief for service %s@%s, minimum is %d seconds\n", p->registry->username, p->registry->hostname, r->expiry);
      AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
      if (r->call) {
         r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
         pvt_set_needdestroy(p, "received 423 response");
      }
      if (r->expiry > max_expiry) {
         ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
         r->expiry = r->configured_expiry;
         r->regstate = REG_STATE_REJECTED;
      } else {
         r->regstate = REG_STATE_UNREGISTERED;
         transmit_register(r, SIP_REGISTER, NULL, NULL);
      }
      manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
      break;
   case 479:   /* SER: Not able to process the URI - address is wrong in register*/
      ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
      pvt_set_needdestroy(p, "received 479 response");
      if (r->call)
         r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
      r->regstate = REG_STATE_REJECTED;
      AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
      break;
   case 200:   /* 200 OK */
      if (!r) {
         ast_log(LOG_WARNING, "Got 200 OK on REGISTER, but there isn't a registry entry for '%s' (we probably already got the OK)\n", S_OR(p->peername, p->username));
         pvt_set_needdestroy(p, "received erroneous 200 response");
         return 0;
      }
      
      r->regstate = REG_STATE_REGISTERED;
      r->regtime = ast_tvnow();     /* Reset time of last succesful registration */
      manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
      r->regattempts = 0;
      ast_debug(1, "Registration successful\n");
      if (r->timeout > -1) {
         ast_debug(1, "Cancelling timeout %d\n", r->timeout);
      }
      AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
      if (r->call)
         r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
      p->registry = registry_unref(p->registry, "unref registry entry p->registry");
      /* Let this one hang around until we have all the responses */
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      /* p->needdestroy = 1; */
      
      /* set us up for re-registering
       * figure out how long we got registered for
       * according to section 6.13 of RFC, contact headers override
       * expires headers, so check those first */
      expires = 0;

      /* XXX todo: try to save the extra call */
      if (!ast_strlen_zero(get_header(req, "Contact"))) {
         const char *contact = NULL;
         const char *tmptmp = NULL;
         int start = 0;
         for(;;) {
            contact = __get_header(req, "Contact", &start);
            /* this loop ensures we get a contact header about our register request */
            if(!ast_strlen_zero(contact)) {
               if( (tmptmp=strstr(contact, p->our_contact))) {
                  contact=tmptmp;
                  break;
               }
            } else
               break;
         }
         tmptmp = strcasestr(contact, "expires=");
         if (tmptmp) {
            if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
               expires = 0;
         }
         
      }
      if (!expires) 
         expires=atoi(get_header(req, "expires"));
      if (!expires)
         expires=default_expiry;
      
      expires_ms = expires * 1000;
      if (expires <= EXPIRY_GUARD_LIMIT)
         expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
      else
         expires_ms -= EXPIRY_GUARD_SECS * 1000;
      if (sipdebug)
         ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000); 
      
      r->refresh= (int) expires_ms / 1000;
      
      /* Schedule re-registration before we expire */
      AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r, 
                        registry_unref(_data,"unref in REPLACE del fail"), 
                        registry_unref(r,"unref in REPLACE add fail"), 
                        registry_addref(r,"The Addition side of REPLACE")); 
   }
   return 1;
}
static void handle_response_subscribe ( struct sip_pvt p,
int  resp,
char *  rest,
struct sip_request req,
int  seqno 
) [static]

Definition at line 18531 of file chan_sip.c.

References ast_debug, ast_free, ast_log(), ast_sched_add(), ast_string_field_set, ASTOBJ_REF, ASTOBJ_UNREF, sip_pvt::authtries, sip_subscription_mwi::call, do_proxy_auth(), get_header(), sip_pvt::initreq, LOG_NOTICE, LOG_WARNING, sip_pvt::mwi, sip_pvt::options, pvt_set_needdestroy(), sip_subscription_mwi::resub, sip_alreadygone(), SIP_SUBSCRIBE, sip_subscribe_mwi_destroy(), sip_subscribe_mwi_do(), sip_subscription_mwi::subscribed, and transmit_response_with_date().

Referenced by handle_response().

{
   if (!p->mwi) {
      return;
   }

   switch (resp) {
   case 200: /* Subscription accepted */
      ast_debug(3, "Got 200 OK on subscription for MWI\n");
      if (p->options) {
         ast_free(p->options);
         p->options = NULL;
      }
      p->mwi->subscribed = 1;
      if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
         ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
      }
      break;
   case 401:
   case 407:
      ast_string_field_set(p, theirtag, NULL);
      if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
         ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
         p->mwi->call = NULL;
         ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
         pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
      }
      break;
   case 403:
      transmit_response_with_date(p, "200 OK", req);
      ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
      p->mwi->call = NULL;
      ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
      pvt_set_needdestroy(p, "received 403 response");
      sip_alreadygone(p);
      break;
   case 404:
      ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
      p->mwi->call = NULL;
      ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
      pvt_set_needdestroy(p, "received 404 response");
      break;
   case 481:
      ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
      p->mwi->call = NULL;
      ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
      pvt_set_needdestroy(p, "received 481 response");
      break;
   case 500:
   case 501:
      ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
      p->mwi->call = NULL;
      ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
      pvt_set_needdestroy(p, "received 500/501 response");
      break;
   }
}
static int handle_t38_options ( struct ast_flags flags,
struct ast_flags mask,
struct ast_variable v,
int *  maxdatagram 
) [static]

Handle T.38 configuration options common to users and peers.

Returns:
non-zero if any config options were handled, zero otherwise

Definition at line 23923 of file chan_sip.c.

References ast_clear_flag, ast_log(), ast_set2_flag, ast_set_flag, ast_strdupa, ast_true(), buf, global_t38_maxdatagram, ast_variable::lineno, LOG_WARNING, ast_variable::name, SIP_PAGE2_FORWARD_LOOP_DETECTED, SIP_PAGE2_T38SUPPORT, SIP_PAGE2_T38SUPPORT_UDPTL, SIP_PAGE2_T38SUPPORT_UDPTL_FEC, SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, SIP_PAGE2_UDPTL_DESTINATION, strsep(), ast_variable::value, and word.

Referenced by build_peer(), and reload_config().

{
   int res = 1;

   if (!strcasecmp(v->name, "t38pt_udptl")) {
      char *buf = ast_strdupa(v->value);
      char *word, *next = buf;

      ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);

      while ((word = strsep(&next, ","))) {
         if (ast_true(word) || !strcasecmp(word, "fec")) {
            ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
            ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
         } else if (!strcasecmp(word, "redundancy")) {
            ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
            ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
         } else if (!strcasecmp(word, "none")) {
            ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
            ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
         } else if (!strncasecmp(word, "maxdatagram=", 12)) {
            if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
               ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
               *maxdatagram = global_t38_maxdatagram;
            }
         }
      }
   } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
      ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
      ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
   } else if (!strcasecmp(v->name, "forwardloopdetected")) {
      ast_set_flag(&mask[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
      ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FORWARD_LOOP_DETECTED);
   } else {
      res = 0;
   }

   return res;
}
static const char * hangup_cause2sip ( int  cause) [static]

Convert Asterisk hangup causes to SIP codes.

 Possible values from causes.h
        AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
        AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED

	In addition to these, a lot of PRI codes is defined in causes.h 
	...should we take care of them too ?
	
	Quote RFC 3398

   ISUP Cause value                        SIP response
   ----------------                        ------------
   1  unallocated number                   404 Not Found
   2  no route to network                  404 Not found
   3  no route to destination              404 Not found
   16 normal call clearing                 --- (*)
   17 user busy                            486 Busy here
   18 no user responding                   408 Request Timeout
   19 no answer from the user              480 Temporarily unavailable
   20 subscriber absent                    480 Temporarily unavailable
   21 call rejected                        403 Forbidden (+)
   22 number changed (w/o diagnostic)      410 Gone
   22 number changed (w/ diagnostic)       301 Moved Permanently
   23 redirection to new destination       410 Gone
   26 non-selected user clearing           404 Not Found (=)
   27 destination out of order             502 Bad Gateway
   28 address incomplete                   484 Address incomplete
   29 facility rejected                    501 Not implemented
   31 normal unspecified                   480 Temporarily unavailable

Definition at line 6121 of file chan_sip.c.

References AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, AST_CAUSE_CALL_REJECTED, AST_CAUSE_CHAN_NOT_IMPLEMENTED, AST_CAUSE_CONGESTION, AST_CAUSE_DESTINATION_OUT_OF_ORDER, AST_CAUSE_FACILITY_REJECTED, AST_CAUSE_FAILURE, AST_CAUSE_INVALID_NUMBER_FORMAT, AST_CAUSE_NO_ANSWER, AST_CAUSE_NO_ROUTE_DESTINATION, AST_CAUSE_NO_ROUTE_TRANSIT_NET, AST_CAUSE_NO_USER_RESPONSE, AST_CAUSE_NORMAL_UNSPECIFIED, AST_CAUSE_NOTDEFINED, AST_CAUSE_NUMBER_CHANGED, AST_CAUSE_SWITCH_CONGESTION, AST_CAUSE_UNALLOCATED, AST_CAUSE_UNREGISTERED, AST_CAUSE_USER_BUSY, and ast_debug.

Referenced by sip_hangup().

{
   switch (cause) {
      case AST_CAUSE_UNALLOCATED:      /* 1 */
      case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
      case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
         return "404 Not Found";
      case AST_CAUSE_CONGESTION:    /* 34 */
      case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
         return "503 Service Unavailable";
      case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
         return "408 Request Timeout";
      case AST_CAUSE_NO_ANSWER:     /* 19 */
      case AST_CAUSE_UNREGISTERED:        /* 20 */
         return "480 Temporarily unavailable";
      case AST_CAUSE_CALL_REJECTED:    /* 21 */
         return "403 Forbidden";
      case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
         return "410 Gone";
      case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
         return "480 Temporarily unavailable";
      case AST_CAUSE_INVALID_NUMBER_FORMAT:
         return "484 Address incomplete";
      case AST_CAUSE_USER_BUSY:
         return "486 Busy here";
      case AST_CAUSE_FAILURE:
         return "500 Server internal failure";
      case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
         return "501 Not Implemented";
      case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
         return "503 Service Unavailable";
      /* Used in chan_iax2 */
      case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
         return "502 Bad Gateway";
      case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
         return "488 Not Acceptable Here";
         
      case AST_CAUSE_NOTDEFINED:
      default:
         ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
         return NULL;
   }

   /* Never reached */
   return 0;
}
static int hangup_sip2cause ( int  cause) [static]

Convert SIP hangup causes to Asterisk hangup causes.

Definition at line 6009 of file chan_sip.c.

References AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, AST_CAUSE_BUSY, AST_CAUSE_CALL_REJECTED, AST_CAUSE_CONGESTION, AST_CAUSE_DESTINATION_OUT_OF_ORDER, AST_CAUSE_FACILITY_REJECTED, AST_CAUSE_FAILURE, AST_CAUSE_INTERWORKING, AST_CAUSE_INVALID_NUMBER_FORMAT, AST_CAUSE_NO_ANSWER, AST_CAUSE_NO_ROUTE_DESTINATION, AST_CAUSE_NO_USER_RESPONSE, AST_CAUSE_NORMAL, AST_CAUSE_NORMAL_TEMPORARY_FAILURE, AST_CAUSE_NUMBER_CHANGED, AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, AST_CAUSE_UNALLOCATED, and AST_CAUSE_USER_BUSY.

Referenced by handle_response().

{
   /* Possible values taken from causes.h */

   switch(cause) {
      case 401:   /* Unauthorized */
         return AST_CAUSE_CALL_REJECTED;
      case 403:   /* Not found */
         return AST_CAUSE_CALL_REJECTED;
      case 404:   /* Not found */
         return AST_CAUSE_UNALLOCATED;
      case 405:   /* Method not allowed */
         return AST_CAUSE_INTERWORKING;
      case 407:   /* Proxy authentication required */
         return AST_CAUSE_CALL_REJECTED;
      case 408:   /* No reaction */
         return AST_CAUSE_NO_USER_RESPONSE;
      case 409:   /* Conflict */
         return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
      case 410:   /* Gone */
         return AST_CAUSE_NUMBER_CHANGED;
      case 411:   /* Length required */
         return AST_CAUSE_INTERWORKING;
      case 413:   /* Request entity too large */
         return AST_CAUSE_INTERWORKING;
      case 414:   /* Request URI too large */
         return AST_CAUSE_INTERWORKING;
      case 415:   /* Unsupported media type */
         return AST_CAUSE_INTERWORKING;
      case 420:   /* Bad extension */
         return AST_CAUSE_NO_ROUTE_DESTINATION;
      case 480:   /* No answer */
         return AST_CAUSE_NO_ANSWER;
      case 481:   /* No answer */
         return AST_CAUSE_INTERWORKING;
      case 482:   /* Loop detected */
         return AST_CAUSE_INTERWORKING;
      case 483:   /* Too many hops */
         return AST_CAUSE_NO_ANSWER;
      case 484:   /* Address incomplete */
         return AST_CAUSE_INVALID_NUMBER_FORMAT;
      case 485:   /* Ambiguous */
         return AST_CAUSE_UNALLOCATED;
      case 486:   /* Busy everywhere */
         return AST_CAUSE_BUSY;
      case 487:   /* Request terminated */
         return AST_CAUSE_INTERWORKING;
      case 488:   /* No codecs approved */
         return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
      case 491:   /* Request pending */
         return AST_CAUSE_INTERWORKING;
      case 493:   /* Undecipherable */
         return AST_CAUSE_INTERWORKING;
      case 500:   /* Server internal failure */
         return AST_CAUSE_FAILURE;
      case 501:   /* Call rejected */
         return AST_CAUSE_FACILITY_REJECTED;
      case 502:   
         return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
      case 503:   /* Service unavailable */
         return AST_CAUSE_CONGESTION;
      case 504:   /* Gateway timeout */
         return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
      case 505:   /* SIP version not supported */
         return AST_CAUSE_INTERWORKING;
      case 600:   /* Busy everywhere */
         return AST_CAUSE_USER_BUSY;
      case 603:   /* Decline */
         return AST_CAUSE_CALL_REJECTED;
      case 604:   /* Does not exist anywhere */
         return AST_CAUSE_UNALLOCATED;
      case 606:   /* Not acceptable */
         return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
      default:
         return AST_CAUSE_NORMAL;
   }
   /* Never reached */
   return 0;
}
static int init_req ( struct sip_request req,
int  sipmethod,
const char *  recip 
) [static]

Initialize SIP request.

Definition at line 9761 of file chan_sip.c.

References ast_free, ast_str_create(), ast_str_set(), ast_str_strlen(), sip_request::content, sip_request::data, sip_request::header, sip_request::headers, sip_request::len, sip_request::method, sip_methods, SIP_MIN_PACKET, and cfsip_methods::text.

Referenced by initreqprep(), reqprep(), and transmit_register().

{
   /* Initialize a request */
   memset(req, 0, sizeof(*req));
   if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
      goto e_return;
   if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
      goto e_free_data;
   req->method = sipmethod;
   req->header[0] = 0;
   ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
   req->len = ast_str_strlen(req->data);
   req->headers++;
   return 0;

e_free_data:
   ast_free(req->data);
   req->data = NULL;
e_return:
   return -1;
}
static int init_resp ( struct sip_request resp,
const char *  msg 
) [static]

Initialize SIP response, based on SIP request.

Definition at line 9738 of file chan_sip.c.

References ast_free, ast_str_create(), ast_str_set(), sip_request::content, sip_request::data, sip_request::header, sip_request::headers, sip_request::len, sip_request::method, SIP_MIN_PACKET, and SIP_RESPONSE.

Referenced by respprep().

{
   /* Initialize a response */
   memset(resp, 0, sizeof(*resp));
   resp->method = SIP_RESPONSE;
   if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
      goto e_return;
   if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
      goto e_free_data;
   resp->header[0] = 0;
   ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
   resp->len = resp->data->used;
   resp->headers++;
   return 0;

e_free_data:
   ast_free(resp->data);
   resp->data = NULL;
e_return:
   return -1;
}
static void initialize_initreq ( struct sip_pvt p,
struct sip_request req 
) [static]

Initialize the initital request packet in the pvt structure. This packet is used for creating replies and future requests in a dialog.

Definition at line 3425 of file chan_sip.c.

References ast_debug, ast_verbose(), sip_pvt::callid, copy_request(), sip_request::debug, sip_request::headers, sip_pvt::initreq, sip_request::lines, sip_request::method, parse_request(), sip_methods, and cfsip_methods::text.

Referenced by transmit_invite(), transmit_notify_custom(), transmit_notify_with_mwi(), transmit_notify_with_sipfrag(), transmit_register(), and transmit_reinvite_with_sdp().

{
   if (p->initreq.headers)
      ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
   else
      ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
   /* Use this as the basis */
   copy_request(&p->initreq, req);
   parse_request(&p->initreq);
   if (req->debug)
      ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
}
static void initreqprep ( struct sip_request req,
struct sip_pvt p,
int  sipmethod 
) [static]

Initiate new SIP request to peer/user.

Todo:
Need to add back the VXML URL here at some point, possibly use build_string for all this junk

Definition at line 11158 of file chan_sip.c.

References add_header(), add_route(), AST_DIGIT_ANYNUM, ast_inet_ntoa(), AST_PRES_ALLOWED, AST_PRES_RESTRICTION, ast_str_alloca, ast_str_append(), ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_uri_encode(), build_contact(), build_rpid(), CALLERID_UNKNOWN, sip_pvt::callid, sip_pvt::callingpres, ast_channel::cid, ast_callerid::cid_name, ast_callerid::cid_num, default_callerid, DEFAULT_MAX_FORWARDS, exten, sip_pvt::flags, sip_pvt::fromdomain, FROMDOMAIN_INVALID, sip_pvt::fromname, sip_pvt::fromuser, sip_pvt::fullcontact, init_req(), sip_pvt::lastmsg, sip_pvt::ocseq, sip_pvt::options, sip_pvt::our_contact, sip_pvt::ourip, ourport, sip_pvt::owner, sip_settings::pedanticsipchecking, sip_pvt::portinuri, sip_pvt::route, sip_pvt::rpid, sip_pvt::rpid_from, s, S_OR, sip_pvt::sa, sip_cfg, SIP_INVITE, sip_methods, SIP_NOTIFY, SIP_SENDRPID, sip_standard_port(), SIP_USEREQPHONE, SIPBUFSIZE, sip_pvt::socket, sip_pvt::tag, cfsip_methods::text, sip_pvt::theirtag, sip_pvt::todnid, sip_pvt::tohost, sip_socket::type, sip_pvt::uri, sip_invite_param::uri_options, sip_pvt::username, sip_pvt::via, and sip_invite_param::vxml_url.

Referenced by transmit_invite(), transmit_notify_custom(), and transmit_notify_with_mwi().

{
   struct ast_str *invite = ast_str_alloca(256);
   char from[256];
   char to[256];
   char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
   char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
   const char *l = NULL;   /* XXX what is this, exactly ? */
   const char *n = NULL;   /* XXX what is this, exactly ? */
   const char *d = NULL;   /* domain in from header */
   const char *urioptions = "";
   int ourport;

   if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
      const char *s = p->username;  /* being a string field, cannot be NULL */

      /* Test p->username against allowed characters in AST_DIGIT_ANY
         If it matches the allowed characters list, then sipuser = ";user=phone"
         If not, then sipuser = ""
      */
      /* + is allowed in first position in a tel: uri */
      if (*s == '+')
         s++;
      for (; *s; s++) {
         if (!strchr(AST_DIGIT_ANYNUM, *s) )
            break;
      }
      /* If we have only digits, add ;user=phone to the uri */
      if (!*s)
         urioptions = ";user=phone";
   }


   snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);

   d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
   if (p->owner) {
      l = p->owner->cid.cid_num;
      n = p->owner->cid.cid_name;
   }
   /* if we are not sending RPID and user wants his callerid restricted */
   if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
       ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
      l = CALLERID_UNKNOWN;
      n = l;
      d = FROMDOMAIN_INVALID;
   }
   if (ast_strlen_zero(l))
      l = default_callerid;
   if (ast_strlen_zero(n))
      n = l;
   /* Allow user to be overridden */
   if (!ast_strlen_zero(p->fromuser))
      l = p->fromuser;
   else /* Save for any further attempts */
      ast_string_field_set(p, fromuser, l);

   /* Allow user to be overridden */
   if (!ast_strlen_zero(p->fromname))
      n = p->fromname;
   else /* Save for any further attempts */
      ast_string_field_set(p, fromname, n);

   if (sip_cfg.pedanticsipchecking) {
      ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
      n = tmp_n;
      ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
      l = tmp_l;
   }

   ourport = ntohs(p->ourip.sin_port);
   if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
      snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
   else
      snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);

   /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
   if (!ast_strlen_zero(p->fullcontact)) {
      /* If we have full contact, trust it */
      ast_str_append(&invite, 0, "%s", p->fullcontact);
   } else {
      /* Otherwise, use the username while waiting for registration */
      ast_str_append(&invite, 0, "sip:");
      if (!ast_strlen_zero(p->username)) {
         n = p->username;
         if (sip_cfg.pedanticsipchecking) {
            ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
            n = tmp_n;
         }
         ast_str_append(&invite, 0, "%s@", n);
      }
      ast_str_append(&invite, 0, "%s", p->tohost);
      if (p->portinuri)
         ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
      ast_str_append(&invite, 0, "%s", urioptions);
   }

   /* If custom URI options have been provided, append them */
   if (p->options && !ast_strlen_zero(p->options->uri_options))
      ast_str_append(&invite, 0, ";%s", p->options->uri_options);
   
   /* This is the request URI, which is the next hop of the call
      which may or may not be the destination of the call
   */
   ast_string_field_set(p, uri, invite->str);
  
   if (!ast_strlen_zero(p->todnid)) {
      /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
      if (!strchr(p->todnid, '@')) {
         /* We have no domain in the dnid */
         snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
      } else {
         snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
      }
   } else {
      if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) { 
         /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
         snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
      } else if (p->options && p->options->vxml_url) {
         /* If there is a VXML URL append it to the SIP URL */
         snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
      } else 
         snprintf(to, sizeof(to), "<%s>", p->uri);
   }

   init_req(req, sipmethod, p->uri);
   /* now tmp_n is available so reuse it to build the CSeq */
   snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);

   add_header(req, "Via", p->via);
   add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
   /* This will be a no-op most of the time. However, under certain circumstances,
    * NOTIFY messages will use this function for preparing the request and should
    * have Route headers present.
    */
   add_route(req, p->route);

   /* Build Remote Party-ID and From */
   if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
      build_rpid(p);
      add_header(req, "From", p->rpid_from);
   } else 
      add_header(req, "From", from);
   add_header(req, "To", to);
   ast_string_field_set(p, exten, l);
   build_contact(p);
   add_header(req, "Contact", p->our_contact);
   add_header(req, "Call-ID", p->callid);
   add_header(req, "CSeq", tmp_n);
   if (!ast_strlen_zero(global_useragent))
      add_header(req, "User-Agent", global_useragent);
   if (!ast_strlen_zero(p->rpid))
      add_header(req, "Remote-Party-ID", p->rpid);
}
static const char * insecure2str ( int  mode) [static]

Convert Insecure setting to printable string.

Definition at line 15508 of file chan_sip.c.

References map_x_s().

Referenced by _sip_show_peer().

{
   return map_x_s(insecurestr, mode, "<error>");
}
static int interpret_t38_parameters ( struct sip_pvt p,
const struct ast_control_t38_parameters parameters 
) [static]

Helper function which updates T.38 capability information and triggers a reinvite.

Definition at line 6639 of file chan_sip.c.

References AST_CONTROL_T38_PARAMETERS, ast_queue_control_data(), AST_SCHED_DEL, AST_SCHED_DEL_UNREF, ast_set_flag, AST_T38_NEGOTIATED, AST_T38_REFUSED, AST_T38_REQUEST_NEGOTIATE, AST_T38_REQUEST_PARMS, AST_T38_REQUEST_TERMINATE, AST_T38_TERMINATED, ast_test_flag, ast_udptl_get_far_max_ifp(), ast_udptl_set_local_max_ifp(), change_t38_state(), dialog_unref(), FALSE, ast_control_t38_parameters::fill_bit_removal, sip_pvt::flags, sip_pvt::initreq, ast_control_t38_parameters::max_ifp, MIN, t38properties::our_parms, sip_pvt::owner, sip_pvt::pendinginvite, ast_control_t38_parameters::rate_management, ast_control_t38_parameters::request_response, SIP_NEEDREINVITE, SIP_PAGE2_T38SUPPORT, SIP_PENDINGBYE, t38properties::state, sip_pvt::t38, T38_DISABLED, T38_ENABLED, T38_LOCAL_REINVITE, T38_PEER_REINVITE, sip_pvt::t38id, t38properties::their_parms, ast_control_t38_parameters::transcoding_jbig, ast_control_t38_parameters::transcoding_mmr, transmit_reinvite_with_sdp(), transmit_response_reliable(), transmit_response_with_t38_sdp(), TRUE, sip_pvt::udptl, ast_control_t38_parameters::version, and XMIT_CRITICAL.

Referenced by sip_indicate().

{
   int res = 0;

   if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
      return -1;
   }
   switch (parameters->request_response) {
   case AST_T38_NEGOTIATED:
   case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
      /* Negotiation can not take place without a valid max_ifp value. */
      if (!parameters->max_ifp) {
         change_t38_state(p, T38_DISABLED);
         if (p->t38.state == T38_PEER_REINVITE) {
            AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
            transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
         }
         break;
      } else if (p->t38.state == T38_PEER_REINVITE) {
         AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
         p->t38.our_parms = *parameters;
         /* modify our parameters to conform to the peer's parameters,
          * based on the rules in the ITU T.38 recommendation
          */
         if (!p->t38.their_parms.fill_bit_removal) {
            p->t38.our_parms.fill_bit_removal = FALSE;
         }
         if (!p->t38.their_parms.transcoding_mmr) {
            p->t38.our_parms.transcoding_mmr = FALSE;
         }
         if (!p->t38.their_parms.transcoding_jbig) {
            p->t38.our_parms.transcoding_jbig = FALSE;
         }
         p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
         p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
         ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
         change_t38_state(p, T38_ENABLED);
         transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
      } else if (p->t38.state != T38_ENABLED) {
         p->t38.our_parms = *parameters;
         ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
         change_t38_state(p, T38_LOCAL_REINVITE);
         if (!p->pendinginvite) {
            transmit_reinvite_with_sdp(p, TRUE, FALSE);
         } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
            ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
         }
      }
      break;
   case AST_T38_TERMINATED:
   case AST_T38_REFUSED:
   case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
      if (p->t38.state == T38_PEER_REINVITE) {
         AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
         change_t38_state(p, T38_DISABLED);
         transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
      } else if (p->t38.state == T38_ENABLED)
         transmit_reinvite_with_sdp(p, FALSE, FALSE);
      break;
   case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
      struct ast_control_t38_parameters parameters = p->t38.their_parms;

      if (p->t38.state == T38_PEER_REINVITE) {
         AST_SCHED_DEL(sched, p->t38id);
         parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
         parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
         ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
         /* we need to return a positive value here, so that applications that
          * send this request can determine conclusively whether it was accepted or not...
          * older versions of chan_sip would just silently accept it and return zero.
          */
         res = AST_T38_REQUEST_PARMS;
      }
      break;
   }
   default:
      res = -1;
      break;
   }

   return res;
}
static void list_route ( struct sip_route route) [static]

List all routes - mostly for debugging.

Definition at line 12968 of file chan_sip.c.

References ast_verbose(), sip_route::hop, and sip_route::next.

Referenced by build_route().

{
   if (!route)
      ast_verbose("list_route: no route\n");
   else {
      for (;route; route = route->next)
         ast_verbose("list_route: hop: <%s>\n", route->hop);
   }
}
static int load_module ( void  ) [static]

PBX load module - initialization.

Todo:
Fix this XXX This must be all wrong XXXX

Definition at line 26457 of file chan_sip.c.

References ao2_t_container_alloc, ARRAY_LEN, ast_channel_register(), ast_check_realtime(), ast_cli_register_multiple(), ast_custom_function_register, ast_log(), ast_manager_register2(), AST_MODULE_LOAD_DECLINE, AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_SUCCESS, ast_realtime_require_field(), ast_register_application_xml, ast_rtp_proto_register(), ast_udptl_proto_register(), ast_verbose(), ASTOBJ_CONTAINER_INIT, CHANNEL_MODULE_LOAD, dialog_cmp_cb(), dialog_hash_cb(), EVENT_FLAG_REPORTING, EVENT_FLAG_SYSTEM, io_context_create(), io_context_destroy(), LOG_ERROR, manager_show_registry(), manager_sip_qualify_peer(), manager_sip_show_peer(), manager_sip_show_peers(), manager_sipnotify(), peer_cmp_cb(), peer_hash_cb(), peer_ipcmp_cb(), peer_iphash_cb(), regl, reload_config(), restart_monitor(), RQ_CHAR, RQ_INTEGER4, RQ_UINTEGER2, sched_context_create(), sched_context_destroy(), ast_channel_tech::send_digit_begin, SENTINEL, sip_addheader(), sip_dtmfmode(), sip_poke_all_peers(), sip_removeheader(), sip_send_all_mwi_subscriptions(), sip_send_all_registers(), sip_tech_info, submwil, threadt_cmp_cb(), and threadt_hash_cb().

{
   ast_verbose("SIP channel loading...\n");
   /* the fact that ao2_containers can't resize automatically is a major worry! */
   /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
   peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
   peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
   dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
   threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
   
   ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
   ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */

   if (!(sched = sched_context_create())) {
      ast_log(LOG_ERROR, "Unable to create scheduler context\n");
      return AST_MODULE_LOAD_FAILURE;
   }

   if (!(io = io_context_create())) {
      ast_log(LOG_ERROR, "Unable to create I/O context\n");
      sched_context_destroy(sched);
      return AST_MODULE_LOAD_FAILURE;
   }

   sip_reloadreason = CHANNEL_MODULE_LOAD;

   if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
      return AST_MODULE_LOAD_DECLINE;

   /* Prepare the version that does not require DTMF BEGIN frames.
    * We need to use tricks such as memcpy and casts because the variable
    * has const fields.
    */
   memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
   memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));

   /* Make sure we can register our sip channel type */
   if (ast_channel_register(&sip_tech)) {
      ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
      io_context_destroy(io);
      sched_context_destroy(sched);
      return AST_MODULE_LOAD_FAILURE;
   }

   /* Register all CLI functions for SIP */
   ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));

   /* Tell the RTP subdriver that we're here */
   ast_rtp_proto_register(&sip_rtp);

   /* Tell the UDPTL subdriver that we're here */
   ast_udptl_proto_register(&sip_udptl);

   /* Register dialplan applications */
   ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
   ast_register_application_xml(app_sipaddheader, sip_addheader);
   ast_register_application_xml(app_sipremoveheader, sip_removeheader);

   /* Register dialplan functions */
   ast_custom_function_register(&sip_header_function);
   ast_custom_function_register(&sippeer_function);
   ast_custom_function_register(&sipchaninfo_function);
   ast_custom_function_register(&checksipdomain_function);

   /* Register manager commands */
   ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
         "List SIP peers (text format)", mandescr_show_peers);
   ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
         "Show SIP peer (text format)", mandescr_show_peer);
   ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
         "Show SIP peer (text format)", mandescr_show_peer);   /*! \todo Fix this XXX This must be all wrong XXXX */
   ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
         "Show SIP registrations (text format)", mandescr_show_registry);
   ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
         "Send a SIP notify", mandescr_sipnotify);
   sip_poke_all_peers();   
   sip_send_all_registers();
   sip_send_all_mwi_subscriptions();

   /* And start the monitor for the first time */
   restart_monitor();

   ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
      "name", RQ_CHAR, 10,
      "ipaddr", RQ_CHAR, 15,
      "port", RQ_UINTEGER2, 5,
      "regseconds", RQ_INTEGER4, 11,
      "defaultuser", RQ_CHAR, 10,
      "fullcontact", RQ_CHAR, 35,
      "regserver", RQ_CHAR, 20,
      "useragent", RQ_CHAR, 20,
      "lastms", RQ_INTEGER4, 11,
      SENTINEL);

   return AST_MODULE_LOAD_SUCCESS;
}
static int local_attended_transfer ( struct sip_pvt transferer,
struct sip_dual current,
struct sip_request req,
int  seqno 
) [static]

Find all call legs and bridge transferee with target called from handle_request_refer.

Definition at line 21006 of file chan_sip.c.

References ast_channel::_state, ao2_t_ref, append_history, ast_bridged_channel(), ast_channel_unlock, ast_clear_flag, ast_debug, ast_set_flag, ast_state2str(), AST_STATE_RING, AST_STATE_RINGING, AST_STATE_UP, ast_streamfile(), ast_strlen_zero(), ast_waitstream(), attempt_transfer(), sip_pvt::callid, sip_dual::chan1, sip_dual::chan2, EVENT_FLAG_CALL, sip_pvt::flags, get_sip_pvt_byid_locked(), ast_channel::language, sip_refer::localtransfer, manager_event, ast_channel::name, sip_pvt::owner, pbx_builtin_getvar_helper(), sip_pvt::refer, REFER_200OK, REFER_FAILED, sip_refer::replaces_callid, sip_refer::replaces_callid_fromtag, sip_refer::replaces_callid_totag, SIP_DEFER_BYE_ON_TRANSFER, SIP_GOTREFER, sip_pvt_unlock, sip_refer::status, transmit_notify_with_sipfrag(), TRUE, ast_channel::uniqueid, and xfersound.

Referenced by handle_request_refer().

{
   struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
               /* Chan 2: Call from Asterisk to target */
   int res = 0;
   struct sip_pvt *targetcall_pvt;

   /* Check if the call ID of the replaces header does exist locally */
   if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag, 
      transferer->refer->replaces_callid_fromtag))) {
      if (transferer->refer->localtransfer) {
         /* We did not find the refered call. Sorry, can't accept then */
         /* Let's fake a response from someone else in order
            to follow the standard */
         transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
         append_history(transferer, "Xfer", "Refer failed");
         ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);  
         transferer->refer->status = REFER_FAILED;
         return -1;
      }
      /* Fall through for remote transfers that we did not find locally */
      ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
      return 0;
   }

   /* Ok, we can accept this transfer */
   append_history(transferer, "Xfer", "Refer accepted");
   if (!targetcall_pvt->owner) { /* No active channel */
      ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
      /* Cancel transfer */
      transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
      append_history(transferer, "Xfer", "Refer failed");
      ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
      transferer->refer->status = REFER_FAILED;
      sip_pvt_unlock(targetcall_pvt);
      if (targetcall_pvt)
         ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
      return -1;
   }

   /* We have a channel, find the bridge */
   target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
   target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */

   if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
      /* Wrong state of new channel */
      if (target.chan2) 
         ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
      else if (target.chan1->_state != AST_STATE_RING)
         ast_debug(4, "SIP attended transfer: Error: No target channel\n");
      else
         ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
   }

   /* Transfer */
   if (sipdebug) {
      if (current->chan2)  /* We have two bridges */
         ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
      else        /* One bridge, propably transfer of IVR/voicemail etc */
         ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
   }

   ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */

   /* Perform the transfer */
   manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Attended\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\n",
      transferer->owner->name,
      transferer->owner->uniqueid,
      transferer->callid,
      target.chan1->name,
      target.chan1->uniqueid);
   res = attempt_transfer(current, &target);
   sip_pvt_unlock(targetcall_pvt);
   if (res) {
      /* Failed transfer */
      transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
      append_history(transferer, "Xfer", "Refer failed");
      if (targetcall_pvt->owner)
         ast_channel_unlock(targetcall_pvt->owner);
      ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
   } else {
      /* Transfer succeeded! */
      const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");

      /* Tell transferer that we're done. */
      transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
      append_history(transferer, "Xfer", "Refer succeeded");
      transferer->refer->status = REFER_200OK;
      if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
         ast_waitstream(target.chan2, "");
      }
      if (targetcall_pvt->owner) {
         ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
         ast_channel_unlock(targetcall_pvt->owner);
      }
   }
   if (targetcall_pvt)
      ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
   return 1;
}
static int lws2sws ( char *  msgbuf,
int  len 
) [static]

Parse multiline SIP headers into one header This is enabled if pedanticsipchecking is enabled.

Definition at line 8160 of file chan_sip.c.

References sip_request::len.

Referenced by handle_request_do().

{
   int h = 0, t = 0; 
   int lws = 0; 

   for (; h < len;) { 
      /* Eliminate all CRs */ 
      if (msgbuf[h] == '\r') { 
         h++; 
         continue; 
      } 
      /* Check for end-of-line */ 
      if (msgbuf[h] == '\n') { 
         /* Check for end-of-message */ 
         if (h + 1 == len) 
            break; 
         /* Check for a continuation line */ 
         if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
            /* Merge continuation line */ 
            h++; 
            continue; 
         } 
         /* Propagate LF and start new line */ 
         msgbuf[t++] = msgbuf[h++]; 
         lws = 0;
         continue; 
      } 
      if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
         if (lws) { 
            h++; 
            continue; 
         } 
         msgbuf[t++] = msgbuf[h++]; 
         lws = 1; 
         continue; 
      } 
      msgbuf[t++] = msgbuf[h++]; 
      if (lws) 
         lws = 0; 
   } 
   msgbuf[t] = '\0'; 
   return t; 
}
static void make_our_tag ( char *  tagbuf,
size_t  len 
) [static]

Make our SIP dialog tag.

Definition at line 7367 of file chan_sip.c.

References ast_random().

Referenced by handle_request_invite(), handle_request_subscribe(), sip_alloc(), transmit_register(), and transmit_response_using_temp().

{
   snprintf(tagbuf, len, "as%08lx", ast_random());
}
static int manager_show_registry ( struct mansession s,
const struct message m 
) [static]

Show SIP registrations in the manager API.

Definition at line 15150 of file chan_sip.c.

References ast_strlen_zero(), astman_append(), astman_get_header(), astman_send_listack(), ASTOBJ_CONTAINER_TRAVERSE, ASTOBJ_RDLOCK, ASTOBJ_UNLOCK, regl, regstate2str(), STANDARD_SIP_PORT, and total.

Referenced by load_module().

{
   const char *id = astman_get_header(m, "ActionID");
   char idtext[256] = "";
   int total = 0;

   if (!ast_strlen_zero(id))
      snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);

   astman_send_listack(s, m, "Registrations will follow", "start");

   ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
      ASTOBJ_RDLOCK(iterator);
      astman_append(s,
         "Event: RegistryEntry\r\n"
         "%s"
         "Host: %s\r\n"
         "Port: %d\r\n"
         "Username: %s\r\n"
         "Refresh: %d\r\n"
         "State: %s\r\n"
         "RegistrationTime: %ld\r\n"
         "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
                 iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
      ASTOBJ_UNLOCK(iterator);
      total++;
   } while(0));

   astman_append(s,
      "Event: RegistrationsComplete\r\n"
      "EventList: Complete\r\n"
      "ListItems: %d\r\n"
      "%s"
      "\r\n", total, idtext);
   
   return 0;
}
static int manager_sip_qualify_peer ( struct mansession s,
const struct message m 
) [static]

Qualify SIP peers in the manager API.

Definition at line 15859 of file chan_sip.c.

References _sip_qualify_peer(), ast_strlen_zero(), astman_append(), astman_get_header(), and astman_send_error().

Referenced by load_module().

{
   const char *a[4];
   const char *peer;

   peer = astman_get_header(m, "Peer");
   if (ast_strlen_zero(peer)) {
      astman_send_error(s, m, "Peer: <name> missing.");
      return 0;
   }
   a[0] = "sip";
   a[1] = "qualify";
   a[2] = "peer";
   a[3] = peer;

   _sip_qualify_peer(1, -1, s, m, 4, a);
   astman_append(s, "\r\n\r\n" );
   return 0;
}
static int manager_sip_show_peer ( struct mansession s,
const struct message m 
) [static]

Show SIP peers in the manager API.

Definition at line 15800 of file chan_sip.c.

References _sip_show_peer(), ast_strlen_zero(), astman_append(), astman_get_header(), and astman_send_error().

Referenced by load_module().

{
   const char *a[4];
   const char *peer;

   peer = astman_get_header(m, "Peer");
   if (ast_strlen_zero(peer)) {
      astman_send_error(s, m, "Peer: <name> missing.");
      return 0;
   }
   a[0] = "sip";
   a[1] = "show";
   a[2] = "peer";
   a[3] = peer;

   _sip_show_peer(1, -1, s, m, 4, a);
   astman_append(s, "\r\n\r\n" );
   return 0;
}
static int manager_sip_show_peers ( struct mansession s,
const struct message m 
) [static]

Show SIP peers in the manager API.

Definition at line 15197 of file chan_sip.c.

References _sip_show_peers(), ast_strlen_zero(), astman_append(), astman_get_header(), astman_send_listack(), and total.

Referenced by load_module().

{
   const char *id = astman_get_header(m, "ActionID");
   const char *a[] = {"sip", "show", "peers"};
   char idtext[256] = "";
   int total = 0;

   if (!ast_strlen_zero(id))
      snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);

   astman_send_listack(s, m, "Peer status list will follow", "start");
   /* List the peers in separate manager events */
   _sip_show_peers(-1, &total, s, m, 3, a);
   /* Send final confirmation */
   astman_append(s,
   "Event: PeerlistComplete\r\n"
   "EventList: Complete\r\n"
   "ListItems: %d\r\n"
   "%s"
   "\r\n", total, idtext);
   return 0;
}
static int manager_sipnotify ( struct mansession s,
const struct message m 
) [static]

Definition at line 11875 of file chan_sip.c.

References ao2_t_link, ao2_t_unlink, ast_set_flag, ast_sip_ouraddrfor(), ast_strlen_zero(), ast_variables_destroy(), astman_get_header(), astman_get_variables(), astman_send_ack(), astman_send_error(), build_callid_pvt(), build_via(), create_addr(), dialog_ref(), dialog_unlink_all(), dialog_unref(), sip_pvt::flags, sip_pvt::ourip, sip_pvt::sa, sip_alloc(), SIP_NOTIFY, SIP_OUTGOING, sip_scheddestroy(), SIP_TRANS_TIMEOUT, transmit_notify_custom(), and TRUE.

Referenced by load_module().

{
   const char *channame = astman_get_header(m, "Channel");
   struct ast_variable *vars = astman_get_variables(m);
   struct sip_pvt *p;

   if (ast_strlen_zero(channame)) {
      astman_send_error(s, m, "SIPNotify requires a channel name");
      return 0;
   }

   if (!strncasecmp(channame, "sip/", 4)) {
      channame += 4;
   }

   if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
      astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
      return 0;
   }

   if (create_addr(p, channame, NULL, 0)) {
      /* Maybe they're not registered, etc. */
      dialog_unlink_all(p, TRUE, TRUE);
      dialog_unref(p, "unref dialog inside for loop" );
      /* sip_destroy(p); */
      astman_send_error(s, m, "Could not create address");
      return 0;
   }

   /* Notify is outgoing call */
   ast_set_flag(&p->flags[0], SIP_OUTGOING);

   /* Recalculate our side, and recalculate Call ID */
   ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
   build_via(p);
   ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
   build_callid_pvt(p);
   ao2_t_link(dialogs, p, "Linking in new name");
   dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
   sip_scheddestroy(p, SIP_TRANS_TIMEOUT);

   if (!transmit_notify_custom(p, vars)) {
      astman_send_ack(s, m, "Notify Sent");
   } else {
      astman_send_error(s, m, "Unable to send notify");
   }
   ast_variables_destroy(vars);
   return 0;
}
static int map_s_x ( const struct _map_x_s table,
const char *  s,
int  errorvalue 
) [static]

map from a string to an integer value, case insensitive. If no match is found, return errorvalue.

Definition at line 2755 of file chan_sip.c.

References _map_x_s::s, and _map_x_s::x.

Referenced by str2dtmfmode(), str2stmode(), and str2strefresher().

{
   const struct _map_x_s *cur;

   for (cur = table; cur->s; cur++)
      if (!strcasecmp(cur->s, s))
         return cur->x;
   return errorvalue;
}
static const char* map_x_s ( const struct _map_x_s table,
int  x,
const char *  errorstring 
) [static]

map from an integer value to a string. If no match is found, return errorstring

Definition at line 2742 of file chan_sip.c.

References _map_x_s::s, and _map_x_s::x.

Referenced by dtmfmode2str(), faxec2str(), insecure2str(), nat2str(), referstatus2str(), regstate2str(), stmode2str(), and strefresher2str().

{
   const struct _map_x_s *cur;

   for (cur = table; cur->s; cur++)
      if (cur->x == x)
         return cur->s;
   return errorstring;
}
static int method_match ( enum sipmethod  id,
const char *  name 
) [static]

returns true if 'name' (with optional trailing whitespace) matches the sip method 'id'. Strictly speaking, SIP methods are case SENSITIVE, but we do a case-insensitive comparison to be more tolerant. following Jon Postel's rule: Be gentle in what you accept, strict with what you send

Definition at line 3522 of file chan_sip.c.

References sip_methods, and text.

Referenced by __sip_autodestruct(), __sip_semi_ack(), and find_sip_method().

{
   int len = strlen(sip_methods[id].text);
   int l_name = name ? strlen(name) : 0;
   /* true if the string is long enough, and ends with whitespace, and matches */
   return (l_name >= len && name[len] < 33 &&
      !strncasecmp(sip_methods[id].text, name, len));
}
static void mwi_event_cb ( const struct ast_event event,
void *  userdata 
) [static]

Receive MWI events that we have subscribed to.

Definition at line 13299 of file chan_sip.c.

References ao2_lock(), ao2_unlock(), and sip_send_mwi_to_peer().

Referenced by add_peer_mwi_subs().

{
   struct sip_peer *peer = userdata;

   ao2_lock(peer);
   sip_send_mwi_to_peer(peer, event, 0);
   ao2_unlock(peer);
}
static const char * nat2str ( int  nat) [static]

Convert NAT setting to text string.

Definition at line 14932 of file chan_sip.c.

References map_x_s().

Referenced by _sip_show_peer(), sip_show_channel(), sip_show_settings(), and sip_show_users().

{
   return map_x_s(natmodes, nat, "Unknown");
}
static struct sip_proxy* obproxy_get ( struct sip_pvt dialog,
struct sip_peer peer 
) [static, read]

Get default outbound proxy or global proxy.

Definition at line 3497 of file chan_sip.c.

References append_history, ast_debug, sip_proxy::name, sip_settings::outboundproxy, sip_peer::outboundproxy, and sip_cfg.

Referenced by __sip_subscribe_mwi_do(), create_addr(), and create_addr_from_peer().

{
   if (peer && peer->outboundproxy) {
      if (sipdebug)
         ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
      append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
      return peer->outboundproxy;
   }
   if (sip_cfg.outboundproxy.name[0]) {
      if (sipdebug)
         ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
      append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
      return &sip_cfg.outboundproxy;
   }
   if (sipdebug)
      ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
   return NULL;
}
static void parse_copy ( struct sip_request dst,
const struct sip_request src 
) [static]

Copy SIP request, parse it.

Definition at line 4341 of file chan_sip.c.

References copy_request(), and parse_request().

Referenced by send_request(), and send_response().

{
   copy_request(dst, src);
   parse_request(dst);
}
int parse_minse ( const char *  p_hdrval,
int *const  p_interval 
) [static]

Session-Timers: Function for parsing Min-SE header.

Definition at line 23307 of file chan_sip.c.

References ast_debug, ast_log(), ast_skip_blanks(), ast_strlen_zero(), and LOG_WARNING.

Referenced by handle_request_invite(), and proc_422_rsp().

{
   if (ast_strlen_zero(p_hdrval)) {
      ast_log(LOG_WARNING, "Null Min-SE header\n");
      return -1;
   }

   *p_interval = 0;
   p_hdrval = ast_skip_blanks(p_hdrval);
   if (!sscanf(p_hdrval, "%30d", p_interval)) {
      ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
      return -1;
   }

   ast_debug(2, "Received Min-SE: %d\n", *p_interval);
   return 0;
}
static void parse_moved_contact ( struct sip_pvt p,
struct sip_request req 
) [static]

Parse 302 Moved temporalily response.

Todo:
XXX Doesn't redirect over TLS on sips: uri's. If we get a redirect to a SIPS: uri, this needs to be going back to the dialplan (this is a request for a secure signalling path). Note that transport=tls is deprecated, but we need to support it on incoming requests.

Definition at line 18012 of file chan_sip.c.

References ao2_ref, ast_copy_string(), ast_debug, ast_string_field_build, ast_string_field_set, ast_test_flag, ast_uri_decode(), sip_pvt::flags, get_header(), get_in_brackets(), get_transport(), sip_pvt::owner, pbx_builtin_setvar_helper(), remove_uri_parameters(), s, set_socket_transport(), SIP_PROMISCREDIR, SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, SIP_TRANSPORT_UDP, SIPBUFSIZE, sip_pvt::socket, strcasestr(), and sip_socket::tcptls_session.

Referenced by handle_response().

{
   char tmp[SIPBUFSIZE];
   char *s, *e, *t, *trans;
   char *domain;
   enum sip_transport transport = SIP_TRANSPORT_UDP;

   ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
   if ((t = strchr(tmp, ',')))
      *t = '\0';

   s = get_in_brackets(tmp);
   if ((trans = strcasestr(s, ";transport="))) do {
      trans += 11;

      if ((e = strchr(trans, ';')))
         *e = '\0';

      if (!strncasecmp(trans, "tcp", 3))
         transport = SIP_TRANSPORT_TCP;
      else if (!strncasecmp(trans, "tls", 3))
         transport = SIP_TRANSPORT_TLS;
      else {
         if (strncasecmp(trans, "udp", 3))
            ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
         /* This will assume UDP for all unknown transports */
         transport = SIP_TRANSPORT_UDP;
      }
   } while(0);
   s = remove_uri_parameters(s);

   if (p->socket.tcptls_session) {
      ao2_ref(p->socket.tcptls_session, -1);
      p->socket.tcptls_session = NULL;
   }

   set_socket_transport(&p->socket, transport);

   if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
      char *host = NULL;
      if (!strncasecmp(s, "sip:", 4))
         s += 4;
      else if (!strncasecmp(s, "sips:", 5))
         s += 5;
      e = strchr(s, '/');
      if (e)
         *e = '\0';
      if ((host = strchr(s, '@'))) {
         *host++ = '\0';
         ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
         if (p->owner)
            ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
      } else {
         ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
         if (p->owner)
            ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
      }
   } else {
      e = strchr(tmp, '@');
      if (e) {
         *e++ = '\0';
         domain = e;
      } else {
         /* No username part */
         domain = tmp;
      }
      e = strchr(tmp, '/');   /* WHEN do we hae a forward slash in the URI? */
      if (e)
         *e = '\0';

      if (!strncasecmp(s, "sip:", 4))
         s += 4;
      else if (!strncasecmp(s, "sips:", 5))
         s += 5;
      e = strchr(s, ';');  /* And username ; parameters? */
      if (e)
         *e = '\0';  
      ast_uri_decode(s);
      ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
      if (p->owner) {
         pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
         ast_string_field_set(p->owner, call_forward, s);
      }
   }
}
static int parse_ok_contact ( struct sip_pvt pvt,
struct sip_request req 
) [static]

Save contact header for 200 OK on INVITE.

Definition at line 12643 of file chan_sip.c.

References ast_copy_string(), ast_string_field_set, get_header(), get_in_brackets(), SIPBUFSIZE, and TRUE.

Referenced by handle_request_invite(), handle_request_subscribe(), and handle_response_invite().

{
   char contact[SIPBUFSIZE]; 
   char *c;

   /* Look for brackets */
   ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
   c = get_in_brackets(contact);

   /* Save full contact to call pvt for later bye or re-invite */
   ast_string_field_set(pvt, fullcontact, c);

   /* Save URI for later ACKs, BYE or RE-invites */
   ast_string_field_set(pvt, okcontacturi, c);

   /* We should return false for URI:s we can't handle,
      like tel:, mailto:,ldap: etc */
   return TRUE;      
}
static enum parse_register_result parse_register_contact ( struct sip_pvt pvt,
struct sip_peer p,
struct sip_request req 
) [static]

Parse contact header and save registration (peer registration)

Todo:
Check NAPTR/SRV if we have not got a port in the URI

Definition at line 12728 of file chan_sip.c.

References __get_header(), sip_peer::addr, ao2_t_link, ao2_t_unlink, ast_apply_ha(), ast_copy_string(), ast_db_put(), ast_debug, ast_gethostbyname(), ast_inet_ntoa(), ast_log(), ast_sched_add(), AST_SCHED_DEL_UNREF, ast_sched_when(), AST_SENSE_ALLOW, ast_strdupa, ast_string_field_build, ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_verb, ast_verbose(), sip_peer::contactha, copy_socket_data(), default_expiry, sip_peer::default_outbound_transport, destroy_association(), EVENT_FLAG_SYSTEM, sip_peer::expire, expire_register(), sip_pvt::expiry, FALSE, sip_peer::flags, sip_peer::fullcontact, get_header(), get_in_brackets(), get_transport_str2enum(), hp, inaddrcmp(), sip_peer::is_realtime, sip_peer::lastms, LOG_NOTICE, LOG_WARNING, manager_event, max_expiry, min_expiry, sip_peer::name, PARSE_REGISTER_DENIED, PARSE_REGISTER_FAILED, PARSE_REGISTER_QUERY, PARSE_REGISTER_UPDATE, parse_uri(), port_str2int(), sip_peer::portinuri, sip_pvt::recv, ref_peer(), register_peer_exten(), sip_peer::rt_fromcontact, s, set_socket_transport(), SIP_NAT_ROUTE, SIP_PAGE2_RTCACHEFRIENDS, sip_poke_peer(), SIP_TRANSPORT_TLS, SIP_TRANSPORT_UDP, SIPBUFSIZE, sip_pvt::sipoptions, sip_peer::sipoptions, sip_peer::socket, sip_request::socket, sip_pvt::socket, STANDARD_SIP_PORT, STANDARD_TLS_PORT, strcasestr(), strsep(), sip_peer::transports, TRUE, sip_socket::type, unref_peer(), sip_peer::useragent, sip_peer::username, VERBOSE_PREFIX_3, and VERBOSITY_ATLEAST.

Referenced by register_verify().

{
   char contact[SIPBUFSIZE];
   char data[SIPBUFSIZE];
   const char *expires = get_header(req, "Expires");
   int expire = atoi(expires);
   char *curi, *host, *pt, *transport;
   int port;
   int transport_type;
   const char *useragent;
   struct hostent *hp;
   struct ast_hostent ahp;
   struct sockaddr_in oldsin, testsin;
   char *firstcuri = NULL;
   int start = 0;
   int wildcard_found = 0;
   int single_binding_found;

   ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));

   if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
      char *s = strcasestr(contact, ";expires=");
      if (s) {
         expires = strsep(&s, ";"); /* trim ; and beyond */
         if (sscanf(expires + 9, "%30d", &expire) != 1)
            expire = default_expiry;
      } else {
         /* Nothing has been specified */
         expire = default_expiry;
      }
   }

   copy_socket_data(&pvt->socket, &req->socket);

   do {
      /* Look for brackets */
      curi = contact;
      if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
         strsep(&curi, ";");  /* This is Header options, not URI options */
      curi = get_in_brackets(contact);
      if (!firstcuri) {
         firstcuri = ast_strdupa(curi);
      }

      if (!strcasecmp(curi, "*")) {
         wildcard_found = 1;
      } else {
         single_binding_found = 1;
      }

      if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
         /* Contact header parameter "*" detected, so punt if: Expires header is missing,
          * Expires value is not zero, or another Contact header is present. */
         return PARSE_REGISTER_FAILED;
      }

      ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
   } while (!ast_strlen_zero(contact));
   curi = firstcuri;

   /* if they did not specify Contact: or Expires:, they are querying
      what we currently have stored as their contact address, so return
      it
   */
   if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
      /* If we have an active registration, tell them when the registration is going to expire */
      if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
         pvt->expiry = ast_sched_when(sched, peer->expire);
      return PARSE_REGISTER_QUERY;
   } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
      /* This means remove all registrations and return OK */
      memset(&peer->addr, 0, sizeof(peer->addr));
      set_socket_transport(&peer->socket, peer->default_outbound_transport);

      AST_SCHED_DEL_UNREF(sched, peer->expire,
            unref_peer(peer, "remove register expire ref"));

      destroy_association(peer);

      register_peer_exten(peer, FALSE);   /* Remove extension from regexten= setting in sip.conf */
      ast_string_field_set(peer, fullcontact, "");
      ast_string_field_set(peer, useragent, "");
      peer->sipoptions = 0;
      peer->lastms = 0;
      peer->portinuri = 0;
      pvt->expiry = 0;

      ast_verb(3, "Unregistered SIP '%s'\n", peer->name);

      manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
      return PARSE_REGISTER_UPDATE;
   }

   /* Store whatever we got as a contact from the client */
   ast_string_field_set(peer, fullcontact, curi);

   /* For the 200 OK, we should use the received contact */
   ast_string_field_build(pvt, our_contact, "<%s>", curi);

   /* Make sure it's a SIP URL */
   if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
      ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
   }

   /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records. 
      The domain part is actually a host. */
   peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;

   /* handle the transport type specified in Contact header. */
   if ((transport_type = get_transport_str2enum(transport))) {
      /* if the port is not specified but the transport is, make sure to set the
       * default port to match the specified transport.  This may or may not be the
       * same transport used by the pvt struct for the Register dialog. */
      
      port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
   } else {
      port = port_str2int(pt, STANDARD_SIP_PORT);
      transport_type = pvt->socket.type;
   }

   /* if the peer's socket type is different than the Registration
    * transport type, change it.  If it got this far, it is a
    * supported type, but check just in case */
   if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
      set_socket_transport(&peer->socket, transport_type);
   }

   oldsin = peer->addr;

   /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
   if (peer->addr.sin_addr.s_addr) {
      ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
   }

   if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
      /* use the data provided in the Contact header for call routing */
      ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
      /* XXX This could block for a long time XXX */
      /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
      hp = ast_gethostbyname(host, &ahp);
      if (!hp)  {
         ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
         ast_string_field_set(peer, fullcontact, "");
         ast_string_field_set(pvt, our_contact, "");
         return PARSE_REGISTER_FAILED;
      }
      peer->addr.sin_family = AF_INET;
      memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
      peer->addr.sin_port = htons(port);
   } else {
      /* Don't trust the contact field.  Just use what they came to us
         with */
      ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
      peer->addr = pvt->recv;
   }

   /* Check that they're allowed to register at this IP */
   memcpy(&testsin.sin_addr, &peer->addr.sin_addr, sizeof(testsin.sin_addr));
   if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
         ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
      ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
      ast_string_field_set(peer, fullcontact, "");
      ast_string_field_set(pvt, our_contact, "");
      return PARSE_REGISTER_DENIED;
   }

   /* if the Contact header information copied into peer->addr matches the
    * received address, and the transport types are the same, then copy socket
    * data into the peer struct */
   if ((peer->socket.type == pvt->socket.type) &&
      (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
      (peer->addr.sin_port == pvt->recv.sin_port)){

      copy_socket_data(&peer->socket, &pvt->socket);
   }

   /* Now that our address has been updated put ourselves back into the container for lookups */
   ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");

   /* Save SIP options profile */
   peer->sipoptions = pvt->sipoptions;

   if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
      ast_string_field_set(peer, username, curi);

   AST_SCHED_DEL_UNREF(sched, peer->expire,
         unref_peer(peer, "remove register expire ref"));

   if (expire > max_expiry)
      expire = max_expiry;
   if (expire < min_expiry)
      expire = min_expiry;
   if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
      peer->expire = -1;
   } else {
      peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
            ref_peer(peer, "add registration ref"));
      if (peer->expire == -1) {
         unref_peer(peer, "remote registration ref");
      }
   }
   pvt->expiry = expire;
   snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), expire, peer->username, peer->fullcontact);
   /* Saving TCP connections is useless, we won't be able to reconnect 
      XXX WHY???? XXX
      \todo Fix this immediately.
   */
   if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
      ast_db_put("SIP/Registry", peer->name, data);
   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", peer->name,  ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port));

   /* Is this a new IP address for us? */
   if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
      ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port));
   }
   sip_poke_peer(peer, 0);
   register_peer_exten(peer, 1);
   
   /* Save User agent */
   useragent = get_header(req, "User-Agent");
   if (strcasecmp(useragent, peer->useragent)) {
      ast_string_field_set(peer, useragent, useragent);
      ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
   }
   return PARSE_REGISTER_UPDATE;
}
static int parse_request ( struct sip_request req) [static]

Parse a SIP message.

Note:
this function is used both on incoming and outgoing packets

Definition at line 8207 of file chan_sip.c.

References ast_debug, ast_log(), ast_str_strlen(), ast_strlen_zero(), sip_request::data, determine_firstline_parts(), sip_request::header, sip_request::headers, sip_request::line, sip_request::lines, LOG_WARNING, SIP_MAX_HEADERS, and SIP_MAX_LINES.

Referenced by _sip_tcp_helper_thread(), handle_request_do(), initialize_initreq(), and parse_copy().

{
   char *c = req->data->str;
   ptrdiff_t *dst = req->header;
   int i = 0, lim = SIP_MAX_HEADERS - 1;
   unsigned int skipping_headers = 0;
   ptrdiff_t current_header_offset = 0;
   char *previous_header = "";

   req->header[0] = 0;
   req->headers = -1;   /* mark that we are working on the header */
   for (; *c; c++) {
      if (*c == '\r') {    /* remove \r */
         *c = '\0';
      } else if (*c == '\n') {   /* end of this line */
         *c = '\0';
         current_header_offset = (c + 1) - req->data->str;
         previous_header = req->data->str + dst[i];
         if (skipping_headers) {
            /* check to see if this line is blank; if so, turn off
               the skipping flag, so the next line will be processed
               as a body line */
            if (ast_strlen_zero(previous_header)) {
               skipping_headers = 0;
            }
            dst[i] = current_header_offset; /* record start of next line */
            continue;
         }
         if (sipdebug) {
            ast_debug(4, "%7s %2d [%3d]: %s\n",
                 req->headers < 0 ? "Header" : "Body",
                 i, (int) strlen(previous_header), previous_header);
         }
         if (ast_strlen_zero(previous_header) && req->headers < 0) {
            req->headers = i; /* record number of header lines */
            dst = req->line;  /* start working on the body */
            i = 0;
            lim = SIP_MAX_LINES - 1;
         } else { /* move to next line, check for overflows */
            if (i++ == lim) {
               /* if we're processing headers, then skip any remaining
                  headers and move on to processing the body, otherwise
                  we're done */
               if (req->headers != -1) {
                  break;
               } else {
                  req->headers = i;
                  dst = req->line;
                  i = 0;
                  lim = SIP_MAX_LINES - 1;
                  skipping_headers = 1;
               }
            }
         }
         dst[i] = current_header_offset; /* record start of next line */
      }
   }

   /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
      but since some devices send without, we'll be generous in what we accept. However,
      if we've already reached the maximum number of lines for portion of the message
      we were parsing, we can't accept any more, so just ignore it.
   */
   previous_header = req->data->str + dst[i];
   if ((i < lim) && !ast_strlen_zero(previous_header)) {
      if (sipdebug) {
         ast_debug(4, "%7s %2d [%3d]: %s\n",
              req->headers < 0 ? "Header" : "Body",
              i, (int) strlen(previous_header), previous_header );
      }
      i++;
   }

   /* update count of header or body lines */
   if (req->headers >= 0) {   /* we are in the body */
      req->lines = i;
   } else {       /* no body */
      req->headers = i;
      req->lines = 0;
      /* req->data->used will be a NULL byte */
      req->line[0] = ast_str_strlen(req->data);
   }

   if (*c) {
      ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
   }

   /* Split up the first line parts */
   return determine_firstline_parts(req);
}
int parse_session_expires ( const char *  p_hdrval,
int *const  p_interval,
enum st_refresher *const  p_ref 
) [static]

Session-Timers: Function for parsing Session-Expires header.

Definition at line 23327 of file chan_sip.c.

References ast_debug, ast_log(), ast_skip_blanks(), ast_strdupa, ast_strlen_zero(), LOG_WARNING, SESSION_TIMER_REFRESHER_AUTO, SESSION_TIMER_REFRESHER_UAC, SESSION_TIMER_REFRESHER_UAS, and strsep().

Referenced by handle_request_invite(), and handle_response_invite().

{
   char *p_token;
   int  ref_idx;
   char *p_se_hdr;

   if (ast_strlen_zero(p_hdrval)) {
      ast_log(LOG_WARNING, "Null Session-Expires header\n");
      return -1;
   }

   *p_ref = SESSION_TIMER_REFRESHER_AUTO;
   *p_interval = 0;

   p_se_hdr = ast_strdupa(p_hdrval);
   p_se_hdr = ast_skip_blanks(p_se_hdr);

   while ((p_token = strsep(&p_se_hdr, ";"))) {
      p_token = ast_skip_blanks(p_token);
      if (!sscanf(p_token, "%30d", p_interval)) {
         ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
         return -1;
      }

      ast_debug(2, "Session-Expires: %d\n", *p_interval);

      if (!p_se_hdr)
         continue;

      p_se_hdr = ast_skip_blanks(p_se_hdr);
      ref_idx = strlen("refresher=");
      if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
         p_se_hdr += ref_idx;
         p_se_hdr = ast_skip_blanks(p_se_hdr);

         if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
            *p_ref = SESSION_TIMER_REFRESHER_UAC;
            ast_debug(2, "Refresher: UAC\n");
         } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
            *p_ref = SESSION_TIMER_REFRESHER_UAS;
            ast_debug(2, "Refresher: UAS\n");
         } else {
            ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
            return -1;
         }
         break;
      }
   }
   return 0;
}
static unsigned int parse_sip_options ( struct sip_pvt pvt,
const char *  supported 
) [static]

Parse supported header in incoming packet.

Definition at line 3546 of file chan_sip.c.

References ARRAY_LEN, ast_debug, ast_skip_blanks(), ast_strdupa, ast_strlen_zero(), FALSE, cfsip_options::id, sip_request::next, SIP_OPT_UNKNOWN, sip_options, sip_pvt::sipoptions, text, and TRUE.

Referenced by handle_request_invite().

{
   char *next, *sep;
   char *temp;
   unsigned int profile = 0;
   int i, found;

   if (ast_strlen_zero(supported) )
      return 0;
   temp = ast_strdupa(supported);

   if (sipdebug)
      ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);

   for (next = temp; next; next = sep) {
      found = FALSE;
      if ( (sep = strchr(next, ',')) != NULL)
         *sep++ = '\0';
      next = ast_skip_blanks(next);
      if (sipdebug)
         ast_debug(3, "Found SIP option: -%s-\n", next);
      for (i = 0; i < ARRAY_LEN(sip_options); i++) {
         if (!strcasecmp(next, sip_options[i].text)) {
            profile |= sip_options[i].id;
            found = TRUE;
            if (sipdebug)
               ast_debug(3, "Matched SIP option: %s\n", next);
            break;
         }
      }

      /* This function is used to parse both Suported: and Require: headers.
      Let the caller of this function know that an unknown option tag was 
      encountered, so that if the UAC requires it then the request can be 
      rejected with a 420 response. */
      if (!found)
         profile |= SIP_OPT_UNKNOWN;

      if (!found && sipdebug) {
         if (!strncasecmp(next, "x-", 2))
            ast_debug(3, "Found private SIP option, not supported: %s\n", next);
         else
            ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
      }
   }

   if (pvt)
      pvt->sipoptions = profile;
   return profile;
}
static int parse_uri ( char *  uri,
const char *  scheme,
char **  ret_name,
char **  pass,
char **  domain,
char **  port,
char **  options,
char **  transport 
) [static]

* parses a URI in its components.

Note:
  • If scheme is specified, drop it from the top.
  • If a component is not requested, do not split around it.
  • Multiple scheme's can be specified ',' delimited. ex: "sip:,sips:"

This means that if we don't have domain, we cannot split name:pass and domain:port. It is safe to call with ret_name, pass, domain, port pointing all to the same place. Init pointers to empty string so we never get NULL dereferencing. Overwrites the string. return 0 on success, other values on error.

 * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
 * 

Definition at line 4594 of file chan_sip.c.

References ast_debug, ast_strdupa, ast_strlen_zero(), name, strsep(), type, and sip_pvt::uri.

Referenced by __set_address_from_contact(), check_user_full(), and parse_register_contact().

{
   char *name = NULL;
   int error = 0;

   /* init field as required */
   if (pass)
      *pass = "";
   if (port)
      *port = "";
   if (scheme) {
      int l;
      char *scheme2 = ast_strdupa(scheme);
      char *cur = strsep(&scheme2, ",");
      for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
         l = strlen(cur);
         if (!strncasecmp(uri, cur, l)) {
            uri += l;
            break;
         }
      }
      if (ast_strlen_zero(cur)) {
         ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
         error = -1;
      }
   }
   if (transport) {
      char *t, *type = "";
      *transport = "";
      if ((t = strstr(uri, "transport="))) {
         strsep(&t, "=");
         if ((type = strsep(&t, ";"))) {
            *transport = type;
         }
      }
   }

   if (!domain) {
      /* if we don't want to split around domain, keep everything as a name,
       * so we need to do nothing here, except remember why.
       */
   } else {
      /* store the result in a temp. variable to avoid it being
       * overwritten if arguments point to the same place.
       */
      char *c, *dom = "";

      if ((c = strchr(uri, '@')) == NULL) {
         /* domain-only URI, according to the SIP RFC. */
         dom = uri;
         name = "";
      } else {
         *c++ = '\0';
         dom = c;
         name = uri;
      }

      /* Remove options in domain and name */
      dom = strsep(&dom, ";");
      name = strsep(&name, ";");

      if (port && (c = strchr(dom, ':'))) { /* Remove :port */
         *c++ = '\0';
         *port = c;
      }
      if (pass && (c = strchr(name, ':'))) { /* user:password */
         *c++ = '\0';
         *pass = c;
      }
      *domain = dom;
   }
   if (ret_name)  /* same as for domain, store the result only at the end */
      *ret_name = name;
   if (options)
      *options = uri ? uri : "";

   return error;
}
static struct sip_via * parse_via ( const char *  header) [static, read]

Parse a Via header.

This function parses the Via header and processes it according to section 18.2 of RFC 3261 and RFC 3581. Since we don't have a transport layer, we only care about the maddr and ttl parms. The received and rport params are not parsed.

Note:
This function fails to parse some odd combinations of SWS in parameter lists.
 VIA syntax. RFC 3261 section 25.1
 Via               =  ( "Via" / "v" ) HCOLON via-parm *(COMMA via-parm)
 via-parm          =  sent-protocol LWS sent-by *( SEMI via-params )
 via-params        =  via-ttl / via-maddr
                   / via-received / via-branch
                   / via-extension
 via-ttl           =  "ttl" EQUAL ttl
 via-maddr         =  "maddr" EQUAL host
 via-received      =  "received" EQUAL (IPv4address / IPv6address)
 via-branch        =  "branch" EQUAL token
 via-extension     =  generic-param
 sent-protocol     =  protocol-name SLASH protocol-version
                   SLASH transport
 protocol-name     =  "SIP" / token
 protocol-version  =  token
 transport         =  "UDP" / "TCP" / "TLS" / "SCTP"
                   / other-transport
 sent-by           =  host [ COLON port ]
 ttl               =  1*3DIGIT ; 0 to 255

Definition at line 7591 of file chan_sip.c.

References ast_calloc, ast_log(), ast_skip_blanks(), ast_strdup, ast_strlen_zero(), sip_via::branch, free_via(), LOG_ERROR, sip_via::maddr, sip_via::port, sip_via::protocol, sip_via::sent_by, strsep(), sip_via::ttl, and sip_via::via.

Referenced by process_via().

{
   struct sip_via *v = ast_calloc(1, sizeof(*v));
   char *via, *parm;

   if (!v) {
      return NULL;
   }

   v->via = ast_strdup(header);
   v->ttl = 1;

   via = v->via;

   if (ast_strlen_zero(via)) {
      ast_log(LOG_ERROR, "received request without a Via header\n");
      free_via(v);
      return NULL;
   }

   /* seperate the first via-parm */
   via = strsep(&via, ",");

   /* chop off sent-protocol */
   v->protocol = strsep(&via, " \t\r\n");
   if (ast_strlen_zero(v->protocol)) {
      ast_log(LOG_ERROR, "missing sent-protocol in Via header\n");
      free_via(v);
      return NULL;
   }
   v->protocol = ast_skip_blanks(v->protocol);

   if (via) {
      via = ast_skip_blanks(via);
   }

   /* chop off sent-by */
   v->sent_by = strsep(&via, "; \t\r\n");
   if (ast_strlen_zero(v->sent_by)) {
      ast_log(LOG_ERROR, "missing sent-by in Via header\n");
      free_via(v);
      return NULL;
   }
   v->sent_by = ast_skip_blanks(v->sent_by);

   /* store the port */
   if ((parm = strchr(v->sent_by, ':'))) {
      char *endptr;

      v->port = strtol(++parm, &endptr, 10);
   }

   /* evaluate any via-parms */
   while ((parm = strsep(&via, "; \t\r\n"))) {
      char *c;
      if ((c = strstr(parm, "maddr="))) {
         v->maddr = ast_skip_blanks(c + sizeof("maddr=") - 1);
      } else if ((c = strstr(parm, "branch="))) {
         v->branch = ast_skip_blanks(c + sizeof("branch=") - 1);
      } else if ((c = strstr(parm, "ttl="))) {
         char *endptr;
         c = ast_skip_blanks(c + sizeof("ttl=") - 1);
         v->ttl = strtol(c, &endptr, 10);

         /* make sure we got a valid ttl value */
         if (c == endptr) {
            v->ttl = 1;
         }
      }
   }

   return v;
}
static int peer_cmp_cb ( void *  obj,
void *  arg,
int  flags 
) [static]
Note:
The only member of the peer used here is the name field

Definition at line 2055 of file chan_sip.c.

References CMP_MATCH, CMP_STOP, and sip_peer::name.

Referenced by load_module().

{
   struct sip_peer *peer = obj, *peer2 = arg;

   return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
}
static int peer_dump_func ( void *  userobj,
void *  arg,
int  flags 
) [static]

Definition at line 15421 of file chan_sip.c.

References ao2_t_ref, ast_cli(), and sip_peer::name.

Referenced by sip_show_objects().

{
   struct sip_peer *peer = userobj;
   int refc = ao2_t_ref(userobj, 0, "");
   int *fd = arg;
   
   ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n", 
          peer->name, 0, refc);
   return 0;
}
static int peer_hash_cb ( const void *  obj,
const int  flags 
) [static]
Note:
The only member of the peer used here is the name field

Definition at line 2045 of file chan_sip.c.

References ast_str_case_hash(), and sip_peer::name.

Referenced by load_module().

{
   const struct sip_peer *peer = obj;

   return ast_str_case_hash(peer->name);
}
static int peer_ipcmp_cb ( void *  obj,
void *  arg,
int  flags 
) [static]

Match Peers by IP and Port number.

This function has two modes.

  • If the peer arg does not have INSECURE_PORT set, then we will only return a match for a peer that matches both the IP and port.
  • If the peer arg does have the INSECURE_PORT flag set, then we will only return a match for a peer that matches the IP and has insecure=port in its configuration.

This callback will be used twice when doing peer matching. There is a first pass for full IP+port matching, and a second pass in case there is a match that meets the insecure=port criteria.

Note:
Connections coming in over TCP or TLS should never be matched by port.
the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.

Definition at line 2093 of file chan_sip.c.

References sip_peer::addr, ast_test_flag, CMP_MATCH, CMP_STOP, sip_peer::flags, SIP_INSECURE_PORT, SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, and sip_peer::transports.

Referenced by load_module().

{
   struct sip_peer *peer = obj, *peer2 = arg;

   if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
      /* IP doesn't match */
      return 0;
   }

   /* We matched the IP, check to see if we need to match by port as well. */
   if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
      /* peer matching on port is not possible with TCP/TLS */
      return CMP_MATCH | CMP_STOP;
   } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
      /* We are allowing match without port for peers configured that
       * way in this pass through the peers. */
      return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
            (CMP_MATCH | CMP_STOP) : 0;
   }

   /* Now only return a match if the port matches, as well. */
   return peer->addr.sin_port == peer2->addr.sin_port ? (CMP_MATCH | CMP_STOP) : 0;
}
static int peer_iphash_cb ( const void *  obj,
const int  flags 
) [static]
Note:
the peer's ip address field is used to create key.

Definition at line 2065 of file chan_sip.c.

References sip_peer::addr.

Referenced by load_module().

{
   const struct sip_peer *peer = obj;
   int ret1 = peer->addr.sin_addr.s_addr;
   if (ret1 < 0)
      ret1 = -ret1;

   return ret1;
}
static int peer_is_marked ( void *  peerobj,
void *  arg,
int  flags 
) [static]

Definition at line 3242 of file chan_sip.c.

References AST_SCHED_DEL, CMP_MATCH, sip_peer::pokeexpire, and sip_peer::the_mark.

Referenced by unlink_marked_peers_from_tables().

{
   struct sip_peer *peer = peerobj;
   if (peer->the_mark && peer->pokeexpire != -1) {
      AST_SCHED_DEL(sched, peer->pokeexpire);
   }
   return peer->the_mark ? CMP_MATCH : 0;
}
static void peer_mailboxes_to_str ( struct ast_str **  mailbox_str,
struct sip_peer peer 
) [static]

list peer mailboxes to CLI

Definition at line 15897 of file chan_sip.c.

References AST_LIST_NEXT, AST_LIST_TRAVERSE, ast_str_append(), ast_strlen_zero(), sip_mailbox::context, sip_mailbox::mailbox, mailbox, sip_peer::mailboxes, and S_OR.

Referenced by _sip_show_peer(), function_sippeer(), show_channels_cb(), and sip_send_mwi_to_peer().

{
   struct sip_mailbox *mailbox;

   AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
      ast_str_append(mailbox_str, 0, "%s%s%s%s",
         mailbox->mailbox,
         ast_strlen_zero(mailbox->context) ? "" : "@",
         S_OR(mailbox->context, ""),
         AST_LIST_NEXT(mailbox, entry) ? "," : "");
   }
}
static int peer_markall_func ( void *  device,
void *  arg,
int  flags 
) [static]

Definition at line 24960 of file chan_sip.c.

References sip_peer::the_mark.

Referenced by reload_config().

{
   struct sip_peer *peer = device;
   peer->the_mark = 1;
   return 0;
}
static int peer_status ( struct sip_peer peer,
char *  status,
int  statuslen 
) [static]

Definition at line 14999 of file chan_sip.c.

References ast_copy_string(), sip_peer::lastms, and sip_peer::maxms.

Referenced by _sip_show_peer(), _sip_show_peers(), and function_sippeer().

{
   int res = 0;
   if (peer->maxms) {
      if (peer->lastms < 0) {
         ast_copy_string(status, "UNREACHABLE", statuslen);
      } else if (peer->lastms > peer->maxms) {
         snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
         res = 1;
      } else if (peer->lastms) {
         snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
         res = 1;
      } else {
         ast_copy_string(status, "UNKNOWN", statuslen);
      }
   } else { 
      ast_copy_string(status, "Unmonitored", statuslen);
      /* Checking if port is 0 */
      res = -1;
   }
   return res;
}
int peercomparefunc ( const void *  a,
const void *  b 
)

Definition at line 15240 of file chan_sip.c.

Referenced by _sip_show_peers().

{
   struct sip_peer **ap = (struct sip_peer **)a;
   struct sip_peer **bp = (struct sip_peer **)b;
   return strcmp((*ap)->name, (*bp)->name);
}
static int port_str2int ( const char *  pt,
unsigned int  standard 
) [static]

converts ascii port to int representation. If no pt buffer is provided or the pt has errors when being converted to an int value, the port provided as the standard is used.

Definition at line 3466 of file chan_sip.c.

References ast_strlen_zero().

Referenced by __set_address_from_contact(), build_peer(), check_via(), create_addr(), parse_register_contact(), proxy_allocate(), and sip_register().

{
   int port = standard;
   if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
      port = standard;
   }

   return port;
}
static void print_codec_to_cli ( int  fd,
struct ast_codec_pref pref 
) [static]

Print codec list from preference to CLI/manager.

Definition at line 15729 of file chan_sip.c.

References ast_cli(), ast_codec_pref_index(), ast_getformatname(), and ast_codec_pref::framing.

Referenced by _sip_show_peer(), sip_show_settings(), and sip_show_user().

{
   int x, codec;

   for(x = 0; x < 32 ; x++) {
      codec = ast_codec_pref_index(pref, x);
      if (!codec)
         break;
      ast_cli(fd, "%s", ast_getformatname(codec));
      ast_cli(fd, ":%d", pref->framing[x]);
      if (x < 31 && ast_codec_pref_index(pref, x + 1))
         ast_cli(fd, ",");
   }
   if (!x)
      ast_cli(fd, "none");
}
static void print_group ( int  fd,
ast_group_t  group,
int  crlf 
) [static]

Print call group and pickup group.

Definition at line 15471 of file chan_sip.c.

References ast_cli(), ast_print_group(), and buf.

Referenced by _sip_show_peer(), and sip_show_user().

{
   char buf[256];
   ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
}
static void proc_422_rsp ( struct sip_pvt p,
struct sip_request rsp 
) [static]

Handle 422 response to INVITE with session-timer requested.

Session-Timers: An INVITE originated by Asterisk that asks for session-timers support from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy server tells Asterisk that the session refresh interval offered by Asterisk is too low for them. The proc_422_rsp() function handles a 422 response. It extracts the Min-SE header that comes back in 422 and sends a new INVITE accordingly.

Definition at line 23386 of file chan_sip.c.

References ast_log(), ast_strlen_zero(), get_header(), LOG_WARNING, parse_minse(), SIP_INVITE, sip_st_dlg::st_interval, sip_pvt::stimer, and transmit_invite().

Referenced by handle_response_invite().

{
   int rtn;
   const char *p_hdrval;
   int minse;

   p_hdrval = get_header(rsp, "Min-SE");
   if (ast_strlen_zero(p_hdrval)) {
      ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
      return;
   }
   rtn = parse_minse(p_hdrval, &minse);
   if (rtn != 0) {
      ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
      return;
   }
   p->stimer->st_interval = minse;
   transmit_invite(p, SIP_INVITE, 1, 2); 
}
static int proc_session_timer ( const void *  vp) [static]

Session-Timers: Process session refresh timeout event.

Definition at line 23226 of file chan_sip.c.

References ast_channel::_state, ast_channel_trylock, ast_channel_unlock, ast_debug, ast_log(), AST_SOFTHANGUP_DEV, ast_softhangup_nolock(), AST_STATE_UP, sip_pvt::callid, dialog_unref(), FALSE, LOG_ERROR, LOG_WARNING, sip_pvt::outgoing_call, sip_pvt::owner, sip_st_dlg::quit_flag, SESSION_TIMER_REFRESHER_UAC, SESSION_TIMER_REFRESHER_UAS, sip_pvt_lock, sip_pvt_unlock, sip_st_dlg::st_active, sip_st_dlg::st_expirys, sip_st_dlg::st_ref, sip_st_dlg::st_schedid, sip_pvt::stimer, stop_session_timer(), transmit_reinvite_with_sdp(), and TRUE.

Referenced by start_session_timer().

{
   struct sip_pvt *p = (struct sip_pvt *) vp;
   int sendreinv = FALSE;
   int res = 0;

   if (!p->stimer) {
      ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
      goto return_unref;
   }

   ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);

   if (!p->owner) {
      goto return_unref;
   }

   if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
      goto return_unref;
   }

   switch (p->stimer->st_ref) {
   case SESSION_TIMER_REFRESHER_UAC:
      if (p->outgoing_call == TRUE) {
         sendreinv = TRUE;
      }
      break;
   case SESSION_TIMER_REFRESHER_UAS:
      if (p->outgoing_call != TRUE) {
         sendreinv = TRUE;
      }
      break;
   default:
      ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
      goto return_unref;
   }

   if (sendreinv == TRUE) {
      res = 1;
      transmit_reinvite_with_sdp(p, FALSE, TRUE);
   } else {
      p->stimer->st_expirys++;
      if (p->stimer->st_expirys >= 2) {
         if (p->stimer->quit_flag) {
            goto return_unref;
         }
         ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
         sip_pvt_lock(p);
         while (p->owner && ast_channel_trylock(p->owner)) {
            sip_pvt_unlock(p);
            usleep(1);
            if (p->stimer && p->stimer->quit_flag) {
               goto return_unref;
            }
            sip_pvt_lock(p);
         }

         ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
         ast_channel_unlock(p->owner);
         sip_pvt_unlock(p);
      }
   }

return_unref:
   if (!res) {
      /* An error occurred.  Stop session timer processing */
      if (p->stimer) {
         p->stimer->st_schedid = -1;
         stop_session_timer(p);
      }

      /* If we are not asking to be rescheduled, then we need to release our
       * reference to the dialog. */
      dialog_unref(p, "removing session timer ref");
   }

   return res;
}
static void process_request_queue ( struct sip_pvt p,
int *  recount,
int *  nounlock 
) [static]

Definition at line 22433 of file chan_sip.c.

References ast_free, AST_LIST_REMOVE_HEAD, ast_log(), sip_pvt::callid, handle_incoming(), LOG_DEBUG, option_debug, sip_pvt::recv, and sip_pvt::request_queue.

Referenced by handle_request_do(), and scheduler_process_request_queue().

{
   struct sip_request *req;

   while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
      if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
         /* Request failed */
         if (option_debug) {
            ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
         }
      }
      ast_free(req);
   }
}
static int process_sdp ( struct sip_pvt p,
struct sip_request req,
int  t38action 
) [static]

Process SIP SDP offer, select formats and activate RTP channels If offer is rejected, we will not change any properties of the call Return 0 on success, a negative value on errors. Must be called after find_sdp().

< RTP Audio host IP

< RTP video host IP

< RTP text host IP

< UDPTL host ip

< RTP Audio port number

< RTP Video port number

< RTP Text port number

< UDPTL Image port number

< media socket address

< video socket address

< image socket address

< text socket address

Definition at line 8491 of file chan_sip.c.

References ast_async_goto(), ast_channel_lock, ast_channel_unlock, ast_clear_flag, ast_codec_choose(), AST_CONTROL_HOLD, AST_CONTROL_UNHOLD, ast_copy_string(), ast_debug, ast_exists_extension(), AST_FORMAT_AUDIO_MASK, AST_FORMAT_T140RED, ast_getformatname_multiple(), ast_inet_ntoa(), ast_log(), ast_null_frame, ast_queue_control(), ast_queue_control_data(), ast_queue_frame(), ast_rtp_alloc_size(), AST_RTP_DTMF, ast_rtp_get_current_formats(), ast_rtp_get_peer(), ast_rtp_lookup_mime_multiple(), ast_rtp_new_init(), ast_rtp_pt_clear(), ast_rtp_pt_copy(), ast_rtp_set_m_type(), ast_rtp_set_peer(), ast_rtp_setdtmf(), ast_rtp_setdtmfcompensate(), ast_rtp_stop(), ast_set_flag, ast_set_read_format(), ast_set_write_format(), ast_skip_blanks(), ast_strlen_zero(), ast_test_flag, ast_threadstorage_get(), ast_udptl_get_far_max_datagram(), ast_udptl_set_error_correction_scheme(), ast_udptl_set_far_max_datagram(), ast_udptl_set_peer(), ast_udptl_stop(), ast_verbose(), buf, sip_pvt::callid, sip_pvt::capability, change_hold_state(), change_t38_state(), ast_channel::cid, ast_callerid::cid_num, ast_channel::context, sip_request::debug, ast_channel::exten, FALSE, sip_pvt::flags, get_sdp_iterate(), get_sdp_line(), ast_hostent::hp, hp, sip_pvt::jointcapability, sip_pvt::jointnoncodeccapability, sip_pvt::lastinvite, sip_pvt::lastrtprx, sip_pvt::lastrtptx, sip_request::len, LOG_DEBUG, LOG_ERROR, LOG_NOTICE, LOG_WARNING, ast_channel::macrocontext, sip_pvt::mohsuggest, ast_channel::name, ast_channel::nativeformats, sip_request::next, sip_pvt::noncodeccapability, sip_pvt::notext, sip_pvt::novideo, offered_media::offered, sip_pvt::offered_media, option_debug, sip_pvt::owner, pbx_builtin_setvar_helper(), sip_pvt::peercapability, sip_pvt::prefs, process_sdp_a_audio(), process_sdp_a_image(), process_sdp_a_sendonly(), process_sdp_a_text(), process_sdp_a_video(), process_sdp_c(), process_sdp_o(), ast_channel::readformat, sip_pvt::red, sip_pvt::rtp, rtp_red_init(), S_OR, SDP_AUDIO, SDP_IMAGE, sip_request::sdp_start, SDP_T38_ACCEPT, SDP_T38_INITIATE, SDP_TEXT, SDP_VIDEO, sip_pvt::session_modify, sip_debug_test_pvt(), SIP_DTMF, SIP_DTMF_AUTO, SIP_DTMF_INBAND, SIP_DTMF_RFC2833, SIP_NAT, SIP_PAGE2_CALL_ONHOLD, SIP_PAGE2_FAX_DETECT_T38, SIP_PAGE2_RFC2833_COMPENSATE, SIP_PAGE2_UDPTL_DESTINATION, SIPBUFSIZE, t38properties::state, sip_pvt::t38, T38_DISABLED, T38_ENABLED, T38_LOCAL_REINVITE, T38_PEER_REINVITE, offered_media::text, text, t38properties::their_parms, sip_pvt::trtp, TRUE, sip_pvt::udptl, UDPTL_ERROR_CORRECTION_NONE, VERBOSE_PREFIX_2, sip_pvt::vrtp, and ast_channel::writeformat.

Referenced by handle_incoming(), handle_request_invite(), handle_response(), and handle_response_invite().

{
   /* Iterators for SDP parsing */
   int start = req->sdp_start;
   int next = start;
   int iterator = start;

   /* Temporary vars for SDP parsing */
   char type = '\0';
   const char *value = NULL;
   const char *m = NULL;           /* SDP media offer */
   const char *nextm = NULL;
   int len = -1;

   /* Host information */
   struct ast_hostent sessionhp;
   struct ast_hostent audiohp;
   struct ast_hostent videohp;
   struct ast_hostent texthp;
   struct ast_hostent imagehp;
   struct hostent *hp = NULL; /*!< RTP Audio host IP */
   struct hostent *vhp = NULL;   /*!< RTP video host IP */
   struct hostent *thp = NULL;   /*!< RTP text host IP */
   struct hostent *ihp = NULL;     /*!< UDPTL host ip */
   int portno = -1;     /*!< RTP Audio port number */
   int vportno = -1;    /*!< RTP Video port number */
   int tportno = -1;    /*!< RTP Text port number */
   int udptlportno = -1;      /*!< UDPTL Image port number */
   struct sockaddr_in sin = { 0, }; /*!< media socket address */
   struct sockaddr_in vsin = { 0, };   /*!< video socket address */
   struct sockaddr_in isin = { 0, };   /*!< image socket address */
   struct sockaddr_in tsin = { 0, };   /*!< text socket address */

   /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
   int peercapability = 0, peernoncodeccapability = 0;
   int vpeercapability = 0, vpeernoncodeccapability = 0;
   int tpeercapability = 0, tpeernoncodeccapability = 0;

   struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
   int newjointcapability;          /* Negotiated capability */
   int newpeercapability;
   int newnoncodeccapability;

   const char *codecs;
   int codec;

   /* Others */
   int sendonly = -1;
   int vsendonly = -1;
   int numberofports;
   int numberofmediastreams = 0;
   int last_rtpmap_codec = 0;
   int red_data_pt[10];    /* For T.140 red */
   int red_num_gen = 0;    /* For T.140 red */
   char red_fmtp[100] = "empty"; /* For T.140 red */
   int debug = sip_debug_test_pvt(p);

   /* START UNKNOWN */
   char buf[SIPBUFSIZE];
   /* END UNKNOWN */

   /* Initial check */
   if (!p->rtp) {
      ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
      return -1;
   }

   /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
#ifdef LOW_MEMORY
   newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
#else
   newaudiortp = alloca(ast_rtp_alloc_size());
#endif
   memset(newaudiortp, 0, ast_rtp_alloc_size());
   ast_rtp_new_init(newaudiortp);
   ast_rtp_pt_clear(newaudiortp);

#ifdef LOW_MEMORY
   newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
#else
   newvideortp = alloca(ast_rtp_alloc_size());
#endif
   memset(newvideortp, 0, ast_rtp_alloc_size());
   ast_rtp_new_init(newvideortp);
   ast_rtp_pt_clear(newvideortp);

#ifdef LOW_MEMORY
   newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
#else
   newtextrtp = alloca(ast_rtp_alloc_size());
#endif
   memset(newtextrtp, 0, ast_rtp_alloc_size());
   ast_rtp_new_init(newtextrtp);
   ast_rtp_pt_clear(newtextrtp);

   /* Update our last rtprx when we receive an SDP, too */
   p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */

   memset(p->offered_media, 0, sizeof(p->offered_media));


   /* default: novideo and notext set */
   p->novideo = TRUE;
   p->notext = TRUE;

   if (p->vrtp)
      ast_rtp_pt_clear(newvideortp);  /* Must be cleared in case no m=video line exists */
 
   if (p->trtp)
      ast_rtp_pt_clear(newtextrtp);  /* Must be cleared in case no m=text line exists */
   
   /* Scan for the first media stream (m=) line to limit scanning of globals */
   nextm = get_sdp_iterate(&next, req, "m");
   if (ast_strlen_zero(nextm)) {
      ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
      return -1;
   }

   /* Scan session level SDP parameters (lines before first media stream) */
   while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
      int processed = FALSE;
      switch (type) {
      case 'o':
         /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
          * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
          */
         if (!process_sdp_o(value, p))
            return (p->session_modify == FALSE) ? 0 : -1;
         break;
      case 'c':
         if (process_sdp_c(value, &sessionhp)) {
            processed = TRUE;
            hp = &sessionhp.hp;
            vhp = hp;
            thp = hp;
            ihp = hp;
         }
         break;
      case 'a':
         if (process_sdp_a_sendonly(value, &sendonly)) {
            processed = TRUE;
            vsendonly = sendonly;
         }
         else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
            processed = TRUE;
         else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
            processed = TRUE;
         else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
            processed = TRUE;
         else if (process_sdp_a_image(value, p))
            processed = TRUE;
         break;
      }

      if (option_debug > 2)
         ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
   }



   /* Scan media stream (m=) specific parameters loop */
   while (!ast_strlen_zero(nextm)) {
      int audio = FALSE;
      int video = FALSE;
      int image = FALSE;
      int text = FALSE;
      int x;

      numberofports = 1;
      len = -1;
      start = next;
      m = nextm;
      iterator = next;
      nextm = get_sdp_iterate(&next, req, "m");

      /* Search for audio media definition */
      if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
          (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
         audio = TRUE;
         p->offered_media[SDP_AUDIO].offered = TRUE;
         numberofmediastreams++;
         portno = x;

         /* Scan through the RTP payload types specified in a "m=" line: */
         codecs = m + len;
         ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
         for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
            if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
               ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
               return -1;
            }
            if (debug)
               ast_verbose("Found RTP audio format %d\n", codec);

            ast_rtp_set_m_type(newaudiortp, codec);
         }
      /* Search for video media definition */
      } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
            (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
         video = TRUE;
         p->novideo = FALSE;
         p->offered_media[SDP_VIDEO].offered = TRUE;
         numberofmediastreams++;
         vportno = x;

         /* Scan through the RTP payload types specified in a "m=" line: */
         codecs = m + len;
         ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
         for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
            if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
               ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
               return -1;
            }
            if (debug)
               ast_verbose("Found RTP video format %d\n", codec);
            ast_rtp_set_m_type(newvideortp, codec);
         }
      /* Search for text media definition */
      } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
            (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
         text = TRUE;
         p->notext = FALSE;
         p->offered_media[SDP_TEXT].offered = TRUE;
         numberofmediastreams++;
         tportno = x;

         /* Scan through the RTP payload types specified in a "m=" line: */
         codecs = m + len;
         ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
         for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
            if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
               ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
               return -1;
            }
            if (debug)
               ast_verbose("Found RTP text format %d\n", codec);
            ast_rtp_set_m_type(newtextrtp, codec);
         }
      /* Search for image media definition */
      } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
               (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
         image = TRUE;
         if (debug)
            ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
         p->offered_media[SDP_IMAGE].offered = TRUE;
         udptlportno = x;
         numberofmediastreams++;

         if (p->t38.state != T38_ENABLED) {
            memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));

            /* default EC to none, the remote end should
             * respond with the EC they want to use */
            ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
         }
      } else {
         ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
         continue;
      }

      /* Check for number of ports */
      if (numberofports > 1)
         ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
      


      /* Media stream specific parameters */
      while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
         int processed = FALSE;

         switch (type) {
         case 'c':
            if (audio) {
               if (process_sdp_c(value, &audiohp)) {
                  processed = TRUE;
                  hp = &audiohp.hp;
               }
            } else if (video) {
               if (process_sdp_c(value, &videohp)) {
                  processed = TRUE;
                  vhp = &videohp.hp;
               }
            } else if (text) {
               if (process_sdp_c(value, &texthp)) {
                  processed = TRUE;
                  thp = &texthp.hp;
               }
            } else if (image) {
               if (process_sdp_c(value, &imagehp)) {
                  processed = TRUE;
                  ihp = &imagehp.hp;
               }
            }
            break;
         case 'a':
            /* Audio specific scanning */
            if (audio) {
               if (process_sdp_a_sendonly(value, &sendonly))
                  processed = TRUE;
               else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
                  processed = TRUE;
            }
            /* Video specific scanning */
            else if (video) {
               if (process_sdp_a_sendonly(value, &vsendonly))
                  processed = TRUE;
               else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
                  processed = TRUE;
            }
            /* Text (T.140) specific scanning */
            else if (text) {
               if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
                  processed = TRUE;
            }
            /* Image (T.38 FAX) specific scanning */
            else if (image) {
               if (process_sdp_a_image(value, p))
                  processed = TRUE;
            }
            break;
         }

         if (option_debug > 2)
            ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
                  (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
                  type, value,
                  (processed == TRUE)? "OK." : "UNSUPPORTED.");
      }
   }


   /* Sanity checks */
   if (!hp && !vhp && !thp && !ihp) {
      ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
      return -1;
   }

   if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1)
      /* No acceptable offer found in SDP  - we have no ports */
      /* Do not change RTP or VRTP if this is a re-invite */
      return -2;

   if (numberofmediastreams > 3)
      /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
      return -3;

   if (udptlportno == -1) {
      change_t38_state(p, T38_DISABLED);
   }


   /* Now gather all of the codecs that we are asked for: */
   ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
   ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
   ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);

   newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
   newpeercapability = (peercapability | vpeercapability | tpeercapability);
   newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;

   if (debug) {
      /* shame on whoever coded this.... */
      char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];

      ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
             ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
             ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
             ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
             ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
             ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));

      ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
             ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
             ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
             ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
   }
   if (!newjointcapability && (portno != -1)) {
      ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
      /* Do NOT Change current setting */
      return -1;
   }

   /* Setup audio address and port */
   if (p->rtp) {
      if (portno > 0) {
         sin.sin_family = AF_INET;
         sin.sin_port = htons(portno);
         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
         ast_rtp_set_peer(p->rtp, &sin);
         if (debug)
            ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
         /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since                                                                                                    
            they are acceptable */
         p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
         p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
         p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */

         ast_rtp_pt_copy(p->rtp, newaudiortp);

         if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
            ast_clear_flag(&p->flags[0], SIP_DTMF);
            if (newnoncodeccapability & AST_RTP_DTMF) {
               /* XXX Would it be reasonable to drop the DSP at this point? XXX */
               ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
               /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
               ast_rtp_setdtmf(p->rtp, 1);
               ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
            } else {
               ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
            }
         }
      } else if (udptlportno > 0) {
         if (debug)
            ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
      } else {
         ast_rtp_stop(p->rtp);
         if (debug)
            ast_verbose("Peer doesn't provide audio\n");
      }
   }

   /* Setup video address and port */
   if (p->vrtp) {
      if (vportno > 0) {
         vsin.sin_family = AF_INET;
         vsin.sin_port = htons(vportno);
         memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
         ast_rtp_set_peer(p->vrtp, &vsin);
         if (debug) 
            ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
         ast_rtp_pt_copy(p->vrtp, newvideortp);
      } else {
         ast_rtp_stop(p->vrtp);
         if (debug)
            ast_verbose("Peer doesn't provide video\n");
      }
   }

   /* Setup text address and port */
   if (p->trtp) {
      if (tportno > 0) {
         tsin.sin_family = AF_INET;
         tsin.sin_port = htons(tportno);
         memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
         ast_rtp_set_peer(p->trtp, &tsin);
         if (debug) 
            ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
         if ((p->jointcapability & AST_FORMAT_T140RED)) {
            p->red = 1;
            rtp_red_init(p->trtp, 300, red_data_pt, 2);
         } else {
            p->red = 0;
         }
         ast_rtp_pt_copy(p->trtp, newtextrtp);
      } else {
         ast_rtp_stop(p->trtp);
         if (debug)
            ast_verbose("Peer doesn't provide T.140\n");
      }
   }
   /* Setup image address and port */
   if (p->udptl) {
      if (udptlportno > 0) {
         isin.sin_family = AF_INET;
         isin.sin_port = htons(udptlportno);
         if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
            struct sockaddr_in remote_address = { 0, };
            ast_rtp_get_peer(p->rtp, &remote_address);
            if (remote_address.sin_addr.s_addr) {
               memcpy(&isin, &remote_address, sizeof(isin));
               if (debug) {
                  ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_inet_ntoa(isin.sin_addr));
               }
            }
         } else {
            memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));
         }
         ast_udptl_set_peer(p->udptl, &isin);
         if (debug)
            ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));

         /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
         if (!ast_udptl_get_far_max_datagram(p->udptl)) {
            /* setting to zero will force a default if none was provided by the SDP */
            ast_udptl_set_far_max_datagram(p->udptl, 0);
         }

         /* Remote party offers T38, we need to update state */
         if ((t38action == SDP_T38_ACCEPT) &&
             (p->t38.state == T38_LOCAL_REINVITE)) {
            change_t38_state(p, T38_ENABLED);
         } else if ((t38action == SDP_T38_INITIATE) &&
               p->owner && p->lastinvite) {
            change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
            /* If fax detection is enabled then send us off to the fax extension */
            if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
               ast_channel_lock(p->owner);
               if (strcmp(p->owner->exten, "fax")) {
                  const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
                  ast_channel_unlock(p->owner);
                  if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
                     ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
                     pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
                     if (ast_async_goto(p->owner, target_context, "fax", 1)) {
                        ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
                     }
                  } else {
                     ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
                  }
               } else {
                  ast_channel_unlock(p->owner);
               }
            }
         }
      } else {
         ast_udptl_stop(p->udptl);
         if (debug)
            ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
      }
   }

   if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
      ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
                return 0;
        }

   /* Ok, we're going with this offer */
   ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));

   if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
      return 0;

   ast_debug(4, "We have an owner, now see if we need to change this call\n");

   if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
      if (debug) {
         char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
         ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n", 
            ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
            ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
      }
      p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
      ast_set_read_format(p->owner, p->owner->readformat);
      ast_set_write_format(p->owner, p->owner->writeformat);
   }
   
   if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)
         && (sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
         isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
         && (!sendonly || sendonly == -1)) {
      ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
      /* Activate a re-invite */
      ast_queue_frame(p->owner, &ast_null_frame);
      change_hold_state(p, req, FALSE, sendonly);
   } else if (!(sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
         isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
         || (sendonly && sendonly != -1)) {
      ast_queue_control_data(p->owner, AST_CONTROL_HOLD, 
                   S_OR(p->mohsuggest, NULL),
                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
      if (sendonly)
         ast_rtp_stop(p->rtp);
      /* RTCP needs to go ahead, even if we're on hold!!! */
      /* Activate a re-invite */
      ast_queue_frame(p->owner, &ast_null_frame);
      change_hold_state(p, req, TRUE, sendonly);
   }
   
   return 0;
}
static int process_sdp_a_audio ( const char *  a,
struct sip_pvt p,
struct ast_rtp newaudiortp,
int *  last_rtpmap_codec 
) [static]

Definition at line 9180 of file chan_sip.c.

References ast_codec_pref_setsize(), ast_debug, AST_FORMAT_SIREN14, AST_FORMAT_SIREN7, ast_log(), ast_rtp_codec_getformat(), ast_rtp_codec_getpref(), ast_rtp_codec_setpref(), ast_rtp_lookup_pt(), AST_RTP_OPT_G726_NONSTANDARD, ast_rtp_set_rtpmap_type_rate(), ast_rtp_unset_m_type(), ast_test_flag, ast_verbose(), sip_pvt::autoframing, sip_request::debug, FALSE, sip_pvt::flags, format, LOG_DEBUG, LOG_WARNING, LONG_MAX, LONG_MIN, MAX_RTP_PT, option_debug, sip_pvt::rtp, SDP_MAX_RTPMAP_CODECS, sip_debug_test_pvt(), SIP_G726_NONSTANDARD, and TRUE.

Referenced by process_sdp().

{
   int found = FALSE;
   int codec;
   char mimeSubtype[128];
   char fmtp_string[64];
   unsigned int sample_rate;
   int debug = sip_debug_test_pvt(p);

   if (!strncasecmp(a, "ptime", 5)) {
      char *tmp = strrchr(a, ':');
      long int framing = 0;
      if (tmp) {
         tmp++;
         framing = strtol(tmp, NULL, 10);
         if (framing == LONG_MIN || framing == LONG_MAX) {
            framing = 0;
            ast_debug(1, "Can't read framing from SDP: %s\n", a);
         }
      }
      if (framing && p->autoframing) {
         struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
         int codec_n;
         int format = 0;
         for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
            format = ast_rtp_codec_getformat(codec_n);
            if (!format)   /* non-codec or not found */
               continue;
            if (option_debug)
               ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
            ast_codec_pref_setsize(pref, format, framing);
         }
         ast_rtp_codec_setpref(p->rtp, pref);
      }
      found = TRUE;
   } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
      /* We have a rtpmap to handle */
      if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
         if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
             ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
            if (debug)
               ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
            //found_rtpmap_codecs[last_rtpmap_codec] = codec;
            (*last_rtpmap_codec)++;
            found = TRUE;
         } else {
            ast_rtp_unset_m_type(newaudiortp, codec);
            if (debug)
               ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
         }
      } else {
         if (debug)
            ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
      }
   } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
      struct rtpPayloadType payload;

      payload = ast_rtp_lookup_pt(newaudiortp, codec);
      if (payload.code && payload.isAstFormat) {
         unsigned int bit_rate;

         switch (payload.code) {
         case AST_FORMAT_SIREN7:
            if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
               if (bit_rate != 32000) {
                  ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
                  ast_rtp_unset_m_type(newaudiortp, codec);
               } else {
                  found = TRUE;
               }
            }
            break;
         case AST_FORMAT_SIREN14:
            if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
               if (bit_rate != 48000) {
                  ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
                  ast_rtp_unset_m_type(newaudiortp, codec);
               } else {
                  found = TRUE;
               }
            }
            break;
         }
      }
   }

   return found;
}
static int process_sdp_a_image ( const char *  a,
struct sip_pvt p 
) [static]

Definition at line 9352 of file chan_sip.c.

References ast_debug, AST_T38_RATE_12000, AST_T38_RATE_14400, AST_T38_RATE_2400, AST_T38_RATE_4800, AST_T38_RATE_7200, AST_T38_RATE_9600, AST_T38_RATE_MANAGEMENT_LOCAL_TCF, AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF, ast_udptl_set_error_correction_scheme(), ast_udptl_set_far_max_datagram(), FALSE, ast_control_t38_parameters::fill_bit_removal, ast_control_t38_parameters::rate, ast_control_t38_parameters::rate_management, s, sip_pvt::t38, sip_pvt::t38_maxdatagram, t38properties::their_parms, ast_control_t38_parameters::transcoding_jbig, ast_control_t38_parameters::transcoding_mmr, TRUE, sip_pvt::udptl, UDPTL_ERROR_CORRECTION_FEC, UDPTL_ERROR_CORRECTION_NONE, UDPTL_ERROR_CORRECTION_REDUNDANCY, and ast_control_t38_parameters::version.

Referenced by process_sdp().

{
   int found = FALSE;
   char s[256];
   unsigned int x;

   if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
      ast_debug(3, "MaxBufferSize:%d\n", x);
      found = TRUE;
   } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
      ast_debug(3, "T38MaxBitRate: %d\n", x);
      switch (x) {
      case 14400:
         p->t38.their_parms.rate = AST_T38_RATE_14400;
         break;
      case 12000:
         p->t38.their_parms.rate = AST_T38_RATE_12000;
         break;
      case 9600:
         p->t38.their_parms.rate = AST_T38_RATE_9600;
         break;
      case 7200:
         p->t38.their_parms.rate = AST_T38_RATE_7200;
         break;
      case 4800:
         p->t38.their_parms.rate = AST_T38_RATE_4800;
         break;
      case 2400:
         p->t38.their_parms.rate = AST_T38_RATE_2400;
         break;
      }
      found = TRUE;
   } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
      ast_debug(3, "FaxVersion: %u\n", x);
      p->t38.their_parms.version = x;
      found = TRUE;
   } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
      /* override the supplied value if the configuration requests it */
      if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
         ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
         x = p->t38_maxdatagram;
      }
      ast_debug(3, "FaxMaxDatagram: %u\n", x);
      ast_udptl_set_far_max_datagram(p->udptl, x);
      found = TRUE;
   } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
      if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
         ast_debug(3, "FillBitRemoval: %d\n", x);
         if (x == 1) {
            p->t38.their_parms.fill_bit_removal = TRUE;
         }
      } else {
         ast_debug(3, "FillBitRemoval\n");
         p->t38.their_parms.fill_bit_removal = TRUE;
      }
      found = TRUE;
   } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
      if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
         ast_debug(3, "Transcoding MMR: %d\n", x);
         if (x == 1) {
            p->t38.their_parms.transcoding_mmr = TRUE;
         }
      } else {
         ast_debug(3, "Transcoding MMR\n");
         p->t38.their_parms.transcoding_mmr = TRUE;
      }
      found = TRUE;
   } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
      if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
         ast_debug(3, "Transcoding JBIG: %d\n", x);
         if (x == 1) {
            p->t38.their_parms.transcoding_jbig = TRUE;
         }
      } else {
         ast_debug(3, "Transcoding JBIG\n");
         p->t38.their_parms.transcoding_jbig = TRUE;
      }
      found = TRUE;
   } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
      ast_debug(3, "RateManagement: %s\n", s);
      if (!strcasecmp(s, "localTCF"))
         p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
      else if (!strcasecmp(s, "transferredTCF"))
         p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
      found = TRUE;
   } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
      ast_debug(3, "UDP EC: %s\n", s);
      if (!strcasecmp(s, "t38UDPRedundancy")) {
         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
      } else if (!strcasecmp(s, "t38UDPFEC")) {
         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
      } else {
         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
      }
      found = TRUE;
   }

   return found;
}
static int process_sdp_a_sendonly ( const char *  a,
int *  sendonly 
) [static]

Definition at line 9160 of file chan_sip.c.

References FALSE, and TRUE.

Referenced by process_sdp().

{
   int found = FALSE;

   if (!strcasecmp(a, "sendonly")) {
      if (*sendonly == -1)
         *sendonly = 1;
      found = TRUE;
   } else if (!strcasecmp(a, "inactive")) {
      if (*sendonly == -1)
         *sendonly = 2;
      found = TRUE;
   }  else if (!strcasecmp(a, "sendrecv")) {
      if (*sendonly == -1)
         *sendonly = 0;
      found = TRUE;
   }
   return found;
}
static int process_sdp_a_text ( const char *  a,
struct sip_pvt p,
struct ast_rtp newtextrtp,
char *  red_fmtp,
int *  red_num_gen,
int *  red_data_pt,
int *  last_rtpmap_codec 
) [static]

Definition at line 9303 of file chan_sip.c.

References ast_rtp_set_rtpmap_type(), ast_verbose(), sip_request::debug, FALSE, RED_MAX_GENERATION, SDP_MAX_RTPMAP_CODECS, sip_debug_test_pvt(), sip_pvt::trtp, and TRUE.

Referenced by process_sdp().

{
   int found = FALSE;
   int codec;
   char mimeSubtype[128];
   unsigned int sample_rate;
   char *red_cp;
   int debug = sip_debug_test_pvt(p);

   if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
      /* We have a rtpmap to handle */
      if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
         if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
            if (p->trtp) {
               /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
               ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
               found = TRUE;
            }
         } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
            if (p->trtp) {
               ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
               sprintf(red_fmtp, "fmtp:%d ", codec); 
               if (debug)
                  ast_verbose("RED submimetype has payload type: %d\n", codec);
               found = TRUE;
            }
         }
      } else {
         if (debug)
            ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
      }
   } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
      /* count numbers of generations in fmtp */
      red_cp = &red_fmtp[strlen(red_fmtp)];
      strncpy(red_fmtp, a, 100);

      sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
      red_cp = strtok(red_cp, "/");
      while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
         sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
         red_cp = strtok(NULL, "/");
      }
      red_cp = red_fmtp;
      found = TRUE;
   }

   return found;
}
static int process_sdp_a_video ( const char *  a,
struct sip_pvt p,
struct ast_rtp newvideortp,
int *  last_rtpmap_codec 
) [static]

Definition at line 9269 of file chan_sip.c.

References ast_rtp_set_rtpmap_type_rate(), ast_rtp_unset_m_type(), ast_verbose(), sip_request::debug, FALSE, SDP_MAX_RTPMAP_CODECS, sip_debug_test_pvt(), and TRUE.

Referenced by process_sdp().

{
   int found = FALSE;
   int codec;
   char mimeSubtype[128];
   unsigned int sample_rate;
   int debug = sip_debug_test_pvt(p);

   if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
      /* We have a rtpmap to handle */
      if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
         /* Note: should really look at the '#chans' params too */
         if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
            if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
               if (debug)
                  ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
               //found_rtpmap_codecs[last_rtpmap_codec] = codec;
               (*last_rtpmap_codec)++;
               found = TRUE;
            } else {
               ast_rtp_unset_m_type(newvideortp, codec);
               if (debug) 
                  ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
            }
         }
      } else {
         if (debug)
            ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
      }
   }

   return found;
}
static int process_sdp_c ( const char *  c,
struct ast_hostent hp 
) [static]

Definition at line 9141 of file chan_sip.c.

References ast_gethostbyname(), ast_log(), FALSE, hp, LOG_WARNING, and TRUE.

Referenced by process_sdp().

{
   char host[258];
   struct hostent *hp;

   /* Check for Media-description-level-address */
   if (sscanf(c, "IN IP4 %255s", host) != 1) {
      ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
      return FALSE;
   } else {
      if (!(hp = ast_gethostbyname(host, ast_hp))) {
         ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
         return FALSE;
      }
      return TRUE;
   }
   return FALSE;
}
static int process_sdp_o ( const char *  o,
struct sip_pvt p 
) [static]

Definition at line 9062 of file chan_sip.c.

References ast_debug, ast_log(), ast_strdupa, ast_strlen_zero(), ast_test_flag, sip_pvt::callid, FALSE, sip_pvt::flags, LOG_WARNING, sip_pvt::session_modify, sip_pvt::sessionversion_remote, SIP_PAGE2_IGNORESDPVERSION, t38properties::state, strsep(), sip_pvt::t38, T38_LOCAL_REINVITE, and TRUE.

Referenced by process_sdp().

{
   char *o_copy;
   char *token;
   int64_t rua_version;

   /* Store the SDP version number of remote UA. This will allow us to
   distinguish between session modifications and session refreshes. If
   the remote UA does not send an incremented SDP version number in a
   subsequent RE-INVITE then that means its not changing media session.
   The RE-INVITE may have been sent to update connected party, remote
   target or to refresh the session (Session-Timers).  Asterisk must not
   change media session and increment its own version number in answer
   SDP in this case. */

   p->session_modify = TRUE;

   if (ast_strlen_zero(o)) {
      ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
      return FALSE;
   }

   o_copy = ast_strdupa(o);
   token = strsep(&o_copy, " ");  /* Skip username   */
   if (!o_copy) {
      ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
      return FALSE;
   }
   token = strsep(&o_copy, " ");  /* Skip session-id */
   if (!o_copy) {
      ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
      return FALSE;
   }
   token = strsep(&o_copy, " ");  /* Version         */
   if (!o_copy) {
      ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
      return FALSE;
   }
   if (!sscanf(token, "%30" SCNd64, &rua_version)) {
      ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
      return FALSE;
   }

   /* we need to check the SDP version number the other end sent us;
    * our rules for deciding what to accept are a bit complex.
    *
    * 1) if 'ignoresdpversion' has been set for this dialog, then
    *    we will just accept whatever they sent and assume it is
    *    a modification of the session, even if it is not
    * 2) otherwise, if this is the first SDP we've seen from them
    *    we accept it
    * 3) otherwise, if the new SDP version number is higher than the
    *    old one, we accept it
    * 4) otherwise, if this SDP is in response to us requesting a switch
    *    to T.38, we accept the SDP, but also generate a warning message
    *    that this peer should have the 'ignoresdpversion' option set,
    *    because it is not following the SDP offer/answer RFC; if we did
    *    not request a switch to T.38, then we stop parsing the SDP, as it
    *    has not changed from the previous version
    */

   if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
       (p->sessionversion_remote < 0) ||
       (p->sessionversion_remote < rua_version)) {
      p->sessionversion_remote = rua_version;
   } else {
      if (p->t38.state == T38_LOCAL_REINVITE) {
         p->sessionversion_remote = rua_version;
         ast_log(LOG_WARNING, "Call %s responded to our T.38 reinvite without changing SDP version; 'ignoresdpversion' should be set for this peer.\n", p->callid);
      } else {
         p->session_modify = FALSE;
         ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
         return FALSE;
      }
   }

   return TRUE;
}
static int process_via ( struct sip_pvt p,
const struct sip_request req 
) [static]

Definition at line 7677 of file chan_sip.c.

References addr_is_multicast(), ast_gethostbyname(), ast_log(), free_via(), get_header(), hp, LOG_ERROR, LOG_WARNING, sip_via::maddr, parse_via(), sip_via::port, sip_pvt::sa, STANDARD_SIP_PORT, sip_via::ttl, and sip_via::via.

Referenced by respprep().

{
   struct sip_via *via = parse_via(get_header(req, "Via"));

   if (!via) {
      ast_log(LOG_ERROR, "error processing via header\n");
      return -1;
   }

   if (via->maddr) {
      struct hostent *hp;
      struct ast_hostent ahp;

      hp = ast_gethostbyname(via->maddr, &ahp);
      if (hp == NULL)  {
         ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
         ast_log(LOG_ERROR, "error processing via header\n");
         free_via(via);
         return -1;
      }

      p->sa.sin_family = AF_INET;
      memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));

      if (via->port) {
         p->sa.sin_port = via->port;
      } else {
         p->sa.sin_port = STANDARD_SIP_PORT;
      }

      if (addr_is_multicast(&p->sa.sin_addr)) {
         setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
      }
   }

   free_via(via);
   return 0;
}
static struct sip_proxy* proxy_allocate ( char *  name,
char *  port,
int  force 
) [static, read]

Allocate and initialize sip proxy.

Definition at line 3477 of file chan_sip.c.

References ao2_alloc, ast_copy_string(), ast_strlen_zero(), sip_proxy::force, sip_proxy::ip, sip_proxy::name, port_str2int(), proxy_update(), and STANDARD_SIP_PORT.

Referenced by build_peer().

{
   struct sip_proxy *proxy;

   if (ast_strlen_zero(name)) {
      return NULL;
   }

   proxy = ao2_alloc(sizeof(*proxy), NULL);
   if (!proxy)
      return NULL;
   proxy->force = force;
   ast_copy_string(proxy->name, name, sizeof(proxy->name));
   proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
   proxy->ip.sin_family = AF_INET;
   proxy_update(proxy);
   return proxy;
}
static int proxy_update ( struct sip_proxy proxy) [static]

Resolve DNS srv name or host name in a sip_proxy structure

Definition at line 3446 of file chan_sip.c.

References ast_get_ip_or_srv(), ast_log(), FALSE, inet_aton(), sip_proxy::ip, sip_proxy::last_dnsupdate, LOG_WARNING, sip_proxy::name, sip_cfg, sip_settings::srvlookup, and TRUE.

Referenced by proxy_allocate(), and reload_config().

{
   /* if it's actually an IP address and not a name,
           there's no need for a managed lookup */
   if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
      /* Ok, not an IP address, then let's check if it's a domain or host */
      /* XXX Todo - if we have proxy port, don't do SRV */
      if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
         ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
         return FALSE;
      }
   }
   proxy->last_dnsupdate = time(NULL);
   return TRUE;
}
static void pvt_set_needdestroy ( struct sip_pvt pvt,
const char *  reason 
) [inline, static]
static int queue_request ( struct sip_pvt p,
const struct sip_request req 
) [static]

Definition at line 22503 of file chan_sip.c.

References ast_calloc, AST_LIST_INSERT_TAIL, ast_sched_add(), copy_request(), dialog_ref(), dialog_unref(), sip_pvt::request_queue, sip_pvt::request_queue_sched_id, and scheduler_process_request_queue().

Referenced by handle_request_do().

{
   struct sip_request *newreq;

   if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
      return -1;
   }

   copy_request(newreq, req);
   AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
   if (p->request_queue_sched_id == -1) {
      if ((p->request_queue_sched_id = ast_sched_add(sched, 10, scheduler_process_request_queue, dialog_ref(p, "Increment refcount to pass dialog pointer to sched callback"))) == -1) {
         dialog_unref(p, "Decrement refcount due to sched_add failure");
      }
   }

   return 0;
}
static struct sip_peer * realtime_peer ( const char *  peername,
struct sockaddr_in *  sin,
int  devstate_only 
) [static, read]

realtime_peer: Get peer from realtime storage Checks the "sippeers" realtime family from extconfig.conf Checks the "sipregs" realtime family from extconfig.conf if it's configured. This returns a pointer to a peer and because we use build_peer, we can rest assured that the refcount is bumped.

Note:
If this one loaded something, then we need to ensure that the host field matched. The only reason why we can't have this as a criteria is because we only have the IP address and the host field might be set as a name (and the reverse PTR might not match).

Definition at line 4944 of file chan_sip.c.

References sip_peer::addr, ao2_t_link, ast_check_realtime(), ast_config_destroy(), ast_copy_flags, ast_copy_string(), ast_debug, ast_gethostbyname(), ast_inet_ntoa(), ast_load_realtime(), ast_load_realtime_multientry(), ast_log(), AST_SCHED_REPLACE_UNREF, ast_test_flag, ast_variables_destroy(), build_peer(), sip_peer::expire, expire_register(), sip_peer::flags, get_insecure_variable_from_config(), get_name_from_variable(), hp, ipaddr, sip_peer::is_realtime, LOG_WARNING, sip_peer::name, ast_variable::name, ast_variable::next, ref_peer(), sip_settings::rtautoclear, SENTINEL, sip_cfg, SIP_PAGE2_RTAUTOCLEAR, SIP_PAGE2_RTCACHEFRIENDS, TRUE, unref_peer(), ast_variable::value, and var.

Referenced by find_peer().

{
   struct sip_peer *peer;
   struct ast_variable *var = NULL;
   struct ast_variable *varregs = NULL;
   struct ast_variable *tmp;
   struct ast_config *peerlist = NULL;
   char ipaddr[INET_ADDRSTRLEN];
   char portstring[6]; /*up to 5 digits plus null terminator*/
   char *cat = NULL;
   unsigned short portnum;
   int realtimeregs = ast_check_realtime("sipregs");

   /* First check on peer name */
   if (newpeername) {
      if (realtimeregs)
         varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);

      var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
      if (!var && sin)
         var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
      if (!var) {
         var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
         /*!\note
          * If this one loaded something, then we need to ensure that the host
          * field matched.  The only reason why we can't have this as a criteria
          * is because we only have the IP address and the host field might be
          * set as a name (and the reverse PTR might not match).
          */
         if (var && sin) {
            for (tmp = var; tmp; tmp = tmp->next) {
               if (!strcasecmp(tmp->name, "host")) {
                  struct hostent *hp;
                  struct ast_hostent ahp;
                  if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
                     /* No match */
                     ast_variables_destroy(var);
                     var = NULL;
                  }
                  break;
               }
            }
         }
      }
   }

   if (!var && sin) {   /* Then check on IP address for dynamic peers */
      ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
      portnum = ntohs(sin->sin_port);
      sprintf(portstring, "%u", portnum);
      var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);  /* First check for fixed IP hosts */
      if (var) {
         if (realtimeregs) {
            newpeername = get_name_from_variable(var, newpeername);
            varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
         }
      } else {
         if (realtimeregs)
            varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
         else
            var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
         if (varregs) {
            newpeername = get_name_from_variable(varregs, newpeername);
            var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
         }
      }
      if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
         peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
         if (peerlist) {
            var = get_insecure_variable_from_config(peerlist);
            if(var) {
               if (realtimeregs) {
                  newpeername = get_name_from_variable(var, newpeername);
                  varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
               }
            } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
               peerlist = NULL;
               cat = NULL;
               peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
               if(peerlist) {
                  var = get_insecure_variable_from_config(peerlist);
                  if(var) {
                     if (realtimeregs) {
                        newpeername = get_name_from_variable(var, newpeername);
                        varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
                     }
                  }
               }
            }
         } else {
            if (realtimeregs) {
               peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
               if (peerlist) {
                  varregs = get_insecure_variable_from_config(peerlist);
                  if (varregs) {
                     newpeername = get_name_from_variable(varregs, newpeername);
                     var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
                  }
               }
            } else {
               peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
               if (peerlist) {
                  var = get_insecure_variable_from_config(peerlist);
                  if (var) {
                     newpeername = get_name_from_variable(var, newpeername);
                     varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
                  }
               }
            }
         }
      }
   }

   if (!var) {
      if (peerlist)
         ast_config_destroy(peerlist);
      return NULL;
   }

   for (tmp = var; tmp; tmp = tmp->next) {
      if (!newpeername && !strcasecmp(tmp->name, "name")) {
         newpeername = tmp->value;
      }
   }
   
   if (!newpeername) {  /* Did not find peer in realtime */
      ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
      if(peerlist)
         ast_config_destroy(peerlist);
      else
         ast_variables_destroy(var);
      return NULL;
   }


   /* Peer found in realtime, now build it in memory */
   peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
   if (!peer) {
      if(peerlist)
         ast_config_destroy(peerlist);
      else {
         ast_variables_destroy(var);
         ast_variables_destroy(varregs);
      }
      return NULL;
   }

   ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);

   if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
      /* Cache peer */
      ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
      if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
         AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
               unref_peer(_data, "remove registration ref"),
               unref_peer(peer, "remove registration ref"),
               ref_peer(peer, "add registration ref"));
      }
      ao2_t_link(peers, peer, "link peer into peers table");
      if (peer->addr.sin_addr.s_addr) {
         ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
      }
   }
   peer->is_realtime = 1;
   if (peerlist)
      ast_config_destroy(peerlist);
   else {
      ast_variables_destroy(var);
      ast_variables_destroy(varregs);
   }

   return peer;
}
static void realtime_update_peer ( const char *  peername,
struct sockaddr_in *  sin,
const char *  username,
const char *  fullcontact,
const char *  useragent,
int  expirey,
int  deprecated_username,
int  lastms 
) [static]

Update peer object in realtime storage If the Asterisk system name is set in asterisk.conf, we will use that name and store that in the "regserver" field in the sippeers table to facilitate multi-server setups.

Definition at line 4740 of file chan_sip.c.

References ast_check_realtime(), ast_config_AST_SYSTEM_NAME, ast_copy_string(), ast_inet_ntoa(), ast_strlen_zero(), ast_update_realtime(), ipaddr, sip_settings::rtsave_sysname, SENTINEL, and sip_cfg.

Referenced by update_peer().

{
   char port[10];
   char ipaddr[INET_ADDRSTRLEN];
   char regseconds[20];
   char *tablename = NULL;
   char str_lastms[20];

   const char *sysname = ast_config_AST_SYSTEM_NAME;
   char *syslabel = NULL;

   time_t nowtime = time(NULL) + expirey;
   const char *fc = fullcontact ? "fullcontact" : NULL;

   int realtimeregs = ast_check_realtime("sipregs");

   tablename = realtimeregs ? "sipregs" : "sippeers";
   

   snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
   snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
   ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
   snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
   
   if (ast_strlen_zero(sysname)) /* No system name, disable this */
      sysname = NULL;
   else if (sip_cfg.rtsave_sysname)
      syslabel = "regserver";

   /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
         *  must also add it to contrib/scripts/asterisk.ldap-schema,
         *  contrib/scripts/asterisk.ldif,
         *  and to configs/res_ldap.conf.sample as described in
         *  bugs 15156 and 15895 
         */
   if (fc) {
      ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
         "port", port, "regseconds", regseconds,
         deprecated_username ? "username" : "defaultuser", defaultuser,
         "useragent", useragent, "lastms", str_lastms,
         fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
   } else {
      ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
         "port", port, "regseconds", regseconds,
         "useragent", useragent, "lastms", str_lastms,
         deprecated_username ? "username" : "defaultuser", defaultuser,
         syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
   }
}
static void receive_message ( struct sip_pvt p,
struct sip_request req 
) [static]

Receive SIP MESSAGE method messages.

Note:
We only handle messages within current calls currently Reference: RFC 3428

Definition at line 14819 of file chan_sip.c.

References AST_FRAME_TEXT, ast_log(), ast_queue_frame(), ast_verbose(), buf, sip_pvt::callid, ast_frame::data, ast_frame::datalen, DEFAULT_TRANS_TIMEOUT, FALSE, ast_frame::frametype, get_header(), get_msg_text(), LOG_WARNING, ast_frame::offset, sip_pvt::owner, ast_frame::ptr, sip_debug_test_pvt(), sip_scheddestroy(), ast_frame::subclass, and transmit_response().

Referenced by handle_request_message().

{
   char buf[1400];   
   struct ast_frame f;
   const char *content_type = get_header(req, "Content-Type");

   if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
      transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
      if (!p->owner)
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      return;
   }

   if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
      ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
      transmit_response(p, "202 Accepted", req);
      if (!p->owner)
         sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      return;
   }

   if (p->owner) {
      if (sip_debug_test_pvt(p))
         ast_verbose("SIP Text message received: '%s'\n", buf);
      memset(&f, 0, sizeof(f));
      f.frametype = AST_FRAME_TEXT;
      f.subclass = 0;
      f.offset = 0;
      f.data.ptr = buf;
      f.datalen = strlen(buf) + 1;
      ast_queue_frame(p->owner, &f);
      transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
      return;
   }

   /* Message outside of a call, we do not support that */
   ast_log(LOG_WARNING, "Received message to %s from %s, dropped it...\n  Content-Type:%s\n  Message: %s\n", get_header(req, "To"), get_header(req, "From"), content_type, buf);
   transmit_response(p, "405 Method Not Allowed", req);
   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
   return;
}
static struct sip_peer* ref_peer ( struct sip_peer peer,
char *  tag 
) [static, read]
static void ref_proxy ( struct sip_pvt pvt,
struct sip_proxy proxy 
) [static]

maintain proper refcounts for a sip_pvt's outboundproxy

This function sets pvt's outboundproxy pointer to the one referenced by the proxy parameter. Because proxy may be a refcounted object, and because pvt's old outboundproxy may also be a refcounted object, we need to maintain the proper refcounts.

Parameters:
pvtThe sip_pvt for which we wish to set the outboundproxy
proxyThe sip_proxy which we will point pvt towards.
Returns:
Returns void

Definition at line 3298 of file chan_sip.c.

References ao2_ref, sip_settings::outboundproxy, sip_pvt::outboundproxy, and sip_cfg.

Referenced by __sip_ack(), __sip_subscribe_mwi_do(), create_addr(), and create_addr_from_peer().

{
   struct sip_proxy *old_obproxy = pvt->outboundproxy;
   /* The sip_cfg.outboundproxy is statically allocated, and so
    * we don't ever need to adjust refcounts for it
    */
   if (proxy && proxy != &sip_cfg.outboundproxy) {
      ao2_ref(proxy, +1);
   }
   pvt->outboundproxy = proxy;
   if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
      ao2_ref(old_obproxy, -1);
   }
}
static const char * referstatus2str ( enum referstatus  rstatus) [static]

Convert transfer status to string.

Definition at line 3411 of file chan_sip.c.

References map_x_s().

Referenced by show_channels_cb().

{
   return map_x_s(referstatusstrings, rstatus, "");
}
static void reg_source_db ( struct sip_peer peer) [static]

Get registration details from Asterisk DB.

Definition at line 12581 of file chan_sip.c.

References sip_peer::addr, ast_db_get(), ast_debug, ast_inet_ntoa(), ast_random(), AST_SCHED_REPLACE_UNREF, ast_string_field_set, sip_request::data, sip_peer::expire, expire_register(), inet_aton(), sip_peer::name, sip_peer::pokeexpire, ref_peer(), register_peer_exten(), sip_peer::rt_fromcontact, sip_poke_peer(), sip_poke_peer_s(), strsep(), TRUE, unref_peer(), and sip_peer::username.

Referenced by build_peer(), and temp_peer().

{
   char data[256];
   struct in_addr in;
   int expire;
   int port;
   char *scan, *addr, *port_str, *expiry_str, *username, *contact;

   if (peer->rt_fromcontact) 
      return;
   if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
      return;

   scan = data;
   addr = strsep(&scan, ":");
   port_str = strsep(&scan, ":");
   expiry_str = strsep(&scan, ":");
   username = strsep(&scan, ":");
   contact = scan;   /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */

   if (!inet_aton(addr, &in))
      return;

   if (port_str)
      port = atoi(port_str);
   else
      return;

   if (expiry_str)
      expire = atoi(expiry_str);
   else
      return;

   if (username)
      ast_string_field_set(peer, username, username);
   if (contact)
      ast_string_field_set(peer, fullcontact, contact);

   ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
       peer->name, peer->username, ast_inet_ntoa(in), port, expire);

   memset(&peer->addr, 0, sizeof(peer->addr));
   peer->addr.sin_family = AF_INET;
   peer->addr.sin_addr = in;
   peer->addr.sin_port = htons(port);
   if (sipsock < 0) {
      /* SIP isn't up yet, so schedule a poke only, pretty soon */
      AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
            unref_peer(_data, "removing poke peer ref"),
            unref_peer(peer, "removing poke peer ref"),
            ref_peer(peer, "adding poke peer ref"));
   } else {
      sip_poke_peer(peer, 0);
   }
   AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
         unref_peer(_data, "remove registration ref"),
         unref_peer(peer, "remove registration ref"),
         ref_peer(peer, "add registration ref"));
   register_peer_exten(peer, TRUE);
}
static void register_peer_exten ( struct sip_peer peer,
int  onoff 
) [static]

Automatically add peer extension to dial plan.

Definition at line 4791 of file chan_sip.c.

References ast_add_extension(), ast_context_find(), ast_context_remove_extension(), ast_copy_string(), ast_exists_extension(), ast_free_ptr, ast_log(), ast_strdup, ast_strlen_zero(), context, E_MATCH, ext, global_regcontext, LOG_WARNING, sip_peer::name, pbx_find_extension(), sip_peer::regexten, S_OR, pbx_find_info::stacklen, and strsep().

Referenced by expire_register(), handle_response_peerpoke(), parse_register_contact(), reg_source_db(), sip_destroy_peer(), and sip_poke_noanswer().

{
   char multi[256];
   char *stringp, *ext, *context;
   struct pbx_find_info q = { .stacklen = 0 };

   /* XXX note that global_regcontext is both a global 'enable' flag and
    * the name of the global regexten context, if not specified
    * individually.
    */
   if (ast_strlen_zero(global_regcontext))
      return;

   ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
   stringp = multi;
   while ((ext = strsep(&stringp, "&"))) {
      if ((context = strchr(ext, '@'))) {
         *context++ = '\0';   /* split ext@context */
         if (!ast_context_find(context)) {
            ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
            continue;
         }
      } else {
         context = global_regcontext;
      }
      if (onoff) {
         if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
            ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
                ast_strdup(peer->name), ast_free_ptr, "SIP");
         }
      } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
         ast_context_remove_extension(context, ext, 1, NULL);
      }
   }
}
static enum check_auth_result register_verify ( struct sip_pvt p,
struct sockaddr_in *  sin,
struct sip_request req,
char *  uri 
) [static]

Verify registration of user

  • Registration is done in several steps, first a REGISTER without auth to get a challenge (nonce) then a second one with auth
  • Registration requests are only matched with peers that are marked as "dynamic".

Todo:
XXX here too we interpret a missing as a name-only URI, whereas the RFC says this is a domain-only uri.
Todo:
OEJ Remove this - there's never RTP in a REGISTER dialog...

Definition at line 13472 of file chan_sip.c.

References sip_peer::addr, sip_settings::alwaysauthreject, ao2_t_link, ast_apply_ha(), ast_copy_flags, ast_copy_string(), AST_DEVICE_UNKNOWN, ast_devstate_changed(), ast_inet_ntoa(), AST_LIST_EMPTY, ast_log(), ast_rtp_codec_setpref(), ast_set_flag, ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_uri_decode(), AUTH_ACL_FAILED, AUTH_BAD_TRANSPORT, AUTH_NOT_FOUND, AUTH_PEER_NOT_DYNAMIC, AUTH_SECRET_FAILED, AUTH_UNKNOWN_DOMAIN, AUTH_USERNAME_MISMATCH, sip_settings::autocreatepeer, sip_peer::autoframing, sip_pvt::autoframing, build_contact(), check_auth(), check_request_transport, check_sip_domain(), EVENT_FLAG_SYSTEM, sip_pvt::expiry, exten, FALSE, find_peer(), FINDPEERS, sip_peer::flags, sip_pvt::flags, sip_peer::fullcontact, get_header(), get_in_brackets(), sip_peer::ha, sip_peer::host_dynamic, sip_request::ignore, sip_pvt::initreq, sip_peer::lastmsgssent, LOG_ERROR, LOG_NOTICE, LOG_WARNING, manager_event, sip_peer::md5secret, sip_peer::name, name, parse_register_contact(), PARSE_REGISTER_DENIED, PARSE_REGISTER_FAILED, PARSE_REGISTER_QUERY, PARSE_REGISTER_UPDATE, sip_settings::pedanticsipchecking, sip_peer::prefs, remove_uri_parameters(), sip_pvt::rtp, sip_peer::secret, sip_cancel_destroy(), sip_cfg, SIP_NAT, SIP_PAGE2_REGISTERTRYING, SIP_PAGE2_SUBSCRIBEMWIONLY, SIP_PENDINGBYE, SIP_REGISTER, strcasestr(), temp_peer(), terminate_uri(), transmit_fake_auth_response(), transmit_response(), transmit_response_with_date(), TRUE, unref_peer(), update_peer(), and XMIT_UNRELIABLE.

Referenced by handle_request_register().

{
   enum check_auth_result res = AUTH_NOT_FOUND;
   struct sip_peer *peer;
   char tmp[256];
   char *name, *c;
   char *domain;

   terminate_uri(uri);  /* warning, overwrite the string */

   ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
   if (sip_cfg.pedanticsipchecking)
      ast_uri_decode(tmp);

   c = get_in_brackets(tmp);
   c = remove_uri_parameters(c);

   if (!strncasecmp(c, "sip:", 4)) {
      name = c + 4;
   } else if (!strncasecmp(c, "sips:", 5)) {
      name = c + 5;
   } else {
      name = c;
      ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
   }

   /*! \todo XXX here too we interpret a missing @domain as a name-only
    * URI, whereas the RFC says this is a domain-only uri.
    */
   /* Strip off the domain name */
   if ((c = strchr(name, '@'))) {
      *c++ = '\0';
      domain = c;
      if ((c = strchr(domain, ':')))   /* Remove :port */
         *c = '\0';
      if (!AST_LIST_EMPTY(&domain_list)) {
         if (!check_sip_domain(domain, NULL, 0)) {
            transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
            return AUTH_UNKNOWN_DOMAIN;
         }
      }
   }
   c = strchr(name, ';');  /* Remove any Username parameters */
   if (c)
      *c = '\0';

   ast_string_field_set(p, exten, name);
   build_contact(p);
   if (req->ignore) {
      /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
      const char *expires = get_header(req, "Expires");
      int expire = atoi(expires);

      if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
         if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
            expire = atoi(expires + 9);
         }
      }
      if (!ast_strlen_zero(expires) && expire == 0) {
         transmit_response_with_date(p, "200 OK", req);
         return 0;
      }
   }
   peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
   if (!(peer && ast_apply_ha(peer->ha, sin))) {
      /* Peer fails ACL check */
      if (peer) {
         unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
         peer = NULL;
         res = AUTH_ACL_FAILED;
      } else
         res = AUTH_NOT_FOUND;
   }

   if (peer) {
      /*! \todo OEJ Remove this - there's never RTP in a REGISTER dialog... */
      /* Set Frame packetization */
      if (p->rtp) {
         ast_rtp_codec_setpref(p->rtp, &peer->prefs);
         p->autoframing = peer->autoframing;
      }
      if (!peer->host_dynamic) {
         ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
         res = AUTH_PEER_NOT_DYNAMIC;
      } else {
         ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
         if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
            transmit_response(p, "100 Trying", req);
         if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
            if (sip_cancel_destroy(p))
               ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");

            if (check_request_transport(peer, req)) {
               ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
               transmit_response_with_date(p, "403 Forbidden", req);
               res = AUTH_BAD_TRANSPORT;
            } else {

               /* We have a successful registration attempt with proper authentication,
                  now, update the peer */
               switch (parse_register_contact(p, peer, req)) {
               case PARSE_REGISTER_DENIED:
                  ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
                  transmit_response_with_date(p, "603 Denied", req);
                  peer->lastmsgssent = -1;
                  res = 0;
                  break;
               case PARSE_REGISTER_FAILED:
                  ast_log(LOG_WARNING, "Failed to parse contact info\n");
                  transmit_response_with_date(p, "400 Bad Request", req);
                  peer->lastmsgssent = -1;
                  res = 0;
                  break;
               case PARSE_REGISTER_QUERY:
                  ast_string_field_set(p, fullcontact, peer->fullcontact);
                  transmit_response_with_date(p, "200 OK", req);
                  peer->lastmsgssent = -1;
                  res = 0;
                  break;
               case PARSE_REGISTER_UPDATE:
                  ast_string_field_set(p, fullcontact, peer->fullcontact);
                  update_peer(peer, p->expiry);
                  /* Say OK and ask subsystem to retransmit msg counter */
                  transmit_response_with_date(p, "200 OK", req);
                  if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
                     peer->lastmsgssent = -1;
                  res = 0;
                  break;
               }
            }

         } 
      }
   }
   if (!peer && sip_cfg.autocreatepeer) {
      /* Create peer if we have autocreate mode enabled */
      peer = temp_peer(name);
      if (peer) {
         ao2_t_link(peers, peer, "link peer into peer table");
         if (peer->addr.sin_addr.s_addr) {
            ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
         }
         
         if (sip_cancel_destroy(p))
            ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
         switch (parse_register_contact(p, peer, req)) {
         case PARSE_REGISTER_DENIED:
            ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
            transmit_response_with_date(p, "403 Forbidden (ACL)", req);
            peer->lastmsgssent = -1;
            res = 0;
            break;
         case PARSE_REGISTER_FAILED:
            ast_log(LOG_WARNING, "Failed to parse contact info\n");
            transmit_response_with_date(p, "400 Bad Request", req);
            peer->lastmsgssent = -1;
            res = 0;
            break;
         case PARSE_REGISTER_QUERY:
            ast_string_field_set(p, fullcontact, peer->fullcontact);
            transmit_response_with_date(p, "200 OK", req);
            peer->lastmsgssent = -1;
            res = 0;
            break;
         case PARSE_REGISTER_UPDATE:
            ast_string_field_set(p, fullcontact, peer->fullcontact);
            /* Say OK and ask subsystem to retransmit msg counter */
            transmit_response_with_date(p, "200 OK", req);
            manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", peer->name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
            peer->lastmsgssent = -1;
            res = 0;
            break;
         }
      }
   }
   if (!peer && sip_cfg.alwaysauthreject) {
      /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
       * trying to avoid leaking information, we MUST also transmit the same
       * response when we DON'T find a peer. */
      transmit_response(p, "100 Trying", req);
      /* Insert a fake delay between the 100 and the subsequent failure. */
      sched_yield();
   }
   if (!res) {
      ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
   }
   if (res < 0) {
      switch (res) {
      case AUTH_SECRET_FAILED:
         /* Wrong password in authentication. Go away, don't try again until you fixed it */
         transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
         if (global_authfailureevents)
            manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: AUTH_SECRET_FAILED\r\nAddress: %s\r\nPort: %d\r\n", 
               name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
         break;
      case AUTH_USERNAME_MISMATCH:
         /* Username and digest username does not match.
            Asterisk uses the From: username for authentication. We need the
            devices to use the same authentication user name until we support
            proper authentication by digest auth name */
      case AUTH_NOT_FOUND:
      case AUTH_PEER_NOT_DYNAMIC:
      case AUTH_ACL_FAILED:
         if (sip_cfg.alwaysauthreject) {
            transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
            if (global_authfailureevents) {
               manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: %s\r\nAddress: %s\r\nPort: %d\r\n",
                  name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
                  ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
            }
         } else {
            /* URI not found */
            if (res == AUTH_PEER_NOT_DYNAMIC) {
               transmit_response(p, "403 Forbidden", &p->initreq);
               if (global_authfailureevents) {
                  manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
                     "ChannelType: SIP\r\n"
                     "Peer: SIP/%s\r\n"
                     "PeerStatus: Rejected\r\n"
                     "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
                     "Address: %s\r\n"
                     "Port: %d\r\n",
                     name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
               }
            } else {
               transmit_response(p, "404 Not found", &p->initreq);
               if (global_authfailureevents) {
                  manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
                     "ChannelType: SIP\r\n"
                     "Peer: SIP/%s\r\n"
                     "PeerStatus: Rejected\r\n"
                     "Cause: %s\r\n"
                     "Address: %s\r\n"
                     "Port: %d\r\n",
                     name,
                     (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
                     ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
               }
            }
         }
         break;
      case AUTH_BAD_TRANSPORT:
      default:
         break;
      }
   }
   if (peer)
      unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");

   return res;
}
static struct sip_registry* registry_addref ( struct sip_registry reg,
char *  tag 
) [static, read]

Add object reference to SIP registry.

Definition at line 3393 of file chan_sip.c.

References ast_debug, ASTOBJ_REF, sip_registry::hostname, and sip_registry::refcount.

Referenced by handle_response_register(), sip_send_all_registers(), and transmit_register().

{
   ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
   return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
}
static void * registry_unref ( struct sip_registry reg,
char *  tag 
) [static]
static const char * regstate2str ( enum sipregistrystate  regstate) [static]

Convert registration state status to string.

Definition at line 11947 of file chan_sip.c.

References map_x_s().

Referenced by handle_response_register(), manager_show_registry(), sip_reg_timeout(), and sip_show_registry().

{
   return map_x_s(regstatestrings, regstate, "Unknown");
}
static int reload ( void  ) [static]

Part of Asterisk module interface.

Definition at line 26422 of file chan_sip.c.

References sip_reload().

{
   if (sip_reload(0, 0, NULL))
      return 0;
   return 1;
}
static int reload_config ( enum channelreloadreason  reason) [static]

Re-read SIP.conf config file.

Note:
This function reloads all config data, except for active peers (with registrations). They will only change configuration data at restart, not at reload. SIP debug and recordhistory state will not change

< Type of address: IPv4

< Don't force proxy usage, use route: headers

< Reset default transport to zero here, default value later on

< Reset default primary transport to zero here, default value later on

< Keep track of hold status for a peer

< Match auth username if available instead of From: Default off.

< Default DTMF setting: RFC2833

< NAT support if requested by device with rport

< Allow re-invites

< Set up call forward on 482 Loop Detected

Definition at line 24973 of file chan_sip.c.

References ast_tcptls_session_args::accept_fd, add_realm_authentication(), add_sip_domain(), sip_peer::addr, sip_settings::allow_external_domains, sip_settings::allowguest, sip_settings::allowsubscribe, sip_settings::allowtransfer, sip_settings::alwaysauthreject, ao2_t_callback, ao2_t_link, ast_append_ha(), ast_category_browse(), AST_CERTFILE, ast_clear_flag, ast_config_AST_SYSTEM_NAME, ast_config_destroy(), ast_config_load, ast_context_find_or_create(), ast_copy_string(), ast_debug, ast_enable_packet_fragmentation(), ast_false(), ast_find_ourip(), AST_FLAGS_ALL, ast_free, ast_free_ha(), ast_get_version(), ast_inet_ntoa(), ast_jb_read_conf(), AST_LIST_EMPTY, ast_log(), AST_MAX_CONTEXT, ast_mutex_lock(), ast_mutex_unlock(), ast_netsock_set_qos(), ast_parse_allow_disallow(), ast_parse_arg(), AST_SCHED_DEL_UNREF, ast_set2_flag, ast_set_flag, ast_skip_blanks(), AST_SSL_DONT_VERIFY_SERVER, ast_ssl_setup(), AST_SSL_VERIFY_CLIENT, ast_str2cos(), ast_str2tos(), ast_strdup, ast_strdupa, ast_strip(), ast_strlen_zero(), ast_stun_request(), ast_tcptls_server_start(), ast_test_flag, ast_true(), ast_unload_realtime(), ast_variable_browse(), ast_variable_retrieve(), ast_verb, ASTOBJ_CONTAINER_DESTROYALL, ASTOBJ_CONTAINER_TRAVERSE, ASTOBJ_RDLOCK, ASTOBJ_UNLOCK, sip_settings::autocreatepeer, bindaddr, build_peer(), ast_tls_config::cafile, sip_settings::callevents, ast_tls_config::capath, ast_tls_config::certfile, CHANNEL_MODULE_LOAD, channelreloadreason2txt(), ast_tls_config::cipher, cleanup_stale_contexts(), clear_realm_authentication(), clear_sip_domains(), sip_settings::compactheaders, CONFIG_FLAG_FILEUNCHANGED, CONFIG_STATUS_FILEINVALID, CONFIG_STATUS_FILEUNCHANGED, context, DEFAULT_ALLOW_EXT_DOM, DEFAULT_ALLOWGUEST, DEFAULT_ALWAYSAUTHREJECT, DEFAULT_AUTHLIMIT, DEFAULT_AUTHTIMEOUT, DEFAULT_AUTOCREATEPEER, DEFAULT_CALLCOUNTER, DEFAULT_CALLERID, DEFAULT_CALLEVENTS, DEFAULT_COMPACTHEADERS, DEFAULT_CONTEXT, sip_settings::default_context, DEFAULT_COS_AUDIO, DEFAULT_COS_SIP, DEFAULT_COS_TEXT, DEFAULT_COS_VIDEO, DEFAULT_DEFAULT_EXPIRY, DEFAULT_MATCHEXTERNIPLOCALLY, DEFAULT_MAX_CALL_BITRATE, DEFAULT_MAX_EXPIRY, DEFAULT_MAX_SE, DEFAULT_MAXMS, DEFAULT_MIN_EXPIRY, DEFAULT_MIN_SE, DEFAULT_MOHINTERPRET, DEFAULT_MOHSUGGEST, DEFAULT_MWI_EXPIRY, DEFAULT_NOTIFYCID, DEFAULT_NOTIFYMIME, DEFAULT_NOTIFYRINGING, DEFAULT_PEDANTIC, default_prefs, DEFAULT_QUALIFY, DEFAULT_QUALIFY_GAP, DEFAULT_QUALIFY_PEERS, DEFAULT_QUALIFYFREQ, DEFAULT_REALM, DEFAULT_REGEXTENONQUALIFY, DEFAULT_REGISTRATION_TIMEOUT, DEFAULT_RTPKEEPALIVE, DEFAULT_SDPOWNER, DEFAULT_SDPSESSION, DEFAULT_SRVLOOKUP, sip_settings::default_subscribecontext, DEFAULT_T1MIN, DEFAULT_TIMER_T1, default_tls_cfg, DEFAULT_TOS_AUDIO, DEFAULT_TOS_SIP, DEFAULT_TOS_TEXT, DEFAULT_TOS_VIDEO, default_transports, DEFAULT_USERAGENT, DEFAULT_VMEXTEN, dialog_unlink_all(), dialog_unref(), sip_settings::directrtpsetup, ast_tls_config::enabled, errno, EVENT_FLAG_SYSTEM, externip, FALSE, ast_tls_config::flags, sip_proxy::force, gen, global_jbconf, handle_common_options(), handle_t38_options(), IGNORE_CONTEXT, sip_settings::ignore_regexpire, inaddrcmp(), internip, sip_proxy::ip, ast_variable::lineno, ast_tcptls_session_args::local_address, LOG_ERROR, LOG_NOTICE, LOG_WARNING, manager_event, sip_settings::matchexterniplocally, MAXHOSTNAMELEN, sip_proxy::name, ast_variable::name, netlock, ast_variable::next, sip_settings::notifycid, sip_settings::notifyhold, sip_settings::notifyringing, OBJ_NODATA, sip_settings::outboundproxy, PARSE_DEFAULT, PARSE_IN_RANGE, PARSE_INADDR, PARSE_INT32, sip_settings::pedanticsipchecking, peer_markall_func(), sip_settings::peer_rtupdate, proxy_update(), sip_settings::realm, sip_settings::regextenonqualify, registry_unref(), regl, sip_settings::rtautoclear, sip_settings::rtsave_sysname, S_OR, secret, SESSION_TIMER_MODE_ACCEPT, SESSION_TIMER_REFRESHER_UAS, sip_cfg, sip_debug_config, sip_debug_console, SIP_DIRECT_MEDIA, SIP_DOMAIN_AUTO, SIP_DOMAIN_CONFIG, SIP_DTMF_RFC2833, SIP_NAT_RFC3581, SIP_PAGE2_ALLOWOVERLAP, SIP_PAGE2_ALLOWSUBSCRIBE, SIP_PAGE2_FAX_DETECT, SIP_PAGE2_FORWARD_LOOP_DETECTED, SIP_PAGE2_IGNORESDPVERSION, SIP_PAGE2_RTAUTOCLEAR, SIP_PAGE2_RTCACHEFRIENDS, SIP_PAGE2_TEXTSUPPORT, SIP_PAGE2_VIDEOSUPPORT, SIP_PAGE2_VIDEOSUPPORT_ALWAYS, sip_parse_host(), sip_register(), sip_registry_destroy(), sip_subscribe_mwi(), SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, SIP_TRANSPORT_UDP, SIP_TYPE_PEER, SIP_TYPE_USER, SIP_USEREQPHONE, sip_request::socket, sip_settings::srvlookup, STANDARD_SIP_PORT, STANDARD_TLS_PORT, str2stmode(), str2strefresher(), strsep(), stunaddr, ast_tcptls_session_args::tls_cfg, TRANSFER_CLOSED, TRANSFER_OPENFORALL, sip_proxy::transport, TRUE, sip_peer::type, unref_peer(), and ast_variable::value.

Referenced by load_module(), and sip_do_reload().

{
   struct ast_config *cfg, *ucfg;
   struct ast_variable *v;
   struct sip_peer *peer;
   char *cat, *stringp, *context, *oldregcontext;
   char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
   struct ast_flags dummy[2];
   struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
   int auto_sip_domains = FALSE;
   struct sockaddr_in old_bindaddr = bindaddr;
   int registry_count = 0, peer_count = 0;
   time_t run_start, run_end;
   
   run_start = time(0);
   ast_unload_realtime("sipregs");     
   ast_unload_realtime("sippeers");
   cfg = ast_config_load(config, config_flags);

   /* We *must* have a config file otherwise stop immediately */
   if (!cfg) {
      ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
      return -1;
   } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
      ucfg = ast_config_load("users.conf", config_flags);
      if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
         return 1;
      } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
         ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
         return 1;
      }
      /* Must reread both files, because one changed */
      ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
      if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
         ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
         ast_config_destroy(ucfg);
         return 1;
      }
   } else if (cfg == CONFIG_STATUS_FILEINVALID) {
      ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
      return 1;
   } else {
      ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
      if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
         ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
         ast_config_destroy(cfg);
         return 1;
      }
   }

   /* Initialize tcp sockets */
   memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
   memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));

   ast_free_ha(global_contact_ha);
   global_contact_ha = NULL;

   default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */

   sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
   sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);

   if (reason != CHANNEL_MODULE_LOAD) {
      ast_debug(4, "--------------- SIP reload started\n");

      clear_realm_authentication(authl);
      clear_sip_domains();
      authl = NULL;

      /* First, destroy all outstanding registry calls */
      /* This is needed, since otherwise active registry entries will not be destroyed */
      ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */

            ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
            if (iterator->call) {
               ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
               /* This will also remove references to the registry */
               dialog_unlink_all(iterator->call, TRUE, TRUE);
               iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
            }
            if (iterator->expire > -1) {
               AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
            }
            if (iterator->timeout > -1) {
               AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
            }
            ASTOBJ_UNLOCK(iterator);
            
      } while(0));

      /* Then, actually destroy users and registry */
      ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
      ast_debug(4, "--------------- Done destroying registry list\n");
      ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
   }
   
   /* Reset certificate handling for TLS sessions */
   if (reason != CHANNEL_MODULE_LOAD) {
      ast_free(default_tls_cfg.certfile);
      ast_free(default_tls_cfg.cipher);
      ast_free(default_tls_cfg.cafile);
      ast_free(default_tls_cfg.capath);
   }
   default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
   default_tls_cfg.cipher = ast_strdup("");
   default_tls_cfg.cafile = ast_strdup("");
   default_tls_cfg.capath = ast_strdup("");

   
   /* Initialize copy of current global_regcontext for later use in removing stale contexts */
   ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
   oldregcontext = oldcontexts;

   /* Clear all flags before setting default values */
   /* Preserve debugging settings for console */
   sipdebug &= sip_debug_console;
   ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
   ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);

   /* Reset IP addresses  */
   memset(&bindaddr, 0, sizeof(bindaddr));
   memset(&stunaddr, 0, sizeof(stunaddr));
   memset(&internip, 0, sizeof(internip));

   /* Free memory for local network address mask */
   ast_free_ha(localaddr);
   memset(&localaddr, 0, sizeof(localaddr));
   memset(&externip, 0, sizeof(externip));
   memset(&default_prefs, 0 , sizeof(default_prefs));
   memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
   sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
   sip_cfg.outboundproxy.ip.sin_family = AF_INET;  /*!< Type of address: IPv4 */
   sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
   default_transports = 0;          /*!< Reset default transport to zero here, default value later on */
   default_primary_transport = 0;         /*!< Reset default primary transport to zero here, default value later on */
   ourport_tcp = STANDARD_SIP_PORT;
   ourport_tls = STANDARD_TLS_PORT;
   bindaddr.sin_port = htons(STANDARD_SIP_PORT);
   sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
   global_tos_sip = DEFAULT_TOS_SIP;
   global_tos_audio = DEFAULT_TOS_AUDIO;
   global_tos_video = DEFAULT_TOS_VIDEO;
   global_tos_text = DEFAULT_TOS_TEXT;
   global_cos_sip = DEFAULT_COS_SIP;
   global_cos_audio = DEFAULT_COS_AUDIO;
   global_cos_video = DEFAULT_COS_VIDEO;
   global_cos_text = DEFAULT_COS_TEXT;

   externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
   externexpire = 0;       /* Expiration for DNS re-issuing */
   externrefresh = 10;

   /* Reset channel settings to default before re-configuring */
   sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
   global_regcontext[0] = '\0';
   sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
   sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
   sip_cfg.notifycid = DEFAULT_NOTIFYCID;
   sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
   sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
   sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
   sip_cfg.allowsubscribe = FALSE;
   snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
   snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
   snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
   global_prematuremediafilter = TRUE;
   ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
   ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
   ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
   sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
   global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
   global_regattempts_max = 0;
   sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
   sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
   global_autoframing = 0;
   sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
   global_callcounter = DEFAULT_CALLCOUNTER;
   global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
   global_rtptimeout = 0;
   global_rtpholdtimeout = 0;
   global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
   sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
   sip_cfg.rtautoclear = 120;
   ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
   ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);     /* Default for all devices: TRUE */
   sip_cfg.peer_rtupdate = TRUE;
   global_dynamic_exclude_static = 0;  /* Exclude static peers */

   /* Session-Timers */
   global_st_mode = SESSION_TIMER_MODE_ACCEPT;    
   global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
   global_min_se  = DEFAULT_MIN_SE;
   global_max_se  = DEFAULT_MAX_SE;

   /* Peer poking settings */
   global_qualify_gap = DEFAULT_QUALIFY_GAP;
   global_qualify_peers = DEFAULT_QUALIFY_PEERS;

   /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
   ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
   sip_cfg.default_subscribecontext[0] = '\0';
   default_language[0] = '\0';
   default_fromdomain[0] = '\0';
   default_qualify = DEFAULT_QUALIFY;
   default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
   ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
   ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
   ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
   ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);        /*!< Default DTMF setting: RFC2833 */
   ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);         /*!< NAT support if requested by device with rport */
   ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);        /*!< Allow re-invites */
   ast_set_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED); /*!< Set up call forward on 482 Loop Detected */

   /* Debugging settings, always default to off */
   dumphistory = FALSE;
   recordhistory = FALSE;
   sipdebug &= ~sip_debug_config;

   /* Misc settings for the channel */
   global_relaxdtmf = FALSE;
   sip_cfg.callevents = DEFAULT_CALLEVENTS;
   global_authfailureevents = FALSE;
   global_t1 = DEFAULT_TIMER_T1;
   global_timer_b = 64 * DEFAULT_TIMER_T1;
   global_t1min = DEFAULT_T1MIN;
   global_qualifyfreq = DEFAULT_QUALIFYFREQ;
   global_t38_maxdatagram = -1;
   global_shrinkcallerid = 1;
   authlimit = DEFAULT_AUTHLIMIT;
   authtimeout = DEFAULT_AUTHTIMEOUT;

   sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;

   /* Copy the default jb config over global_jbconf */
   memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));

   ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
   ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
   ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
   ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);


   /* Read the [general] config section of sip.conf (or from realtime config) */
   for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
      if (handle_common_options(&global_flags[0], &dummy[0], v))
         continue;
      if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
         continue;
      }
      /* handle jb conf */
      if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
         continue;

      if (!strcasecmp(v->name, "context")) {
         ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
      } else if (!strcasecmp(v->name, "subscribecontext")) {
         ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
      } else if (!strcasecmp(v->name, "callcounter")) {
         global_callcounter = ast_true(v->value) ? 1 : 0;
      } else if (!strcasecmp(v->name, "allowguest")) {
         sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
      } else if (!strcasecmp(v->name, "realm")) {
         ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
      } else if (!strcasecmp(v->name, "useragent")) {
         ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
         ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
      } else if (!strcasecmp(v->name, "sdpsession")) {
         ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
      } else if (!strcasecmp(v->name, "sdpowner")) {
         /* Field cannot contain spaces */
         if (!strstr(v->value, " "))
            ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
         else
            ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
      } else if (!strcasecmp(v->name, "allowtransfer")) {
         sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
      } else if (!strcasecmp(v->name, "rtcachefriends")) {
         ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);   
      } else if (!strcasecmp(v->name, "rtsavesysname")) {
         sip_cfg.rtsave_sysname = ast_true(v->value);
      } else if (!strcasecmp(v->name, "rtupdate")) {
         sip_cfg.peer_rtupdate = ast_true(v->value);
      } else if (!strcasecmp(v->name, "ignoreregexpire")) {
         sip_cfg.ignore_regexpire = ast_true(v->value);
      } else if (!strcasecmp(v->name, "timert1")) {
         /* Defaults to 500ms, but RFC 3261 states that it is recommended
          * for the value to be set higher, though a lower value is only
          * allowed on private networks unconnected to the Internet. */
         global_t1 = atoi(v->value);
         /* Note that timer B is dependent on the value of T1 */
         global_timer_b = global_t1 * 64;
      } else if (!strcasecmp(v->name, "t1min")) {
         global_t1min = atoi(v->value);
      } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
         char *val = ast_strdupa(v->value);
         char *trans;

         while ((trans = strsep(&val, ","))) {
            trans = ast_skip_blanks(trans);

            if (!strncasecmp(trans, "udp", 3)) 
               default_transports |= SIP_TRANSPORT_UDP;
            else if (!strncasecmp(trans, "tcp", 3))
               default_transports |= SIP_TRANSPORT_TCP;
            else if (!strncasecmp(trans, "tls", 3))
               default_transports |= SIP_TRANSPORT_TLS;
            else
               ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
            if (default_primary_transport == 0) {
               default_primary_transport = default_transports;
            }
         }
      } else if (!strcasecmp(v->name, "tcpenable")) {
         sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
         ast_debug(2, "Enabling TCP socket for listening\n");
      } else if (!strcasecmp(v->name, "tcpbindaddr")) {
         int family = sip_tcp_desc.local_address.sin_family;
         if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
            ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
         sip_tcp_desc.local_address.sin_family = family;
         ast_debug(2, "Setting TCP socket address to %s\n", v->value);
      } else if (!strcasecmp(v->name, "tlsenable")) {
         default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
         sip_tls_desc.local_address.sin_family = AF_INET;
      } else if (!strcasecmp(v->name, "tlscertfile")) {
         ast_free(default_tls_cfg.certfile);
         default_tls_cfg.certfile = ast_strdup(v->value);
      } else if (!strcasecmp(v->name, "tlscipher")) {
         ast_free(default_tls_cfg.cipher);
         default_tls_cfg.cipher = ast_strdup(v->value);
      } else if (!strcasecmp(v->name, "tlscafile")) {
         ast_free(default_tls_cfg.cafile);
         default_tls_cfg.cafile = ast_strdup(v->value);
      } else if (!strcasecmp(v->name, "tlscapath")) {
         ast_free(default_tls_cfg.capath);
         default_tls_cfg.capath = ast_strdup(v->value);
      } else if (!strcasecmp(v->name, "tlsverifyclient")) {
         ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);   
      } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
         ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER); 
      } else if (!strcasecmp(v->name, "tlsbindaddr")) {
         if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
            ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
      } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
         global_dynamic_exclude_static = ast_true(v->value);
      } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
         int ha_error = 0;
         global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
         if (ha_error) {
            ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
         }
      } else if (!strcasecmp(v->name, "rtautoclear")) {
         int i = atoi(v->value);
         if (i > 0)
            sip_cfg.rtautoclear = i;
         else
            i = 0;
         ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
      } else if (!strcasecmp(v->name, "usereqphone")) {
         ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);   
      } else if (!strcasecmp(v->name, "prematuremedia")) {
         global_prematuremediafilter = ast_true(v->value);
      } else if (!strcasecmp(v->name, "relaxdtmf")) {
         global_relaxdtmf = ast_true(v->value);
      } else if (!strcasecmp(v->name, "vmexten")) {
         ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
      } else if (!strcasecmp(v->name, "rtptimeout")) {
         if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
            ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
            global_rtptimeout = 0;
         }
      } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
         if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
            ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
            global_rtpholdtimeout = 0;
         }
      } else if (!strcasecmp(v->name, "rtpkeepalive")) {
         if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
            ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
            global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
         }
      } else if (!strcasecmp(v->name, "compactheaders")) {
         sip_cfg.compactheaders = ast_true(v->value);
      } else if (!strcasecmp(v->name, "notifymimetype")) {
         ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
      } else if (!strcasecmp(v->name, "directrtpsetup")) {
         sip_cfg.directrtpsetup = ast_true(v->value);
      } else if (!strcasecmp(v->name, "notifyringing")) {
         sip_cfg.notifyringing = ast_true(v->value);
      } else if (!strcasecmp(v->name, "notifyhold")) {
         sip_cfg.notifyhold = ast_true(v->value);
      } else if (!strcasecmp(v->name, "notifycid")) {
         if (!strcasecmp(v->value, "ignore-context")) {
            sip_cfg.notifycid = IGNORE_CONTEXT;
         } else {
            sip_cfg.notifycid = ast_true(v->value);
         }
      } else if (!strcasecmp(v->name, "alwaysauthreject")) {
         sip_cfg.alwaysauthreject = ast_true(v->value);
      } else if (!strcasecmp(v->name, "mohinterpret")) {
         ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
      } else if (!strcasecmp(v->name, "mohsuggest")) {
         ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
      } else if (!strcasecmp(v->name, "language")) {
         ast_copy_string(default_language, v->value, sizeof(default_language));
      } else if (!strcasecmp(v->name, "regcontext")) {
         ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
         stringp = newcontexts;
         /* Let's remove any contexts that are no longer defined in regcontext */
         cleanup_stale_contexts(stringp, oldregcontext);
         /* Create contexts if they don't exist already */
         while ((context = strsep(&stringp, "&"))) {
            ast_copy_string(used_context, context, sizeof(used_context));
            ast_context_find_or_create(NULL, NULL, context, "SIP");
         }
         ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
      } else if (!strcasecmp(v->name, "regextenonqualify")) {
         sip_cfg.regextenonqualify = ast_true(v->value);
      } else if (!strcasecmp(v->name, "callerid")) {
         ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
      } else if (!strcasecmp(v->name, "fromdomain")) {
         ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
      } else if (!strcasecmp(v->name, "outboundproxy")) {
         int portnum;
         char *tok, *proxyname;

         if (ast_strlen_zero(v->value)) {
            ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
            continue;
         }

         tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));

         sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);

         sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
   
         if ((tok = strtok(NULL, ","))) {
            sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
         } else {
            sip_cfg.outboundproxy.force = FALSE;
         }

         if (ast_strlen_zero(proxyname)) {
            ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
            sip_cfg.outboundproxy.name[0] = '\0';
            continue;
         }

         ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));

         proxy_update(&sip_cfg.outboundproxy);
      } else if (!strcasecmp(v->name, "autocreatepeer")) {
         sip_cfg.autocreatepeer = ast_true(v->value);
      } else if (!strcasecmp(v->name, "match_auth_username")) {
         global_match_auth_username = ast_true(v->value);
      } else if (!strcasecmp(v->name, "srvlookup")) {
         sip_cfg.srvlookup = ast_true(v->value);
      } else if (!strcasecmp(v->name, "pedantic")) {
         sip_cfg.pedanticsipchecking = ast_true(v->value);
      } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
         max_expiry = atoi(v->value);
         if (max_expiry < 1)
            max_expiry = DEFAULT_MAX_EXPIRY;
      } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
         min_expiry = atoi(v->value);
         if (min_expiry < 1)
            min_expiry = DEFAULT_MIN_EXPIRY;
      } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
         default_expiry = atoi(v->value);
         if (default_expiry < 1)
            default_expiry = DEFAULT_DEFAULT_EXPIRY;
      } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
         mwi_expiry = atoi(v->value);
         if (mwi_expiry < 1)
            mwi_expiry = DEFAULT_MWI_EXPIRY;
      } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
         if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
                 &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
            ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
               v->name, v->value, v->lineno, config);
         }
      } else if (!strcasecmp(v->name, "tcpauthlimit")) {
         if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
                 &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
            ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
               v->name, v->value, v->lineno, config);
         }
      } else if (!strcasecmp(v->name, "sipdebug")) {
         if (ast_true(v->value))
            sipdebug |= sip_debug_config;
      } else if (!strcasecmp(v->name, "dumphistory")) {
         dumphistory = ast_true(v->value);
      } else if (!strcasecmp(v->name, "recordhistory")) {
         recordhistory = ast_true(v->value);
      } else if (!strcasecmp(v->name, "registertimeout")) {
         global_reg_timeout = atoi(v->value);
         if (global_reg_timeout < 1)
            global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
      } else if (!strcasecmp(v->name, "registerattempts")) {
         global_regattempts_max = atoi(v->value);
      } else if (!strcasecmp(v->name, "stunaddr")) {
         stunaddr.sin_port = htons(3478);
         if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
            ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
         externexpire = time(NULL);
      } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
         if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
            ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
      } else if (!strcasecmp(v->name, "localnet")) {
         struct ast_ha *na;
         int ha_error = 0;

         if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
            ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
         else
            localaddr = na;
         if (ha_error)
            ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
      } else if (!strcasecmp(v->name, "externip")) {
         if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
            ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
         externexpire = 0;
         /* If no port was specified use the value of bindport */
         if (!externip.sin_port)
            externip.sin_port = bindaddr.sin_port;
      } else if (!strcasecmp(v->name, "externhost")) {
         ast_copy_string(externhost, v->value, sizeof(externhost));
         if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
            ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
         externexpire = time(NULL);
         /* If no port was specified use the value of bindport */
         if (!externip.sin_port)
            externip.sin_port = bindaddr.sin_port;
      } else if (!strcasecmp(v->name, "externrefresh")) {
         if (sscanf(v->value, "%30d", &externrefresh) != 1) {
            ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
            externrefresh = 10;
         }
      } else if (!strcasecmp(v->name, "allow")) {
         int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
         if (error)
            ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
      } else if (!strcasecmp(v->name, "disallow")) {
         int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
         if (error)
            ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
      } else if (!strcasecmp(v->name, "autoframing")) {
         global_autoframing = ast_true(v->value);
      } else if (!strcasecmp(v->name, "allowexternaldomains")) {
         sip_cfg.allow_external_domains = ast_true(v->value);
      } else if (!strcasecmp(v->name, "autodomain")) {
         auto_sip_domains = ast_true(v->value);
      } else if (!strcasecmp(v->name, "domain")) {
         char *domain = ast_strdupa(v->value);
         char *cntx = strchr(domain, ',');

         if (cntx)
            *cntx++ = '\0';

         if (ast_strlen_zero(cntx))
            ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
         if (ast_strlen_zero(domain))
            ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
         else
            add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
      } else if (!strcasecmp(v->name, "register")) {
         if (sip_register(v->value, v->lineno) == 0)
            registry_count++;
      } else if (!strcasecmp(v->name, "mwi")) {
         sip_subscribe_mwi(v->value, v->lineno);
      } else if (!strcasecmp(v->name, "tos_sip")) {
         if (ast_str2tos(v->value, &global_tos_sip))
            ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
      } else if (!strcasecmp(v->name, "tos_audio")) {
         if (ast_str2tos(v->value, &global_tos_audio))
            ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
      } else if (!strcasecmp(v->name, "tos_video")) {
         if (ast_str2tos(v->value, &global_tos_video))
            ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
      } else if (!strcasecmp(v->name, "tos_text")) {
         if (ast_str2tos(v->value, &global_tos_text))
            ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
      } else if (!strcasecmp(v->name, "cos_sip")) {
         if (ast_str2cos(v->value, &global_cos_sip))
            ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
      } else if (!strcasecmp(v->name, "cos_audio")) {
         if (ast_str2cos(v->value, &global_cos_audio))
            ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
      } else if (!strcasecmp(v->name, "cos_video")) {
         if (ast_str2cos(v->value, &global_cos_video))
            ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
      } else if (!strcasecmp(v->name, "cos_text")) {
         if (ast_str2cos(v->value, &global_cos_text))
            ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
      } else if (!strcasecmp(v->name, "bindport")) {
         int i;
         if (sscanf(v->value, "%5d", &i) == 1) {
            bindaddr.sin_port = htons(i);
         } else {
            ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
         }
      } else if (!strcasecmp(v->name, "qualify")) {
         if (!strcasecmp(v->value, "no")) {
            default_qualify = 0;
         } else if (!strcasecmp(v->value, "yes")) {
            default_qualify = DEFAULT_MAXMS;
         } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
            ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
            default_qualify = 0;
         }
      } else if (!strcasecmp(v->name, "qualifyfreq")) {
         int i;
         if (sscanf(v->value, "%30d", &i) == 1)
            global_qualifyfreq = i * 1000;
         else {
            ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
            global_qualifyfreq = DEFAULT_QUALIFYFREQ;
         }
      } else if (!strcasecmp(v->name, "callevents")) {
         sip_cfg.callevents = ast_true(v->value);
      } else if (!strcasecmp(v->name, "authfailureevents")) {
         global_authfailureevents = ast_true(v->value);
      } else if (!strcasecmp(v->name, "maxcallbitrate")) {
         default_maxcallbitrate = atoi(v->value);
         if (default_maxcallbitrate < 0)
            default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
      } else if (!strcasecmp(v->name, "matchexterniplocally")) {
         sip_cfg.matchexterniplocally = ast_true(v->value);
      } else if (!strcasecmp(v->name, "session-timers")) {
         int i = (int) str2stmode(v->value); 
         if (i < 0) {
            ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
            global_st_mode = SESSION_TIMER_MODE_ACCEPT;
         } else {
            global_st_mode = i;
         }
      } else if (!strcasecmp(v->name, "session-expires")) {
         if (sscanf(v->value, "%30d", &global_max_se) != 1) {
            ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
            global_max_se = DEFAULT_MAX_SE;
         } 
      } else if (!strcasecmp(v->name, "session-minse")) {
         if (sscanf(v->value, "%30d", &global_min_se) != 1) {
            ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
            global_min_se = DEFAULT_MIN_SE;
         } 
         if (global_min_se < 90) {
            ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
            global_min_se = DEFAULT_MIN_SE;
         } 
      } else if (!strcasecmp(v->name, "session-refresher")) {
         int i = (int) str2strefresher(v->value); 
         if (i < 0) {
            ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
            global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
         } else {
            global_st_refresher = i;
         }
      } else if (!strcasecmp(v->name, "qualifygap")) {
         if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
            ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
            global_qualify_gap = DEFAULT_QUALIFY_GAP;
         }
      } else if (!strcasecmp(v->name, "qualifypeers")) {
         if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
            ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
            global_qualify_peers = DEFAULT_QUALIFY_PEERS;
         }
      } else if (!strcasecmp(v->name, "shrinkcallerid")) {
         if (ast_true(v->value)) {
            global_shrinkcallerid = 1;
         } else if (ast_false(v->value)) {
            global_shrinkcallerid = 0;
         } else {
            ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
         }
      }
   }

   if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
      ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
      sip_cfg.allow_external_domains = 1;
   }
   /* If not configured, set default transports */
   if (default_transports == 0) {
      default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
   }
   
   /* Build list of authentication to various SIP realms, i.e. service providers */
   for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
      /* Format for authentication is auth = username:password@realm */
      if (!strcasecmp(v->name, "auth"))
         authl = add_realm_authentication(authl, v->value, v->lineno);
   }

   /* Set UDP address and open socket */
   bindaddr.sin_family = AF_INET;
   internip = bindaddr;
   if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
      ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
      ast_config_destroy(cfg);
      return 0;
   }

   ast_mutex_lock(&netlock);
   if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
      close(sipsock);
      sipsock = -1;
   }
   if (sipsock < 0) {
      sipsock = socket(AF_INET, SOCK_DGRAM, 0);
      if (sipsock < 0) {
         ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
         ast_config_destroy(cfg);
         ast_mutex_unlock(&netlock);
         return -1;
      } else {
         /* Allow SIP clients on the same host to access us: */
         const int reuseFlag = 1;

         setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
               (const char*)&reuseFlag,
               sizeof reuseFlag);

         ast_enable_packet_fragmentation(sipsock);

         if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
            ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
            ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
            strerror(errno));
            close(sipsock);
            sipsock = -1;
         } else {
            ast_verb(2, "SIP Listening on %s:%d\n",
                  ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
            ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
         }
      }
   } else {
      ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
   }
   if (stunaddr.sin_addr.s_addr != 0) {
      ast_debug(1, "stun to %s:%d\n",
         ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
      ast_stun_request(sipsock, &stunaddr,
         NULL, &externip);
      ast_debug(1, "STUN sees us at %s:%d\n", 
         ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
   }
   ast_mutex_unlock(&netlock);

   /* Start TCP server */
   ast_tcptls_server_start(&sip_tcp_desc);
   if (sip_tcp_desc.accept_fd == -1 &&  sip_tcp_desc.local_address.sin_family == AF_INET) {
      /* TCP server start failed. Tell the admin */
      ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
      sip_tcp_desc.local_address.sin_family = 0;
   } else {
      ast_debug(2, "SIP TCP server started\n");
   }

   /* Start TLS server if needed */
   memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));

   if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
      ast_tcptls_server_start(&sip_tls_desc);
      if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
         ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
         sip_tls_desc.tls_cfg = NULL;
      }
   } else if (sip_tls_desc.tls_cfg->enabled) {
      sip_tls_desc.tls_cfg = NULL;
      ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
   }

   if (ucfg) {
      struct ast_variable *gen;
      int genhassip, genregistersip;
      const char *hassip, *registersip;
      
      genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
      genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
      gen = ast_variable_browse(ucfg, "general");
      cat = ast_category_browse(ucfg, NULL);
      while (cat) {
         if (strcasecmp(cat, "general")) {
            hassip = ast_variable_retrieve(ucfg, cat, "hassip");
            registersip = ast_variable_retrieve(ucfg, cat, "registersip");
            if (ast_true(hassip) || (!hassip && genhassip)) {
               peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
               if (peer) {
                  /* user.conf entries are always of type friend */
                  peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
                  ao2_t_link(peers, peer, "link peer into peer table");
                  if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
                     ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
                  }
                  
                  unref_peer(peer, "unref_peer: from reload_config");
                  peer_count++;
               }
            }
            if (ast_true(registersip) || (!registersip && genregistersip)) {
               char tmp[256];
               const char *host = ast_variable_retrieve(ucfg, cat, "host");
               const char *username = ast_variable_retrieve(ucfg, cat, "username");
               const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
               const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
               const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
               if (!host)
                  host = ast_variable_retrieve(ucfg, "general", "host");
               if (!username)
                  username = ast_variable_retrieve(ucfg, "general", "username");
               if (!secret)
                  secret = ast_variable_retrieve(ucfg, "general", "secret");
               if (!contact)
                  contact = "s";
               if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
                  if (!ast_strlen_zero(secret)) {
                     if (!ast_strlen_zero(authuser)) {
                        snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
                     } else {
                        snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
                     }
                  } else if (!ast_strlen_zero(authuser)) {
                     snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
                  } else {
                     snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
                  }
                  if (sip_register(tmp, 0) == 0)
                     registry_count++;
               }
            }
         }
         cat = ast_category_browse(ucfg, cat);
      }
      ast_config_destroy(ucfg);
   }

   /* Load peers, users and friends */
   cat = NULL;
   while ( (cat = ast_category_browse(cfg, cat)) ) {
      const char *utype;
      if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
         continue;
      utype = ast_variable_retrieve(cfg, cat, "type");
      if (!utype) {
         ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
         continue;
      } else {
         if (!strcasecmp(utype, "user")) {
            ;
         } else if (!strcasecmp(utype, "friend")) {
            ;
         } else if (!strcasecmp(utype, "peer")) {
            ;
         } else {
            ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
            continue;
         }
         peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
         if (peer) {
            ao2_t_link(peers, peer, "link peer into peers table");
            if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
               ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
            }
            unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
            peer_count++;
         }
      }
   }

   /* Add default domains - host name, IP address and IP:port
    * Only do this if user added any sip domain with "localdomains" 
    * In order to *not* break backwards compatibility 
    *    Some phones address us at IP only, some with additional port number 
    */
   if (auto_sip_domains) {
      char temp[MAXHOSTNAMELEN];

      /* First our default IP address */
      if (bindaddr.sin_addr.s_addr) {
         add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
      } else if (internip.sin_addr.s_addr) {
      /* Our internal IP address, if configured */
         add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
      } else {
         ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
      }

      /* If TCP is running on a different IP than UDP, then add it too */
      if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
         add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);

      /* If TLS is running on a differen IP than UDP and TCP, then add that too */
      if (sip_tls_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tls_desc.local_address) && inaddrcmp(&sip_tcp_desc.local_address, &sip_tls_desc.local_address))
         add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);

      /* Our extern IP address, if configured */
      if (externip.sin_addr.s_addr)
         add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);

      /* Extern host name (NAT traversal support) */
      if (!ast_strlen_zero(externhost))
         add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
      
      /* Our host name */
      if (!gethostname(temp, sizeof(temp)))
         add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
   }

   /* Release configuration from memory */
   ast_config_destroy(cfg);

   /* Load the list of manual NOTIFY types to support */
   if (notify_types)
      ast_config_destroy(notify_types);
   if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
      ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
      notify_types = NULL;
   }

   /* Done, tell the manager */
   manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "ChannelType: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\n", channelreloadreason2txt(reason), registry_count, peer_count);
   run_end = time(0);
   ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));

   return 0;
}
static char * remove_uri_parameters ( char *  uri) [static]

Definition at line 11030 of file chan_sip.c.

Referenced by extract_uri(), parse_moved_contact(), register_verify(), reqprep(), and transmit_state_notify().

{
   char *atsign;
   atsign = strchr(uri, '@'); /* First, locate the at sign */
   if (!atsign)
      atsign = uri;  /* Ok hostname only, let's stick with the rest */
   atsign = strchr(atsign, ';'); /* Locate semi colon */
   if (atsign)
      *atsign = '\0';   /* Kill at the semi colon */
   return uri;
}
static void replace_cid ( struct sip_pvt p,
const char *  rpid_num,
const char *  calleridname 
) [static]

helper function for check_{user|peer}_ok()

Definition at line 14492 of file chan_sip.c.

References ast_is_shrinkable_phonenumber(), ast_shrink_phone_number(), ast_strdupa, ast_string_field_set, ast_strlen_zero(), ast_test_flag, cid_name, cid_num, sip_pvt::flags, and SIP_TRUSTRPID.

Referenced by check_peer_ok(), and check_user_full().

{
   /* replace callerid if rpid found, and not restricted */
   if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
      char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
      if (!ast_strlen_zero(calleridname))
         ast_string_field_set(p, cid_name, calleridname);
      if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
         ast_shrink_phone_number(tmp);
      ast_string_field_set(p, cid_num, tmp);
   }
}
static int reply_digest ( struct sip_pvt p,
struct sip_request req,
char *  header,
int  sipmethod,
char *  digest,
int  digest_len 
) [static]

reply to authentication for outbound registrations

Returns:
Returns -1 if we have no auth
Note:
This is used for register= servers in sip.conf, SIP proxies we register with for receiving calls from.

Definition at line 17616 of file chan_sip.c.

References ast_copy_string(), ast_log(), ast_skip_blanks(), ast_string_field_ptr_set, ast_string_field_set, ast_strlen_zero(), build_reply_digest(), sip_pvt::domain, get_header(), LOG_WARNING, sip_registry::nonce, sip_pvt::nonce, sip_registry::noncecount, sip_pvt::noncecount, sip_registry::opaque, sip_pvt::opaque, sip_registry::qop, sip_pvt::qop, sip_registry::realm, sip_pvt::realm, sip_pvt::registry, and strsep().

Referenced by do_proxy_auth(), and do_register_auth().

{
   char tmp[512];
   char *c;
   char oldnonce[256];

   /* table of recognised keywords, and places where they should be copied */
   const struct x {
      const char *key;
      const ast_string_field *field;
   } *i, keys[] = {
      { "realm=", &p->realm },
      { "nonce=", &p->nonce },
      { "opaque=", &p->opaque },
      { "qop=", &p->qop },
      { "domain=", &p->domain },
      { NULL, 0 },
   };

   ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
   if (ast_strlen_zero(tmp)) 
      return -1;
   if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
      ast_log(LOG_WARNING, "missing Digest.\n");
      return -1;
   }
   c = tmp + strlen("Digest ");
   ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
   while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
      for (i = keys; i->key != NULL; i++) {
         char *src, *separator;
         if (strncasecmp(c, i->key, strlen(i->key)) != 0)
            continue;
         /* Found. Skip keyword, take text in quotes or up to the separator. */
         c += strlen(i->key);
         if (*c == '"') {
            src = ++c;
            separator = "\"";
         } else {
            src = c;
            separator = ",";
         }
         strsep(&c, separator); /* clear separator and move ptr */
         ast_string_field_ptr_set(p, i->field, src);
         break;
      }
      if (i->key == NULL) /* not found, try ',' */
         strsep(&c, ",");
   }
   /* Reset nonce count */
   if (strcmp(p->nonce, oldnonce)) 
      p->noncecount = 0;

   /* Save auth data for following registrations */
   if (p->registry) {
      struct sip_registry *r = p->registry;

      if (strcmp(r->nonce, p->nonce)) {
         ast_string_field_set(r, realm, p->realm);
         ast_string_field_set(r, nonce, p->nonce);
         ast_string_field_set(r, domain, p->domain);
         ast_string_field_set(r, opaque, p->opaque);
         ast_string_field_set(r, qop, p->qop);
         r->noncecount = 0;
      }
   }
   return build_reply_digest(p, sipmethod, digest, digest_len); 
}
static int reqprep ( struct sip_request req,
struct sip_pvt p,
int  sipmethod,
int  seqno,
int  newbranch 
) [static]

Initialize a SIP request message (not the initial one in a dialog)

< Strict routing flag

Definition at line 9932 of file chan_sip.c.

References add_header(), add_route(), ast_copy_string(), ast_debug, ast_random(), ast_string_field_set, ast_strlen_zero(), ast_test_flag, sip_pvt::branch, build_via(), sip_pvt::callid, copy_header(), DEFAULT_MAX_FORWARDS, FALSE, sip_pvt::flags, get_header(), get_in_brackets(), sip_route::hop, init_req(), sip_pvt::initreq, sip_pvt::invite_branch, sip_pvt::lastmsg, sip_route::next, sip_pvt::ocseq, sip_pvt::okcontacturi, sip_pvt::our_contact, remove_uri_parameters(), REQ_OFFSET_TO_STR, sip_request::rlPart2, sip_pvt::route, sip_pvt::rpid, set_destination(), SIP_ACK, SIP_BYE, SIP_CANCEL, SIP_INVITE, SIP_MESSAGE, sip_methods, SIP_OUTGOING, sip_st_dlg::st_active, sip_st_dlg::st_active_peer_ua, st_get_se(), sip_st_dlg::st_interval, sip_st_dlg::st_ref, sip_pvt::stimer, strcasestr(), strefresher2str(), sip_pvt::tag, text, cfsip_methods::text, sip_pvt::theirtag, TRUE, sip_pvt::uri, url, sip_pvt::url, and sip_pvt::via.

Referenced by transmit_info_with_digit(), transmit_info_with_vidupdate(), transmit_invite(), transmit_message_with_text(), transmit_notify_with_sipfrag(), transmit_refer(), transmit_reinvite_with_sdp(), transmit_request(), transmit_request_with_auth(), and transmit_state_notify().

{
   struct sip_request *orig = &p->initreq;
   char stripped[80];
   char tmp[80];
   char newto[256];
   const char *c;
   const char *ot, *of;
   int is_strict = FALSE;     /*!< Strict routing flag */
   int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */

   memset(req, 0, sizeof(struct sip_request));
   
   snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
   
   if (!seqno) {
      p->ocseq++;
      seqno = p->ocseq;
   }
   
   /* A CANCEL must have the same branch as the INVITE that it is canceling. */
   if (sipmethod == SIP_CANCEL) {
      p->branch = p->invite_branch;
      build_via(p);
   } else if (newbranch && (sipmethod == SIP_INVITE)) {
      p->branch ^= ast_random();
      p->invite_branch = p->branch;
      build_via(p);
   } else if (newbranch) {
      p->branch ^= ast_random();
      build_via(p);
   }

   /* Check for strict or loose router */
   if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
      is_strict = TRUE;
      if (sipdebug)
         ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
   }
   
   if (sipmethod == SIP_CANCEL)
      c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
   else if (sipmethod == SIP_ACK) {
      /* Use URI from Contact: in 200 OK (if INVITE) 
      (we only have the contacturi on INVITEs) */
      if (!ast_strlen_zero(p->okcontacturi))
         c = is_strict ? p->route->hop : p->okcontacturi;
      else
         c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
   } else if (!ast_strlen_zero(p->okcontacturi)) 
      c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
   else if (!ast_strlen_zero(p->uri)) 
      c = p->uri;
   else {
      char *n;
      /* We have no URI, use To: or From:  header as URI (depending on direction) */
      ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
            sizeof(stripped));
      n = get_in_brackets(stripped);
      c = remove_uri_parameters(n);
   }  
   init_req(req, sipmethod, c);

   snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);

   add_header(req, "Via", p->via);
   if (p->route) {
      set_destination(p, p->route->hop);
      add_route(req, is_strict ? p->route->next : p->route);
   }
   add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);

   ot = get_header(orig, "To");
   of = get_header(orig, "From");

   /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
      as our original request, including tag (or presumably lack thereof) */
   if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
      /* Add the proper tag if we don't have it already.  If they have specified
         their tag, use it.  Otherwise, use our own tag */
      if (is_outbound && !ast_strlen_zero(p->theirtag))
         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
      else if (!is_outbound)
         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
      else
         snprintf(newto, sizeof(newto), "%s", ot);
      ot = newto;
   }

   if (is_outbound) {
      add_header(req, "From", of);
      add_header(req, "To", ot);
   } else {
      add_header(req, "From", ot);
      add_header(req, "To", of);
   }
   /* Do not add Contact for MESSAGE, BYE and Cancel requests */
   if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
      add_header(req, "Contact", p->our_contact);

   copy_header(req, orig, "Call-ID");
   add_header(req, "CSeq", tmp);

   if (!ast_strlen_zero(global_useragent))
      add_header(req, "User-Agent", global_useragent);

   if (!ast_strlen_zero(p->rpid))
      add_header(req, "Remote-Party-ID", p->rpid);

   if (!ast_strlen_zero(p->url)) {
      add_header(req, "Access-URL", p->url);
      ast_string_field_set(p, url, NULL);
   }

   /* Add Session-Timers related headers if the feature is active for this session.
      An exception to this behavior is the ACK request. Since Asterisk never requires 
      session-timers support from a remote end-point (UAS) in an INVITE, it must 
      not send 'Require: timer' header in the ACK request. 
      This should only be added in the INVITE transactions, not MESSAGE or REFER or other
      in-dialog messages.
   */
   if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE 
       && sipmethod == SIP_INVITE) {
      char se_hdr[256];
      snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
         strefresher2str(p->stimer->st_ref));
      add_header(req, "Require", "timer");
      add_header(req, "Session-Expires", se_hdr);
      snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
      add_header(req, "Min-SE", se_hdr);
   }

   return 0;
}
static int resp_needs_contact ( const char *  msg,
enum sipmethod  method 
) [inline, static]

Test if this response needs a contact header.

Definition at line 9798 of file chan_sip.c.

References SIP_ACK, SIP_BYE, SIP_CANCEL, SIP_INFO, SIP_INVITE, SIP_MESSAGE, SIP_NOTIFY, SIP_OPTIONS, SIP_PING, SIP_PRACK, SIP_PUBLISH, SIP_REFER, SIP_REGISTER, SIP_SUBSCRIBE, and SIP_UPDATE.

Referenced by respprep().

                                                                             {
   /* Requirements for Contact header inclusion in responses generated
    * from the header tables found in the following RFCs.  Where the
    * Contact header was marked mandatory (m) or optional (o) this
    * function returns 1.
    *
    * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
    * - RFC 2976 (INFO)
    * - RFC 3262 (PRACK)
    * - RFC 3265 (SUBSCRIBE, NOTIFY)
    * - RFC 3311 (UPDATE)
    * - RFC 3428 (MESSAGE)
    * - RFC 3515 (REFER)
    * - RFC 3903 (PUBLISH)
    */

   switch (method) {
      /* 1xx, 2xx, 3xx, 485 */
      case SIP_INVITE:
      case SIP_UPDATE:
      case SIP_SUBSCRIBE:
      case SIP_NOTIFY:
         if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
            return 1;
         break;

      /* 2xx, 3xx, 485 */
      case SIP_REGISTER:
      case SIP_OPTIONS:
         if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
            return 1;
         break;

      /* 3xx, 485 */
      case SIP_BYE:
      case SIP_PRACK:
      case SIP_MESSAGE:
      case SIP_PUBLISH:
         if (msg[0] == '3' || !strncmp(msg, "485", 3))
            return 1;
         break;

      /* 2xx, 3xx, 4xx, 5xx, 6xx */
      case SIP_REFER:
         if (msg[0] >= '2' && msg[0] <= '6')
            return 1;
         break;

      /* contact will not be included for everything else */
      case SIP_ACK:
      case SIP_CANCEL:
      case SIP_INFO:
      case SIP_PING:
      default:
         return 0;
   }
   return 0;
}
static int respprep ( struct sip_request resp,
struct sip_pvt p,
const char *  msg,
const struct sip_request req 
) [static]

Prepare SIP response packet.

Definition at line 9858 of file chan_sip.c.

References add_header(), add_supported_header(), ALLOWED_METHODS, ast_copy_string(), ast_log(), ast_string_field_set, ast_strlen_zero(), ast_test_flag, copy_all_header(), copy_header(), copy_via_headers(), sip_pvt::expiry, sip_pvt::flags, sip_pvt::fullcontact, get_header(), init_resp(), LOG_WARNING, sip_pvt::method, sip_pvt::our_contact, process_via(), sip_pvt::recv, resp_needs_contact(), sip_pvt::sa, SIP_INVITE, SIP_OUTGOING, SIP_REGISTER, SIP_SUBSCRIBE, SIPBUFSIZE, sip_st_dlg::st_active, sip_st_dlg::st_active_peer_ua, sip_st_dlg::st_interval, sip_st_dlg::st_ref, sip_pvt::stimer, strcasestr(), strefresher2str(), sip_pvt::tag, sip_pvt::theirtag, TRUE, url, and sip_pvt::url.

Referenced by __transmit_response(), transmit_response_with_allow(), transmit_response_with_auth(), transmit_response_with_date(), transmit_response_with_minse(), transmit_response_with_sdp(), transmit_response_with_t38_sdp(), and transmit_response_with_unsupported().

{
   char newto[256];
   const char *ot;

   init_resp(resp, msg);
   copy_via_headers(p, resp, req, "Via");
   if (msg[0] == '1' || msg[0] == '2')
      copy_all_header(resp, req, "Record-Route");
   copy_header(resp, req, "From");
   ot = get_header(req, "To");
   if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
      /* Add the proper tag if we don't have it already.  If they have specified
         their tag, use it.  Otherwise, use our own tag */
      if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
      else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
      else
         ast_copy_string(newto, ot, sizeof(newto));
      ot = newto;
   }
   add_header(resp, "To", ot);
   copy_header(resp, req, "Call-ID");
   copy_header(resp, req, "CSeq");
   if (!ast_strlen_zero(global_useragent))
      add_header(resp, "Server", global_useragent);
   add_header(resp, "Allow", ALLOWED_METHODS);
   add_supported_header(p, resp);

   /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
   if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
      char se_hdr[256];
      snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
         strefresher2str(p->stimer->st_ref));
      add_header(resp, "Session-Expires", se_hdr);
   }

   if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
      /* For registration responses, we also need expiry and
         contact info */
      char tmp[256];

      snprintf(tmp, sizeof(tmp), "%d", p->expiry);
      add_header(resp, "Expires", tmp);
      if (p->expiry) {  /* Only add contact if we have an expiry time */
         char contact[SIPBUFSIZE];
         const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
         char *brackets = strchr(contact_uri, '<');
         snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
         add_header(resp, "Contact", contact);  /* Not when we unregister */
      }
   } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
      add_header(resp, "Contact", p->our_contact);
   }

   if (!ast_strlen_zero(p->url)) {
      add_header(resp, "Access-URL", p->url);
      ast_string_field_set(p, url, NULL);
   }

   /* default to routing the response to the address where the request
    * came from.  Since we don't have a transport layer, we do this here.
    */
   p->sa = p->recv;

   if (process_via(p, req)) {
      ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
   }

   return 0;
}
static int restart_monitor ( void  ) [static]

Start the channel monitor thread.

Definition at line 23146 of file chan_sip.c.

References ast_log(), ast_mutex_lock(), ast_mutex_unlock(), ast_pthread_create_background, AST_PTHREADT_NULL, AST_PTHREADT_STOP, do_monitor(), LOG_ERROR, LOG_WARNING, and monlock.

Referenced by load_module(), sip_reload(), and sip_request_call().

{
   /* If we're supposed to be stopped -- stay stopped */
   if (monitor_thread == AST_PTHREADT_STOP)
      return 0;
   ast_mutex_lock(&monlock);
   if (monitor_thread == pthread_self()) {
      ast_mutex_unlock(&monlock);
      ast_log(LOG_WARNING, "Cannot kill myself\n");
      return -1;
   }
   if (monitor_thread != AST_PTHREADT_NULL) {
      /* Wake up the thread */
      pthread_kill(monitor_thread, SIGURG);
   } else {
      /* Start a new monitor */
      if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
         ast_mutex_unlock(&monlock);
         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
         return -1;
      }
   }
   ast_mutex_unlock(&monlock);
   return 0;
}
static void restart_session_timer ( struct sip_pvt p) [static]

Session-Timers: Restart session timer.

Definition at line 23174 of file chan_sip.c.

References ast_debug, ast_log(), AST_SCHED_DEL_UNREF, sip_pvt::callid, dialog_unref(), LOG_WARNING, sip_st_dlg::st_active, sip_st_dlg::st_schedid, start_session_timer(), sip_pvt::stimer, and TRUE.

Referenced by handle_request_invite().

{
   if (!p->stimer) {
      ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
      return;
   }

   if (p->stimer->st_active == TRUE) {
      AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
            dialog_unref(p, "Removing session timer ref"));
      ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
      start_session_timer(p);
   }
}
static int retrans_pkt ( const void *  data) [static]

Retransmit SIP message if no answer (Called from scheduler)

Definition at line 3914 of file chan_sip.c.

References __sip_xmit(), append_history, AST_CAUSE_NO_USER_RESPONSE, AST_CAUSE_PROTOCOL_ERROR, ast_channel_trylock, ast_channel_unlock, ast_debug, ast_free, ast_inet_ntoa(), ast_log(), ast_queue_hangup_with_cause(), ast_verbose(), sip_pvt::callid, sip_pkt::data, DEFAULT_RETRANS, dialog_unref(), ast_channel::hangupcause, sip_pkt::is_fatal, sip_pkt::is_resp, LOG_WARNING, MAX_RETRANS, sip_pkt::method, sip_pkt::next, sip_pvt::owner, sip_pkt::owner, sip_pkt::packetlen, sip_pvt::packets, pvt_set_needdestroy(), sip_pkt::retrans, sip_pkt::retransid, sip_pkt::seqno, sip_alreadygone(), SIP_BYE, sip_debug_test_pvt(), SIP_INVITE, sip_methods, sip_nat_mode(), SIP_OPTIONS, sip_pvt_lock, sip_pvt_unlock, sip_real_dst(), SIP_REGISTER, cfsip_methods::text, sip_pkt::timer_a, sip_pkt::timer_t1, UNLINK, and XMIT_ERROR.

Referenced by __sip_reliable_xmit(), and sip_show_sched().

{
   struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
   int reschedule = DEFAULT_RETRANS;
   int xmitres = 0;

   /* Lock channel PVT */
   sip_pvt_lock(pkt->owner);

   if (pkt->retrans < MAX_RETRANS) {
      pkt->retrans++;
      if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
         if (sipdebug)
            ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
      } else {
         int siptimer_a;

         if (sipdebug)
            ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
         if (!pkt->timer_a)
            pkt->timer_a = 2 ;
         else
            pkt->timer_a = 2 * pkt->timer_a;

         /* For non-invites, a maximum of 4 secs */
         siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
         if (pkt->method != SIP_INVITE && siptimer_a > 4000)
            siptimer_a = 4000;

         /* Reschedule re-transmit */
         reschedule = siptimer_a;
         ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
      }

      if (sip_debug_test_pvt(pkt->owner)) {
         const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
         ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
            pkt->retrans, sip_nat_mode(pkt->owner),
            ast_inet_ntoa(dst->sin_addr),
            ntohs(dst->sin_port), pkt->data->str);
      }

      append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
      xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
      if (xmitres == XMIT_ERROR) {
         ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
      } else {
         sip_pvt_unlock(pkt->owner);
         return  reschedule;
      }
   }
   /* Too many retries */
   if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
      if (pkt->is_fatal || sipdebug)   /* Tell us if it's critical or if we're debugging */
         ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions \n",
            pkt->owner->callid, pkt->seqno,
            pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
   } else if (pkt->method == SIP_OPTIONS && sipdebug) {
         ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions \n", pkt->owner->callid);

   }
   if (xmitres == XMIT_ERROR) {
      ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
      append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
   } else {
      append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
   }
   pkt->retransid = -1;

   if (pkt->is_fatal) {
      while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
         sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
         usleep(1);
         sip_pvt_lock(pkt->owner);
      }

      if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
         pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;

      if (pkt->owner->owner) {
         sip_alreadygone(pkt->owner);
         ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions ).\n", pkt->owner->callid);
         ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
         ast_channel_unlock(pkt->owner->owner);
      } else {
         /* If no channel owner, destroy now */

         /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
         if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
            pvt_set_needdestroy(pkt->owner, "no response to critical packet");
            sip_alreadygone(pkt->owner);
            append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
         }
      }
   }

   if (pkt->method == SIP_BYE) {
      /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
      sip_alreadygone(pkt->owner);
      if (pkt->owner->owner)
         ast_channel_unlock(pkt->owner->owner);
      append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
      pvt_set_needdestroy(pkt->owner, "no response to BYE");
   }

   /* Remove the packet */
   for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
      if (cur == pkt) {
         UNLINK(cur, pkt->owner->packets, prev);
         sip_pvt_unlock(pkt->owner);
         if (pkt->owner)
            pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
         if (pkt->data)
            ast_free(pkt->data);
         pkt->data = NULL;
         ast_free(pkt);
         return 0;
      }
   }
   /* error case */
   ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
   sip_pvt_unlock(pkt->owner);
   return 0;
}
static int scheduler_process_request_queue ( const void *  data) [static]

Definition at line 22448 of file chan_sip.c.

References ast_channel_trylock, ast_channel_unlock, AST_LIST_EMPTY, ast_update_use_count(), dialog_unref(), sip_pvt::owner, process_request_queue(), sip_pvt::request_queue, sip_pvt::request_queue_sched_id, sip_pvt_lock, and sip_pvt_unlock.

Referenced by queue_request().

{
   struct sip_pvt *p = (struct sip_pvt *) data;
   int recount = 0;
   int nounlock = 0;
   int lockretry;

   for (lockretry = 10; lockretry > 0; lockretry--) {
      sip_pvt_lock(p);

      /* lock the owner if it has one -- we may need it */
      /* because this is deadlock-prone, we need to try and unlock if failed */
      if (!p->owner || !ast_channel_trylock(p->owner)) {
         break;   /* locking succeeded */
      }

      if (lockretry != 1) {
         sip_pvt_unlock(p);
         /* Sleep for a very short amount of time */
         usleep(1);
      }
   }

   if (!lockretry) {
      int retry = !AST_LIST_EMPTY(&p->request_queue);

      /* we couldn't get the owner lock, which is needed to process
         the queued requests, so return a non-zero value, which will
         cause the scheduler to run this request again later if there
         still requests to be processed
      */
      sip_pvt_unlock(p);
      if (!retry) {
         dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
      }
      return retry;
   };

   process_request_queue(p, &recount, &nounlock);
   p->request_queue_sched_id = -1;

   if (p->owner && !nounlock) {
      ast_channel_unlock(p->owner);
   }
   sip_pvt_unlock(p);

   if (recount) {
      ast_update_use_count();
   }

   dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");

   return 0;
}
static int send_provisional_keepalive ( const void *  data) [static]

Definition at line 4377 of file chan_sip.c.

References send_provisional_keepalive_full().

Referenced by update_provisional_keepalive().

                                                        {
   struct sip_pvt *pvt = (struct sip_pvt *) data;

   return send_provisional_keepalive_full(pvt, 0);
}
static int send_provisional_keepalive_full ( struct sip_pvt pvt,
int  with_sdp 
) [static]

Definition at line 4357 of file chan_sip.c.

References FALSE, sip_pvt::initreq, INV_COMPLETED, sip_pvt::invitestate, sip_pvt::last_provisional, msg, PROVIS_KEEPALIVE_TIMEOUT, S_OR, transmit_response(), transmit_response_with_sdp(), and XMIT_UNRELIABLE.

Referenced by send_provisional_keepalive(), and send_provisional_keepalive_with_sdp().

{
   const char *msg = NULL;

   if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
      msg = "183 Session Progress";
   }

   if (pvt->invitestate < INV_COMPLETED) {
      if (with_sdp) {
         transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
      } else {
         transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
      }
      return PROVIS_KEEPALIVE_TIMEOUT;
   }

   return 0;
}
static int send_provisional_keepalive_with_sdp ( const void *  data) [static]

Definition at line 4383 of file chan_sip.c.

References send_provisional_keepalive_full().

Referenced by update_provisional_keepalive().

                                                                 {
   struct sip_pvt *pvt = (void *)data;

   return send_provisional_keepalive_full(pvt, 1);
}
static int send_request ( struct sip_pvt p,
struct sip_request req,
enum xmittype  reliable,
int  seqno 
) [static]

Send SIP Request to the other part of the dialogue.

Definition at line 4435 of file chan_sip.c.

References __sip_reliable_xmit(), __sip_xmit(), add_blank(), append_history, ast_inet_ntoa(), ast_test_flag, ast_verbose(), sip_request::data, deinit_req(), sip_pvt::do_history, finalize_content(), sip_pvt::flags, get_header(), sip_proxy::ip, sip_request::len, sip_request::method, sip_pvt::outboundproxy, parse_copy(), sip_pvt::recv, sip_request::rlPart1, sip_pvt::sa, sip_debug_test_pvt(), sip_methods, SIP_NAT_ROUTE, cfsip_methods::text, and XMIT_CRITICAL.

Referenced by transmit_info_with_digit(), transmit_info_with_vidupdate(), transmit_invite(), transmit_message_with_text(), transmit_notify_custom(), transmit_notify_with_mwi(), transmit_notify_with_sipfrag(), transmit_refer(), transmit_register(), transmit_reinvite_with_sdp(), transmit_request(), transmit_request_with_auth(), and transmit_state_notify().

{
   int res;

   /* If we have an outbound proxy, reset peer address 
      Only do this once.
   */
   if (p->outboundproxy) {
      p->sa = p->outboundproxy->ip;
   }

   finalize_content(req);
   add_blank(req);
   if (sip_debug_test_pvt(p)) {
      if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
         ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data->str);
      else
         ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data->str);
   }
   if (p->do_history) {
      struct sip_request tmp = { .rlPart1 = 0, };
      parse_copy(&tmp, req);
      append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
      deinit_req(&tmp);
   }
   res = (reliable) ?
      __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
      __sip_xmit(p, req->data, req->len);
   deinit_req(req);
   return res;
}
static int send_response ( struct sip_pvt p,
struct sip_request req,
enum xmittype  reliable,
int  seqno 
) [static]

Transmit response on SIP request.

Definition at line 4398 of file chan_sip.c.

References __sip_reliable_xmit(), __sip_xmit(), add_blank(), append_history, ast_inet_ntoa(), AST_SCHED_DEL_UNREF, ast_verbose(), sip_request::data, deinit_req(), dialog_unref(), sip_pvt::do_history, finalize_content(), get_header(), sip_pvt::initreq, sip_request::len, sip_request::method, parse_copy(), sip_pvt::provisional_keepalive_sched_id, REQ_OFFSET_TO_STR, sip_request::rlPart1, sip_request::rlPart2, sip_debug_test_pvt(), SIP_INVITE, sip_methods, sip_nat_mode(), sip_real_dst(), SIP_RESPONSE, SIP_UNKNOWN, cfsip_methods::text, and XMIT_CRITICAL.

Referenced by __transmit_response(), transmit_response_with_allow(), transmit_response_with_auth(), transmit_response_with_date(), transmit_response_with_minse(), transmit_response_with_sdp(), transmit_response_with_t38_sdp(), and transmit_response_with_unsupported().

{
   int res;

   finalize_content(req);
   add_blank(req);
   if (sip_debug_test_pvt(p)) {
      const struct sockaddr_in *dst = sip_real_dst(p);

      ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
         reliable ? "Reliably " : "", sip_nat_mode(p),
         ast_inet_ntoa(dst->sin_addr),
         ntohs(dst->sin_port), req->data->str);
   }
   if (p->do_history) {
      struct sip_request tmp = { .rlPart1 = 0, };
      parse_copy(&tmp, req);
      append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), 
         (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
      deinit_req(&tmp);
   }

   /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
   if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
      AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
   }

   res = (reliable) ?
       __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
      __sip_xmit(p, req->data, req->len);
   deinit_req(req);
   if (res > 0)
      return 0;
   return res;
}
static int set_address_from_contact ( struct sip_pvt pvt) [static]

Change the other partys IP address based on given contact.

Todo:
We need to save the TRANSPORT here too

Definition at line 12714 of file chan_sip.c.

References __set_address_from_contact(), ast_test_flag, sip_pvt::flags, sip_pvt::fullcontact, sip_pvt::recv, sip_pvt::sa, SIP_NAT_ROUTE, SIP_TRANSPORT_TLS, sip_pvt::socket, and sip_socket::type.

Referenced by handle_response_invite().

{
   if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
      /* NAT: Don't trust the contact field.  Just use what they came to us
         with. */
      /*! \todo We need to save the TRANSPORT here too */
      pvt->sa = pvt->recv;
      return 0;
   }

   return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
}
static void set_destination ( struct sip_pvt p,
char *  uri 
) [static]

Set destination from SIP URI.

Parse uri to h (host) and port - uri is already just the part inside the <> general form we are expecting is sip[s]:username[:password][;parameter][:port][;...] If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even for SIP: uri's

If there's a sips: uri scheme, TLS will be required.

Todo:
XXX If we have use_dns on, then look for NAPTR/SRV, otherwise, just look for A records

Definition at line 9671 of file chan_sip.c.

References ast_copy_string(), ast_gethostbyname(), ast_inet_ntoa(), ast_log(), ast_verbose(), sip_request::debug, FALSE, hostname, hp, LOG_WARNING, sip_pvt::sa, sip_cfg, sip_debug_test_pvt(), sip_settings::srvlookup, STANDARD_SIP_PORT, STANDARD_TLS_PORT, and TRUE.

Referenced by reqprep().

{
   char *h, *maddr, hostname[256];
   int port, hn;
   struct hostent *hp;
   struct ast_hostent ahp;
   int debug=sip_debug_test_pvt(p);
   int tls_on = FALSE;
   int use_dns = sip_cfg.srvlookup;

   if (debug)
      ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);

   /* Find and parse hostname */
   h = strchr(uri, '@');
   if (h)
      ++h;
   else {
      h = uri;
      if (!strncasecmp(h, "sip:", 4)) {
         h += 4;
      } else if (!strncasecmp(h, "sips:", 5)) {
         h += 5;
         tls_on = TRUE;
      }
   }
   hn = strcspn(h, ":;>") + 1;
   if (hn > sizeof(hostname)) 
      hn = sizeof(hostname);
   ast_copy_string(hostname, h, hn);
   /* XXX bug here if string has been trimmed to sizeof(hostname) */
   h += hn - 1;

   /* Is "port" present? if not default to STANDARD_SIP_PORT */
   if (*h == ':') {
      /* Parse port */
      ++h;
      port = strtol(h, &h, 10);
      use_dns = FALSE;
   } else
      port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;

   /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
   maddr = strstr(h, "maddr=");
   if (maddr) {
      maddr += 6;
      hn = strspn(maddr, "0123456789.") + 1;
      if (hn > sizeof(hostname))
         hn = sizeof(hostname);
      ast_copy_string(hostname, maddr, hn);
   }

   /*! \todo XXX If we have use_dns on, then look for NAPTR/SRV, otherwise, just look for A records */
   
   hp = ast_gethostbyname(hostname, &ahp);
   if (hp == NULL)  {
      ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
      return;
   }
   p->sa.sin_family = AF_INET;
   memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
   p->sa.sin_port = htons(port);
   if (debug)
      ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
}
static void set_insecure_flags ( struct ast_flags flags,
const char *  value,
int  lineno 
) [static]

Parse insecure= setting in sip.conf and set flags according to setting.

Definition at line 23897 of file chan_sip.c.

References ast_copy_string(), ast_false(), ast_log(), ast_set_flag, ast_strlen_zero(), buf, LOG_WARNING, sip_request::next, SIP_INSECURE_INVITE, SIP_INSECURE_PORT, strsep(), and word.

Referenced by get_insecure_variable_from_config(), and handle_common_options().

{
   if (ast_strlen_zero(value))
      return;

   if (!ast_false(value)) {
      char buf[64];
      char *word, *next;

      ast_copy_string(buf, value, sizeof(buf));
      next = buf;
      while ((word = strsep(&next, ","))) {
         if (!strcasecmp(word, "port"))
            ast_set_flag(&flags[0], SIP_INSECURE_PORT);
         else if (!strcasecmp(word, "invite"))
            ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
         else
            ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
      }
   }
}
static void set_nonce_randdata ( struct sip_pvt p,
int  forceupdate 
) [static]

builds the sip_pvt's randdata field which is used for the nonce challenge. When forceupdate is not set, the nonce is only updated if the current one is stale. In this case, a stalenonce is one which has already received a response, if a nonce has not received a response it is not always necessary or beneficial to create a new one.

Definition at line 13087 of file chan_sip.c.

References ast_random(), ast_string_field_build, ast_strlen_zero(), sip_pvt::randdata, and sip_pvt::stalenonce.

Referenced by check_auth(), and transmit_fake_auth_response().

{
   if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
      ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
      p->stalenonce = 0;
   }
}
static void set_peer_defaults ( struct sip_peer peer) [static]

Set peer defaults before configuring specific configurations.

Definition at line 24269 of file chan_sip.c.

References sip_peer::addr, sip_settings::allowtransfer, sip_peer::allowtransfer, ast_copy_flags, ast_string_field_set, sip_peer::autoframing, sip_peer::call_limit, sip_peer::callgroup, sip_peer::capability, cid_name, cid_num, clear_peer_mailboxes(), context, sip_peer::defaddr, sip_settings::default_context, default_maxcallbitrate, sip_peer::default_outbound_transport, default_prefs, default_primary_transport, default_qualify, sip_settings::default_subscribecontext, default_transports, sip_peer::expire, sip_peer::flags, global_autoframing, global_capability, global_max_se, global_min_se, global_qualifyfreq, global_rtpholdtimeout, global_rtpkeepalive, global_rtptimeout, global_st_mode, global_st_refresher, global_t1, global_t38_maxdatagram, global_timer_b, language, sip_peer::maxcallbitrate, sip_peer::maxms, mohinterpret, mohsuggest, sip_peer::pickupgroup, sip_peer::pokeexpire, sip_peer::prefs, sip_peer::qualifyfreq, sip_peer::rtpholdtimeout, sip_peer::rtpkeepalive, sip_peer::rtptimeout, secret, set_socket_transport(), sip_cfg, SIP_FLAGS_TO_COPY, SIP_PAGE2_FLAGS_TO_COPY, SIP_TRANSPORT_UDP, SIP_TYPE_PEER, sip_peer::socket, sip_st_cfg::st_max_se, sip_st_cfg::st_min_se, sip_st_cfg::st_mode_oper, sip_st_cfg::st_ref, STANDARD_SIP_PORT, sip_peer::stimer, sip_peer::t38_maxdatagram, sip_peer::timer_b, sip_peer::timer_t1, sip_peer::transports, and sip_peer::type.

Referenced by build_peer(), and temp_peer().

{
   if (peer->expire == 0) {
      /* Don't reset expire or port time during reload 
         if we have an active registration 
      */
      peer->expire = -1;
      peer->pokeexpire = -1;
      peer->addr.sin_port = htons(STANDARD_SIP_PORT);
      set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
   }
   peer->type = SIP_TYPE_PEER;
   ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
   ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
   ast_string_field_set(peer, context, sip_cfg.default_context);
   ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
   ast_string_field_set(peer, language, default_language);
   ast_string_field_set(peer, mohinterpret, default_mohinterpret);
   ast_string_field_set(peer, mohsuggest, default_mohsuggest);
   peer->addr.sin_family = AF_INET;
   peer->defaddr.sin_family = AF_INET;
   peer->capability = global_capability;
   peer->maxcallbitrate = default_maxcallbitrate;
   peer->rtptimeout = global_rtptimeout;
   peer->rtpholdtimeout = global_rtpholdtimeout;
   peer->rtpkeepalive = global_rtpkeepalive;
   peer->allowtransfer = sip_cfg.allowtransfer;
   peer->autoframing = global_autoframing;
   peer->t38_maxdatagram = global_t38_maxdatagram;
   peer->qualifyfreq = global_qualifyfreq;
   if (global_callcounter)
      peer->call_limit=INT_MAX;
   ast_string_field_set(peer, vmexten, default_vmexten);
   ast_string_field_set(peer, secret, "");
   ast_string_field_set(peer, remotesecret, "");
   ast_string_field_set(peer, md5secret, "");
   ast_string_field_set(peer, cid_num, "");
   ast_string_field_set(peer, cid_name, "");
   ast_string_field_set(peer, fromdomain, "");
   ast_string_field_set(peer, fromuser, "");
   ast_string_field_set(peer, regexten, "");
   peer->callgroup = 0;
   peer->pickupgroup = 0;
   peer->maxms = default_qualify;
   peer->prefs = default_prefs;
   peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
   peer->stimer.st_ref = global_st_refresher;
   peer->stimer.st_min_se = global_min_se;
   peer->stimer.st_max_se = global_max_se;
   peer->timer_t1 = global_t1;
   peer->timer_b = global_timer_b;
   clear_peer_mailboxes(peer);
   peer->transports = default_transports;
   peer->default_outbound_transport = default_primary_transport;
}
static void set_socket_transport ( struct sip_socket socket,
int  transport 
) [static]

Definition at line 12499 of file chan_sip.c.

References ao2_ref, sip_socket::fd, sip_socket::tcptls_session, and sip_socket::type.

Referenced by __sip_subscribe_mwi_do(), _sip_tcp_helper_thread(), build_peer(), create_addr(), expire_register(), get_transport_pvt(), parse_moved_contact(), parse_register_contact(), set_peer_defaults(), sip_alloc(), sip_request_call(), sip_send_mwi_to_peer(), sipsock_read(), and transmit_register().

{
   /* if the transport type changes, clear all socket data */
   if (socket->type != transport) {
      socket->fd = -1;
      socket->type = transport;
      if (socket->tcptls_session) {
         ao2_ref(socket->tcptls_session, -1);
         socket->tcptls_session = NULL;
      }
   }
}
static int show_channels_cb ( void *  __cur,
void *  __arg,
int  flags 
) [static]

callback for show channel|subscription

Definition at line 16766 of file chan_sip.c.

References ast_cli(), ast_extension_state2str(), ast_getformatname_multiple(), ast_inet_ntoa(), ast_str_alloca, ast_test_flag, sip_pvt::callid, sip_pvt::cid_num, cli_yesno(), sip_pvt::expiry, __show_chan_arg::fd, sip_pvt::flags, FORMAT, FORMAT4, sip_pvt::lastmsg, sip_pvt::laststate, MWI_NOTIFICATION, ast_channel::nativeformats, sip_pvt::needdestroy, NONE, __show_chan_arg::numchans, sip_pvt::owner, peer_mailboxes_to_str(), sip_pvt::refer, referstatus2str(), sip_pvt::relatedpeer, S_OR, SIP_PAGE2_CALL_ONHOLD, sip_real_dst(), SIPBUFSIZE, sip_refer::status, sip_pvt::subscribed, sip_pvt::subscribeuri, subscription_type2str(), __show_chan_arg::subscriptions, and sip_pvt::username.

Referenced by sip_show_channels().

{
   struct sip_pvt *cur = __cur;
   struct __show_chan_arg *arg = __arg;
   const struct sockaddr_in *dst = sip_real_dst(cur);
   
   /* XXX indentation preserved to reduce diff. Will be fixed later */
   if (cur->subscribed == NONE && !arg->subscriptions) {
      /* set if SIP transfer in progress */
      const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
      char formatbuf[SIPBUFSIZE/2];
      
      ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr), 
            S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
            cur->callid, 
            ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
            cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
            cur->needdestroy ? "(d)" : "",
            cur->lastmsg ,
            referstatus
         );
      arg->numchans++;
   }
   if (cur->subscribed != NONE && arg->subscriptions) {
      struct ast_str *mailbox_str = ast_str_alloca(512);
      if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
         peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
      ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
            S_OR(cur->username, S_OR(cur->cid_num, "(None)")), 
               cur->callid,
            /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
            cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
            cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate), 
            subscription_type2str(cur->subscribed),
            cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
            cur->expiry
         );
      arg->numchans++;
   }
   return 0;   /* don't care, we scan all channels */
}
static int show_chanstats_cb ( void *  __cur,
void *  __arg,
int  flags 
) [static]

Callback for show_chanstats.

Definition at line 16409 of file chan_sip.c.

References ast_cli(), ast_inet_ntoa(), ast_rtp_get_qosvalue(), AST_RTP_RXCOUNT, AST_RTP_RXJITTER, AST_RTP_RXPLOSS, AST_RTP_TXCOUNT, AST_RTP_TXJITTER, AST_RTP_TXPLOSS, ast_tvdiff_ms(), ast_tvnow(), ast_tvzero(), sip_pvt::callid, ast_channel::cdr, invstate2stringtable::desc, __show_chan_arg::fd, FORMAT, sip_pvt::invitestate, invitestate2string, NONE, __show_chan_arg::numchans, sip_pvt::owner, sip_pvt::rtp, sip_pvt::sa, ast_cdr::start, and sip_pvt::subscribed.

Referenced by sip_show_channelstats().

{
#define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
#define FORMAT  "%-15.15s  %-11.11s  %-8.8s %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.6u %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.6u\n"
   struct sip_pvt *cur = __cur;
   unsigned int rxcount, txcount, rxploss, txploss;
   char durbuf[10];
        int duration;
        int durh, durm, durs;
   struct ast_channel *c = cur->owner;
   struct __show_chan_arg *arg = __arg;
   int fd = arg->fd;


   if (cur->subscribed != NONE) /* Subscriptions */
      return 0;   /* don't care, we scan all channels */

   if (!cur->rtp) {
      if (sipdebug)
         ast_cli(fd, "%-15.15s  %-11.11s (inv state: %s) -- %s\n", ast_inet_ntoa(cur->sa.sin_addr), cur->callid, invitestate2string[cur->invitestate].desc, "-- No RTP active");
      return 0;   /* don't care, we scan all channels */
   }
   rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
   txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
   rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
   txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);

   /* Find the duration of this channel */
   if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
      duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
      durh = duration / 3600;
      durm = (duration % 3600) / 60;
      durs = duration % 60;
      snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
   } else {
      durbuf[0] = '\0';
   }
   /* Print stats for every call with RTP */
   ast_cli(fd, FORMAT, 
      ast_inet_ntoa(cur->sa.sin_addr), 
      cur->callid, 
      durbuf,
      rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
      rxcount > (unsigned int) 100000 ? "K":" ",
      rxploss,
      (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
      ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
      txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
      txcount > (unsigned int) 100000 ? "K":" ",
      txploss,
      txcount > 0 ? (double) txploss / txcount * 100 : 0,
      ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
   );
   arg->numchans++;

   return 0;   /* don't care, we scan all channels */
}
static int sip_addheader ( struct ast_channel chan,
void *  data 
) [static]

Add a SIP header to an outbound INVITE.

Definition at line 26160 of file chan_sip.c.

References ast_channel_lock, ast_channel_unlock, ast_debug, ast_get_encoded_str(), ast_log(), ast_strlen_zero(), sip_request::data, FALSE, inbuf(), LOG_WARNING, pbx_builtin_getvar_helper(), pbx_builtin_setvar_helper(), and TRUE.

Referenced by load_module().

{
   int no = 0;
   int ok = FALSE;
   char varbuf[30];
   char *inbuf = data, *subbuf;
   
   if (ast_strlen_zero(inbuf)) {
      ast_log(LOG_WARNING, "This application requires the argument: Header\n");
      return 0;
   }
   ast_channel_lock(chan);

   /* Check for headers */
   while (!ok && no <= 50) {
      no++;
      snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);

      /* Compare without the leading underscores */
      if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
         ok = TRUE;
      }
   }
   if (ok) {
      size_t len = strlen(inbuf);
      subbuf = alloca(len + 1);
      ast_get_encoded_str(inbuf, subbuf, len + 1);
      pbx_builtin_setvar_helper(chan, varbuf, subbuf);
      if (sipdebug) {
         ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
      }
   } else {
      ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
   }
   ast_channel_unlock(chan);
   return 0;
}
static struct sip_pvt * sip_alloc ( ast_string_field  callid,
struct sockaddr_in *  sin,
int  useglobal_nat,
const int  intended_method,
struct sip_request req 
) [static, read]

Allocate sip_pvt structure, set defaults and link in the container. Returns a reference to the object so whoever uses it later must remember to release the reference.

Definition at line 7396 of file chan_sip.c.

References sip_settings::allowtransfer, sip_pvt::allowtransfer, ao2_t_alloc, ao2_t_link, ao2_t_ref, ast_clear_flag, ast_copy_flags, ast_debug, AST_LIST_HEAD_INIT_NOLOCK, ast_log(), ast_random(), ast_rtp_codec_setpref(), AST_RTP_DTMF, ast_rtp_new_with_bindaddr(), ast_rtp_set_rtpholdtimeout(), ast_rtp_set_rtpkeepalive(), ast_rtp_set_rtptimeout(), ast_rtp_setdtmf(), ast_rtp_setdtmfcompensate(), ast_rtp_setqos(), ast_sip_ouraddrfor(), ast_string_field_init, ast_string_field_set, ast_test_flag, ast_udptl_new_with_bindaddr(), ast_udptl_setqos(), ast_variables_destroy(), sip_pvt::autoframing, sip_pvt::autokillid, bindaddr, sip_pvt::branch, build_callid_pvt(), build_via(), sip_pvt::callid, sip_pvt::capability, sip_pvt::chanvars, context, sip_settings::default_context, default_maxcallbitrate, default_prefs, sip_pvt::do_history, do_setnat(), errno, sip_socket::fd, sip_pvt::flags, sip_pvt::fromdomain, global_autoframing, global_capability, global_t1, global_t38_maxdatagram, global_timer_b, INITIAL_CSEQ, sip_pvt::initid, internip, LOG_ERROR, LOG_WARNING, make_our_tag(), sip_pvt::maxcallbitrate, sip_pvt::method, mohinterpret, mohsuggest, sip_pvt::noncodeccapability, NONE, sip_pvt::ocseq, sip_pvt::ourip, parkinglot, sip_pvt::prefs, sip_pvt::provisional_keepalive_sched_id, recordhistory, sip_pvt::recv, sip_pvt::request_queue, sip_pvt::request_queue_sched_id, sip_pvt::rtp, sip_pvt::sa, sip_pvt::session_modify, sip_pvt::sessionversion_remote, set_socket_transport(), set_t38_capabilities(), sip_cfg, sip_destroy_fn(), SIP_DTMF, SIP_DTMF_AUTO, SIP_DTMF_RFC2833, SIP_FLAGS_TO_COPY, sip_methods, SIP_NAT, SIP_NAT_ROUTE, SIP_OPTIONS, SIP_PAGE2_FLAGS_TO_COPY, SIP_PAGE2_RFC2833_COMPENSATE, SIP_PAGE2_T38SUPPORT, SIP_PAGE2_TEXTSUPPORT, SIP_PAGE2_VIDEOSUPPORT, SIP_PAGE2_VIDEOSUPPORT_ALWAYS, SIP_REGISTER, SIP_TRANSPORT_UDP, sip_request::socket, sip_pvt::socket, sip_pvt::stateid, sip_pvt::stimer, sip_pvt::subscribed, sip_pvt::t38_maxdatagram, sip_pvt::t38id, sip_pvt::tag, cfsip_methods::text, sip_pvt::timer_b, sip_pvt::timer_t1, sip_pvt::trtp, TRUE, sip_socket::type, sip_pvt::udptl, sip_pvt::vrtp, and sip_pvt::waitid.

Referenced by __sip_subscribe_mwi_do(), find_call(), manager_sipnotify(), sip_cli_notify(), sip_poke_peer(), sip_request_call(), sip_send_mwi_to_peer(), and transmit_register().

{
   struct sip_pvt *p;

   if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
      return NULL;

   if (ast_string_field_init(p, 512)) {
      ao2_t_ref(p, -1, "failed to string_field_init, drop p");
      return NULL;
   }

   if (req) {
      set_socket_transport(&p->socket, req->socket.type); /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
   } else {
      set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
   }

   p->socket.fd = -1;
   p->method = intended_method;
   p->initid = -1;
   p->waitid = -1;
   p->autokillid = -1;
   p->request_queue_sched_id = -1;
   p->provisional_keepalive_sched_id = -1;
   p->t38id = -1;
   p->subscribed = NONE;
   p->stateid = -1;
   p->sessionversion_remote = -1;
   p->session_modify = TRUE;
   p->stimer = NULL;
   p->prefs = default_prefs;     /* Set default codecs for this call */

   if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
      p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
      p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
   }

   if (!sin)
      p->ourip = internip;
   else {
      p->sa = *sin;
      ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
   }

   /* Copy global flags to this PVT at setup. */
   ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
   ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);

   p->do_history = recordhistory;

   p->branch = ast_random();  
   make_our_tag(p->tag, sizeof(p->tag));
   p->ocseq = INITIAL_CSEQ;

   if (sip_methods[intended_method].need_rtp) {
      p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
      /* If the global videosupport flag is on, we always create a RTP interface for video */
      if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
            ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS))
         p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
      if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
         p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
      if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
         if (!(p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
            /* udptl creation failed, T38 can not be supported on this dialog */
            ast_log(LOG_ERROR, "UDPTL creation failed\n");
            ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
         }
      }
      if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp) 
            || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
         ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
            ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
            ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
         if (p->chanvars) {
            ast_variables_destroy(p->chanvars);
            p->chanvars = NULL;
         }
         ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
         return NULL;
         p->t38_maxdatagram = global_t38_maxdatagram;
      }
      ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
      ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
      ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
      ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
      ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
      ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
      if (p->vrtp) {
         ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
         ast_rtp_setdtmf(p->vrtp, 0);
         ast_rtp_setdtmfcompensate(p->vrtp, 0);
         ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
         ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
         ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
      }
      if (p->trtp) {
         ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
         ast_rtp_setdtmf(p->trtp, 0);
         ast_rtp_setdtmfcompensate(p->trtp, 0);
      }
      if (p->udptl)
         ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
      p->maxcallbitrate = default_maxcallbitrate;
      p->autoframing = global_autoframing;
      ast_rtp_codec_setpref(p->rtp, &p->prefs);
   }

   if (useglobal_nat && sin) {
      /* Setup NAT structure according to global settings if we have an address */
      ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
      p->recv = *sin;
      do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
   }

   if (p->method != SIP_REGISTER)
      ast_string_field_set(p, fromdomain, default_fromdomain);
   build_via(p);
   if (!callid)
      build_callid_pvt(p);
   else
      ast_string_field_set(p, callid, callid);
   /* Assign default music on hold class */
   ast_string_field_set(p, mohinterpret, default_mohinterpret);
   ast_string_field_set(p, mohsuggest, default_mohsuggest);
   p->capability = global_capability;
   p->allowtransfer = sip_cfg.allowtransfer;
   if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
       (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
      p->noncodeccapability |= AST_RTP_DTMF;
   if (p->udptl) {
      p->t38_maxdatagram = global_t38_maxdatagram;
      set_t38_capabilities(p);
   }
   ast_string_field_set(p, context, sip_cfg.default_context);
   ast_string_field_set(p, parkinglot, default_parkinglot);

   AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);

   /* Add to active dialog list */

   ao2_t_link(dialogs, p, "link pvt into dialogs table");
   
   ast_debug(1, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : p->callid, sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
   return p;
}
static void sip_alreadygone ( struct sip_pvt dialog) [static]

Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging.

Definition at line 3439 of file chan_sip.c.

References sip_pvt::alreadygone, ast_debug, and sip_pvt::callid.

Referenced by handle_request_bye(), handle_request_cancel(), handle_request_invite(), handle_request_refer(), handle_response(), handle_response_invite(), handle_response_subscribe(), retrans_pkt(), sip_indicate(), and sip_sipredirect().

{
   ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
   dialog->alreadygone = 1;
}
static int sip_answer ( struct ast_channel ast) [static]
static int sip_call ( struct ast_channel ast,
char *  dest,
int  timeout 
) [static]

Initiate SIP call from PBX used from the dial() application.

Definition at line 5584 of file chan_sip.c.

References ast_channel::_state, sip_invite_param::addsipheaders, AST_CAUSE_USER_BUSY, ast_clear_flag, ast_debug, AST_FORMAT_AUDIO_MASK, AST_LIST_TRAVERSE, ast_log(), AST_SCHED_REPLACE_UNREF, ast_set_flag, AST_STATE_DOWN, AST_STATE_RESERVED, ast_string_field_set, ast_translate_available_formats(), ast_var_name(), ast_var_value(), auto_congest(), buf, sip_pvt::callingpres, sip_pvt::capability, ast_channel::cid, cid_name, sip_pvt::cid_name, ast_callerid::cid_pres, dialog_ref(), dialog_unref(), ast_var_t::entries, sip_pvt::flags, ast_channel::hangupcause, INC_CALL_RINGING, sip_pvt::initid, INV_CALLING, sip_pvt::invitestate, sip_pvt::jointcapability, sip_pvt::jointnoncodeccapability, LOG_WARNING, ast_channel::name, sip_pvt::noncodeccapability, sip_pvt::options, sip_pvt::prefcodec, sip_invite_param::replaces, SIP_INVITE, SIP_OUTGOING, SIP_PAGE2_FAX_DETECT_T38, SIPBUFSIZE, ast_channel::tech_pvt, sip_pvt::timer_b, sip_invite_param::transfer, transmit_invite(), update_call_counter(), sip_invite_param::uri_options, sip_pvt::username, ast_channel::varshead, sip_invite_param::vxml_url, and XMIT_ERROR.

{
   int res;
   struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
   struct varshead *headp;
   struct ast_var_t *current;
   const char *referer = NULL;   /* SIP referrer */

   if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
      ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
      return -1;
   }

   /* Check whether there is vxml_url, distinctive ring variables */
   headp=&ast->varshead;
   AST_LIST_TRAVERSE(headp, current, entries) {
      /* Check whether there is a VXML_URL variable */
      if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
         p->options->vxml_url = ast_var_value(current);
      } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
         p->options->uri_options = ast_var_value(current);
      } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
         /* Check whether there is a variable with a name starting with SIPADDHEADER */
         p->options->addsipheaders = 1;
      } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
         ast_string_field_set(p, fromdomain, ast_var_value(current));
      } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
         /* This is a transfered call */
         p->options->transfer = 1;
      } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
         /* This is the referrer */
         referer = ast_var_value(current);
      } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
         /* We're replacing a call. */
         p->options->replaces = ast_var_value(current);
      }
   }

   res = 0;
   ast_set_flag(&p->flags[0], SIP_OUTGOING);

   /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
    * so ensure it is disabled.
    */
   ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);

   if (p->options->transfer) {
      char buf[SIPBUFSIZE/2];

      if (referer) {
         if (sipdebug)
            ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
         snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
      } else 
         snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
      ast_string_field_set(p, cid_name, buf);
   } 
   ast_debug(1, "Outgoing Call for %s\n", p->username);

   res = update_call_counter(p, INC_CALL_RINGING);

   if (res == -1) {
      ast->hangupcause = AST_CAUSE_USER_BUSY;
      return res;
   }
   p->callingpres = ast->cid.cid_pres;
   p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
   p->jointnoncodeccapability = p->noncodeccapability;

   /* If there are no audio formats left to offer, punt */
   if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
      ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
      res = -1;
   } else {
      int xmitres;

      xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
      if (xmitres == XMIT_ERROR)
         return -1;
      p->invitestate = INV_CALLING;
   
      /* Initialize auto-congest time */
      AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p, 
                        dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"), 
                        dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
                        dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
   }
   return res;
}
static int sip_cancel_destroy ( struct sip_pvt p) [static]

Cancel destruction of SIP dialog. Be careful as this also absorbs the reference - if you call it from within the scheduler, this might be the last reference.

Definition at line 4218 of file chan_sip.c.

References append_history, ast_sched_del(), sip_pvt::autokillid, and dialog_unref().

Referenced by cb_extensionstate(), handle_request_invite(), handle_request_subscribe(), handle_response(), handle_response_invite(), register_verify(), sip_hangup(), and sip_scheddestroy().

{
   int res = 0;
   if (p->autokillid > -1) {
      int res3;

      if (!(res3 = ast_sched_del(sched, p->autokillid))) {
         append_history(p, "CancelDestroy", "");
         p->autokillid = -1;
         dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
      }
   }
   return res;
}
static int sip_check_authtimeout ( time_t  start) [static]

Check if the authtimeout has expired.

Parameters:
startthe time when the session started
Return values:
0the timeout has expired
-1error
Returns:
the number of milliseconds until the timeout will expire

Definition at line 2930 of file chan_sip.c.

References ast_log(), errno, and LOG_ERROR.

Referenced by _sip_tcp_helper_thread().

{
   int timeout;
   time_t now;
   if(time(&now) == -1) {
      ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
      return -1;
   }

   timeout = (authtimeout - (now - start)) * 1000;
   if (timeout < 0) {
      /* we have timed out */
      return 0;
   }

   return timeout;
}
static char * sip_cli_notify ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Cli command to send SIP notify to peer.

Definition at line 17468 of file chan_sip.c.

References ao2_t_link, ao2_t_unlink, ast_cli_args::argc, ast_cli_args::argv, ast_cli(), ast_log(), ast_set_flag, ast_sip_ouraddrfor(), ast_variable_browse(), build_callid_pvt(), build_via(), CLI_FAILURE, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, complete_sipnotify(), create_addr(), dialog_ref(), dialog_unlink_all(), dialog_unref(), ast_cli_args::fd, sip_pvt::flags, ast_cli_args::line, LOG_WARNING, ast_cli_args::n, sip_pvt::ourip, ast_cli_args::pos, sip_pvt::sa, sip_alloc(), SIP_NOTIFY, SIP_OUTGOING, sip_scheddestroy(), SIP_TRANS_TIMEOUT, transmit_notify_custom(), TRUE, ast_cli_entry::usage, and ast_cli_args::word.

{
   struct ast_variable *varlist;
   int i;

   switch (cmd) {
   case CLI_INIT:
      e->command = "sip notify";
      e->usage =
         "Usage: sip notify <type> <peer> [<peer>...]\n"
         "       Send a NOTIFY message to a SIP peer or peers\n"
         "       Message types are defined in sip_notify.conf\n";
      return NULL;
   case CLI_GENERATE:
      return complete_sipnotify(a->line, a->word, a->pos, a->n);
   }

   if (a->argc < 4)
      return CLI_SHOWUSAGE;

   if (!notify_types) {
      ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
      return CLI_FAILURE;
   }

   varlist = ast_variable_browse(notify_types, a->argv[2]);

   if (!varlist) {
      ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
      return CLI_FAILURE;
   }

   for (i = 3; i < a->argc; i++) {
      struct sip_pvt *p;

      if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
         ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
         return CLI_FAILURE;
      }

      if (create_addr(p, a->argv[i], NULL, 1)) {
         /* Maybe they're not registered, etc. */
         dialog_unlink_all(p, TRUE, TRUE);
         dialog_unref(p, "unref dialog inside for loop" );
         /* sip_destroy(p); */
         ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
         continue;
      }

      /* Notify is outgoing call */
      ast_set_flag(&p->flags[0], SIP_OUTGOING);

      /* Recalculate our side, and recalculate Call ID */
      ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
      build_via(p);
      ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
      build_callid_pvt(p);
      ao2_t_link(dialogs, p, "Linking in new name");
      ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
      dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
      sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
      transmit_notify_custom(p, varlist);
   }

   return CLI_SUCCESS;
}
static int sip_debug_test_addr ( const struct sockaddr_in *  addr) [inline, static]

See if we pass debug IP filter.

Definition at line 3598 of file chan_sip.c.

References debugaddr.

Referenced by check_peer_ok(), handle_request_do(), and sip_debug_test_pvt().

{
   if (!sipdebug)
      return 0;
   if (debugaddr.sin_addr.s_addr) {
      if (((ntohs(debugaddr.sin_port) != 0)
         && (debugaddr.sin_port != addr->sin_port))
         || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
         return 0;
   }
   return 1;
}
static struct sip_pvt * sip_destroy ( struct sip_pvt p) [static, read]

Destroy SIP call structure. Make it return NULL so the caller can do things like foo = sip_destroy(foo); and reduce the chance of bugs due to dangling pointers.

Definition at line 6001 of file chan_sip.c.

References __sip_destroy(), ast_debug, sip_pvt::callid, and TRUE.

Referenced by sip_destroy_fn(), and sip_subscribe_mwi_destroy().

{
   ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
   __sip_destroy(p, TRUE, TRUE);
   return NULL;
}
static void sip_destroy_fn ( void *  p) [static]

Definition at line 5991 of file chan_sip.c.

References sip_destroy().

Referenced by sip_alloc().

{
   sip_destroy(p);
}
static void sip_destroy_peer ( struct sip_peer peer) [static]

Destroy peer object from memory.

Definition at line 4854 of file chan_sip.c.

References ao2_ref, ast_atomic_fetchadd_int(), ast_debug, ast_dnsmgr_release(), ast_free_ha(), ast_string_field_free_memory, ast_variables_destroy(), sip_peer::auth, sip_peer::call, sip_peer::chanvars, clear_peer_mailboxes(), clear_realm_authentication(), dialog_unlink_all(), dialog_unref(), sip_peer::dnsmgr, FALSE, sip_peer::ha, sip_peer::is_realtime, sip_peer::mwipvt, sip_peer::name, sip_peer::outboundproxy, register_peer_exten(), sip_peer::selfdestruct, sip_peer::socket, sip_socket::tcptls_session, and TRUE.

Referenced by sip_destroy_peer_fn().

{
   ast_debug(3, "Destroying SIP peer %s\n", peer->name);
   if (peer->outboundproxy)
      ao2_ref(peer->outboundproxy, -1);
   peer->outboundproxy = NULL;

   /* Delete it, it needs to disappear */
   if (peer->call) {
      dialog_unlink_all(peer->call, TRUE, TRUE);
      peer->call = dialog_unref(peer->call, "peer->call is being unset");
   }
   

   if (peer->mwipvt) {  /* We have an active subscription, delete it */
      dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
      peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
   }
   
   if (peer->chanvars) {
      ast_variables_destroy(peer->chanvars);
      peer->chanvars = NULL;
   }
   
   register_peer_exten(peer, FALSE);
   ast_free_ha(peer->ha);
   if (peer->selfdestruct)
      ast_atomic_fetchadd_int(&apeerobjs, -1);
   else if (peer->is_realtime) {
      ast_atomic_fetchadd_int(&rpeerobjs, -1);
      ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
   } else
      ast_atomic_fetchadd_int(&speerobjs, -1);
   clear_realm_authentication(peer->auth);
   peer->auth = NULL;
   if (peer->dnsmgr)
      ast_dnsmgr_release(peer->dnsmgr);
   clear_peer_mailboxes(peer);

   if (peer->socket.tcptls_session) {
      ao2_ref(peer->socket.tcptls_session, -1);
      peer->socket.tcptls_session = NULL;
   }

   ast_string_field_free_memory(peer);
}
static void sip_destroy_peer_fn ( void *  peer) [static]

Definition at line 4848 of file chan_sip.c.

References sip_destroy_peer().

Referenced by build_peer(), and temp_peer().

{
   sip_destroy_peer(peer);
}
static int sip_devicestate ( void *  data) [static]

Part of PBX channel interface.

Note:
Return values:---

If we have qualify on and the device is not reachable, regardless of registration state we return AST_DEVICE_UNAVAILABLE

For peers with call limit:

  • not registered AST_DEVICE_UNAVAILABLE
  • registered, no call AST_DEVICE_NOT_INUSE
  • registered, active calls AST_DEVICE_INUSE
  • registered, call limit reached AST_DEVICE_BUSY
  • registered, onhold AST_DEVICE_ONHOLD
  • registered, ringing AST_DEVICE_RINGING

For peers without call limit:

  • not registered AST_DEVICE_UNAVAILABLE
  • registered AST_DEVICE_NOT_INUSE
  • fixed IP (!dynamic) AST_DEVICE_NOT_INUSE

Peers that does not have a known call and can't be reached by OPTIONS

  • unreachable AST_DEVICE_UNAVAILABLE

If we return AST_DEVICE_UNKNOWN, the device state engine will try to find out a state by walking the channel list.

The queue system (app_queue.c) treats a member as "active" if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID

When placing a call to the queue member, queue system sets a member to busy if != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN

Definition at line 23649 of file chan_sip.c.

References sip_peer::addr, ast_debug, AST_DEVICE_BUSY, AST_DEVICE_INUSE, AST_DEVICE_INVALID, AST_DEVICE_NOT_INUSE, AST_DEVICE_ONHOLD, AST_DEVICE_RINGING, AST_DEVICE_RINGINUSE, AST_DEVICE_UNAVAILABLE, AST_DEVICE_UNKNOWN, ast_strdupa, sip_peer::busy_level, sip_peer::call_limit, sip_peer::defaddr, FALSE, find_peer(), FINDALLDEVICES, sip_peer::inRinging, sip_peer::inUse, sip_peer::lastms, sip_peer::maxms, sip_peer::onHold, TRUE, and unref_peer().

{
   char *host;
   char *tmp;
   struct sip_peer *p;

   int res = AST_DEVICE_INVALID;

   /* make sure data is not null. Maybe unnecessary, but better be safe */
   host = ast_strdupa(data ? data : "");
   if ((tmp = strchr(host, '@')))
      host = tmp + 1;

   ast_debug(3, "Checking device state for peer %s\n", host);

   /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
    * is because when a peer tries to autoexpire, the last thing it does is to
    * queue up an event telling the system that the devicestate has changed
    * (presumably to unavailable).  If we ask for a realtime peer here, this would
    * load it BACK into memory, thus defeating the point of trying to clear dead
    * hosts out of memory.
    */
   if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
      if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
         /* we have an address for the peer */
      
         /* Check status in this order
            - Hold
            - Ringing
            - Busy (enforced only by call limit)
            - Inuse (we have a call)
            - Unreachable (qualify)
            If we don't find any of these state, report AST_DEVICE_NOT_INUSE
            for registered devices */

         if (p->onHold)
            /* First check for hold or ring states */
            res = AST_DEVICE_ONHOLD;
         else if (p->inRinging) {
            if (p->inRinging == p->inUse)
               res = AST_DEVICE_RINGING;
            else
               res = AST_DEVICE_RINGINUSE;
         } else if (p->call_limit && (p->inUse == p->call_limit))
            /* check call limit */
            res = AST_DEVICE_BUSY;
         else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
            /* We're forcing busy before we've reached the call limit */
            res = AST_DEVICE_BUSY;
         else if (p->call_limit && p->inUse)
            /* Not busy, but we do have a call */
            res = AST_DEVICE_INUSE;
         else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0))) 
            /* We don't have a call. Are we reachable at all? Requires qualify= */
            res = AST_DEVICE_UNAVAILABLE;
         else  /* Default reply if we're registered and have no other data */
            res = AST_DEVICE_NOT_INUSE;
      } else {
         /* there is no address, it's unavailable */
         res = AST_DEVICE_UNAVAILABLE;
      }
      unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
   } else {
      res = AST_DEVICE_UNKNOWN;
   }

   return res;
}
static char * sip_do_debug ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Turn on SIP debugging (CLI command)

Note:
this can be a special debug command - "sip debug text" or something

Definition at line 17425 of file chan_sip.c.

References ast_cli_args::argc, ast_cli_entry::args, ast_cli_args::argv, ast_cli(), CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, complete_sip_peer(), debugaddr, ast_cli_args::fd, ast_cli_args::n, ast_cli_args::pos, sip_debug_console, sip_do_debug_ip(), sip_do_debug_peer(), ast_cli_entry::usage, and ast_cli_args::word.

{
   int oldsipdebug = sipdebug & sip_debug_console;
   char *what;

   if (cmd == CLI_INIT) {
      e->command = "sip set debug {on|off|ip|peer}";
      e->usage =
         "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
         "       Globally disables dumping of SIP packets,\n"
         "       or enables it either globally or for a (single)\n"
         "       IP address or registered peer.\n";
      return NULL;
   } else if (cmd == CLI_GENERATE) {
      if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) 
         return complete_sip_peer(a->word, a->n, 0);
      return NULL;
        }

   what = a->argv[e->args-1];      /* guaranteed to exist */
   if (a->argc == e->args) {       /* on/off */
      if (!strcasecmp(what, "on")) {
         sipdebug |= sip_debug_console;
         sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
         memset(&debugaddr, 0, sizeof(debugaddr));
         ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
         return CLI_SUCCESS;
      } else if (!strcasecmp(what, "off")) {
         sipdebug &= ~sip_debug_console;
         sipdebug_text = 0;
         ast_cli(a->fd, "SIP Debugging Disabled\n");
         return CLI_SUCCESS;
      }
   } else if (a->argc == e->args +1) {/* ip/peer */
      if (!strcasecmp(what, "ip"))
         return sip_do_debug_ip(a->fd, a->argv[e->args]);
      else if (!strcasecmp(what, "peer"))
         return sip_do_debug_peer(a->fd, a->argv[e->args]);
   }
   return CLI_SHOWUSAGE;   /* default, failure */
}
static char * sip_do_debug_ip ( int  fd,
char *  arg 
) [static]

Enable SIP Debugging for a single IP.

Definition at line 17375 of file chan_sip.c.

References ast_cli(), ast_gethostbyname(), ast_inet_ntoa(), CLI_SHOWUSAGE, CLI_SUCCESS, debugaddr, hp, sip_debug_console, and strsep().

Referenced by sip_do_debug().

{
   struct hostent *hp;
   struct ast_hostent ahp;
   int port = 0;
   char *p;

   p = arg;
   strsep(&p, ":");
   if (p)
      port = atoi(p);
   hp = ast_gethostbyname(arg, &ahp);
   if (hp == NULL)
      return CLI_SHOWUSAGE;

   debugaddr.sin_family = AF_INET;
   memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
   debugaddr.sin_port = htons(port);
   if (port == 0)
      ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
   else
      ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);

   sipdebug |= sip_debug_console;

   return CLI_SUCCESS;
}
static char * sip_do_debug_peer ( int  fd,
char *  arg 
) [static]

Turn on SIP debugging for a given peer.

Definition at line 17404 of file chan_sip.c.

References sip_peer::addr, ast_cli(), ast_inet_ntoa(), CLI_SUCCESS, debugaddr, FALSE, find_peer(), FINDPEERS, sip_debug_console, TRUE, and unref_peer().

Referenced by sip_do_debug().

{
   struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
   if (!peer)
      ast_cli(fd, "No such peer '%s'\n", arg);
   else if (peer->addr.sin_addr.s_addr == 0)
      ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
   else {
      debugaddr.sin_family = AF_INET;
      debugaddr.sin_addr = peer->addr.sin_addr;
      debugaddr.sin_port = peer->addr.sin_port;
      ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
         ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
      sipdebug |= sip_debug_console;
   }
   if (peer)
      unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
   return CLI_SUCCESS;
}
static int sip_do_reload ( enum channelreloadreason  reason) [static]

Reload module.

Definition at line 26363 of file chan_sip.c.

References ast_debug, ast_sched_dump(), reload_config(), sip_poke_all_peers(), sip_send_all_mwi_subscriptions(), sip_send_all_registers(), and unlink_marked_peers_from_tables().

Referenced by do_monitor().

{
   time_t start_poke, end_poke;
   
   reload_config(reason);
   ast_sched_dump(sched);

   start_poke = time(0);
   /* Prune peers who still are supposed to be deleted */
   unlink_marked_peers_from_tables();

   ast_debug(4, "--------------- Done destroying pruned peers\n");

   /* Send qualify (OPTIONS) to all peers */
   sip_poke_all_peers();

   /* Register with all services */
   sip_send_all_registers();

   sip_send_all_mwi_subscriptions();

   end_poke = time(0);
   
   ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));

   ast_debug(4, "--------------- SIP reload done\n");

   return 0;
}
static int sip_dtmfmode ( struct ast_channel chan,
void *  data 
) [static]

Set the DTMFmode for an outbound SIP call (application)

Definition at line 26102 of file chan_sip.c.

References ast_channel_lock, ast_channel_unlock, ast_clear_flag, ast_dsp_free(), ast_dsp_new(), ast_dsp_set_features(), ast_log(), AST_RTP_DTMF, ast_rtp_setdtmf(), ast_set_flag, ast_test_flag, sip_request::data, sip_pvt::dsp, DSP_FEATURE_DIGIT_DETECT, sip_pvt::flags, IS_SIP_TECH, sip_pvt::jointnoncodeccapability, LOG_WARNING, sip_pvt::rtp, SIP_DTMF, SIP_DTMF_INBAND, SIP_DTMF_INFO, SIP_DTMF_RFC2833, SIP_DTMF_SHORTINFO, sip_pvt_lock, sip_pvt_unlock, ast_channel::tech, and ast_channel::tech_pvt.

Referenced by load_module().

{
   struct sip_pvt *p;
   char *mode = data;

   if (!data) {
      ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
      return 0;
   }
   ast_channel_lock(chan);
   if (!IS_SIP_TECH(chan->tech)) {
      ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
      ast_channel_unlock(chan);
      return 0;
   }
   p = chan->tech_pvt;
   if (!p) {
      ast_channel_unlock(chan);
      return 0;
   }
   sip_pvt_lock(p);
   if (!strcasecmp(mode, "info")) {
      ast_clear_flag(&p->flags[0], SIP_DTMF);
      ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
      p->jointnoncodeccapability &= ~AST_RTP_DTMF;
   } else if (!strcasecmp(mode, "shortinfo")) {
      ast_clear_flag(&p->flags[0], SIP_DTMF);
      ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
      p->jointnoncodeccapability &= ~AST_RTP_DTMF;
   } else if (!strcasecmp(mode, "rfc2833")) {
      ast_clear_flag(&p->flags[0], SIP_DTMF);
      ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
      p->jointnoncodeccapability |= AST_RTP_DTMF;
   } else if (!strcasecmp(mode, "inband")) { 
      ast_clear_flag(&p->flags[0], SIP_DTMF);
      ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
      p->jointnoncodeccapability &= ~AST_RTP_DTMF;
   } else
      ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
   if (p->rtp)
      ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
   if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
      if (!p->dsp) {
         p->dsp = ast_dsp_new();
         ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
      }
   } else {
      if (p->dsp) {
         ast_dsp_free(p->dsp);
         p->dsp = NULL;
      }
   }
   sip_pvt_unlock(p);
   ast_channel_unlock(chan);
   return 0;
}
static void sip_dump_history ( struct sip_pvt dialog) [static]

Dump SIP history to debug log file at end of lifespan for SIP dialog.

Definition at line 17160 of file chan_sip.c.

References ast_debug, AST_LIST_TRAVERSE, ast_log(), sip_pvt::callid, sip_history::event, sip_pvt::history, LOG_NOTICE, option_debug, and sip_pvt::subscribed.

Referenced by __sip_destroy().

{
   int x = 0;
   struct sip_history *hist;
   static int errmsg = 0;

   if (!dialog)
      return;

   if (!option_debug && !sipdebug) {
      if (!errmsg) {
         ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
         errmsg = 1;
      }
      return;
   }

   ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
   if (dialog->subscribed)
      ast_debug(1, "  * Subscription\n");
   else
      ast_debug(1, "  * SIP Call\n");
   if (dialog->history)
      AST_LIST_TRAVERSE(dialog->history, hist, list)
         ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
   if (!x)
      ast_debug(1, "Call '%s' has no history\n", dialog->callid);
   ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
}
static int sip_fixup ( struct ast_channel oldchan,
struct ast_channel newchan 
) [static]

sip_fixup: Fix up a channel: If a channel is consumed, this is called. Basically update any ->owner links

Definition at line 6532 of file chan_sip.c.

References append_history, ast_debug, AST_FLAG_ZOMBIE, ast_log(), ast_test_flag, sip_pvt::callid, LOG_WARNING, ast_channel::name, sip_pvt::owner, sip_pvt_lock, sip_pvt_unlock, sip_set_rtp_peer(), and ast_channel::tech_pvt.

{
   int ret = -1;
   struct sip_pvt *p;

   if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
      ast_debug(1, "New channel is zombie\n");
   if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
      ast_debug(1, "Old channel is zombie\n");

   if (!newchan || !newchan->tech_pvt) {
      if (!newchan)
         ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
      else
         ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
      return -1;
   }
   p = newchan->tech_pvt;

   sip_pvt_lock(p);
   append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
   append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
   if (p->owner != oldchan)
      ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
   else {
      p->owner = newchan;
      /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
         RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
         able to do this if the masquerade happens before the bridge breaks (e.g., AMI
         redirect of both channels). Note that a channel can not be masqueraded *into*
         a native bridge. So there is no danger that this breaks a native bridge that
         should stay up. */
      sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
      ret = 0;
   }
   ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);

   sip_pvt_unlock(p);
   return ret;
}
static const char * sip_get_callid ( struct ast_channel chan) [static]

Deliver SIP call ID for the call.

Definition at line 4709 of file chan_sip.c.

References ast_channel::tech_pvt.

{
   return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
}
static int sip_get_codec ( struct ast_channel chan) [static]

Return SIP UA's codec (part of the RTP interface)

Definition at line 26291 of file chan_sip.c.

References sip_pvt::capability, sip_pvt::jointcapability, and ast_channel::tech_pvt.

{
   struct sip_pvt *p = chan->tech_pvt;
   return p->jointcapability ? p->jointcapability : p->capability;   
}
static enum ast_rtp_get_result sip_get_rtp_peer ( struct ast_channel chan,
struct ast_rtp **  rtp 
) [static]
static enum ast_rtp_get_result sip_get_trtp_peer ( struct ast_channel chan,
struct ast_rtp **  rtp 
) [static]

Returns null if we can't reinvite text (part of RTP interface)

Definition at line 26002 of file chan_sip.c.

References AST_RTP_GET_FAILED, AST_RTP_TRY_NATIVE, AST_RTP_TRY_PARTIAL, ast_test_flag, sip_pvt::flags, SIP_DIRECT_MEDIA, sip_pvt_lock, sip_pvt_unlock, ast_channel::tech_pvt, and sip_pvt::trtp.

{
   struct sip_pvt *p = NULL;
   enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
   
   if (!(p = chan->tech_pvt))
      return AST_RTP_GET_FAILED;

   sip_pvt_lock(p);
   if (!(p->trtp)) {
      sip_pvt_unlock(p);
      return AST_RTP_GET_FAILED;
   }

   *rtp = p->trtp;

   if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
      res = AST_RTP_TRY_NATIVE;

   sip_pvt_unlock(p);

   return res;
}
static struct ast_udptl * sip_get_udptl_peer ( struct ast_channel chan) [static, read]

Definition at line 25904 of file chan_sip.c.

References ast_test_flag, sip_pvt::flags, SIP_DIRECT_MEDIA, sip_pvt_lock, sip_pvt_unlock, ast_channel::tech_pvt, and sip_pvt::udptl.

{
   struct sip_pvt *p;
   struct ast_udptl *udptl = NULL;
   
   p = chan->tech_pvt;
   if (!p)
      return NULL;
   
   sip_pvt_lock(p);
   if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
      udptl = p->udptl;
   sip_pvt_unlock(p);
   return udptl;
}
static enum ast_rtp_get_result sip_get_vrtp_peer ( struct ast_channel chan,
struct ast_rtp **  rtp 
) [static]

Returns null if we can't reinvite video (part of RTP interface)

Definition at line 25977 of file chan_sip.c.

References AST_RTP_GET_FAILED, AST_RTP_TRY_NATIVE, AST_RTP_TRY_PARTIAL, ast_test_flag, sip_pvt::flags, SIP_DIRECT_MEDIA, sip_pvt_lock, sip_pvt_unlock, ast_channel::tech_pvt, and sip_pvt::vrtp.

{
   struct sip_pvt *p = NULL;
   enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
   
   if (!(p = chan->tech_pvt))
      return AST_RTP_GET_FAILED;

   sip_pvt_lock(p);
   if (!(p->vrtp)) {
      sip_pvt_unlock(p);
      return AST_RTP_GET_FAILED;
   }

   *rtp = p->vrtp;

   if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
      res = AST_RTP_TRY_NATIVE;

   sip_pvt_unlock(p);

   return res;
}
static int sip_hangup ( struct ast_channel ast) [static]

sip_hangup: Hangup SIP call Part of PBX interface, called from ast_hangup

Definition at line 6171 of file chan_sip.c.

References __sip_semi_ack(), ast_channel::_state, sip_pvt::alreadygone, sip_pvt::answered_elsewhere, append_history, ast_bridged_channel(), ast_cause2str(), AST_CAUSE_ANSWERED_ELSEWHERE, ast_channel_trylock, ast_channel_unlock, ast_clear_flag, ast_debug, ast_dsp_free(), AST_FLAG_ANSWERED_ELSEWHERE, AST_FLAG_ZOMBIE, ast_log(), ast_module_unref(), ast_rtp_get_quality(), ast_rtp_set_vars(), AST_SCHED_DEL_UNREF, ast_set_flag, ast_state2str(), AST_STATE_UP, ast_strlen_zero(), ast_test_flag, sip_pvt::autokillid, ast_channel::bridge, sip_pvt::callid, CHANNEL_DEADLOCK_AVOIDANCE, sip_pkt::data, sip_request::data, DEC_CALL_LIMIT, DEFAULT_TRANS_TIMEOUT, dialog_unref(), sip_pvt::do_history, sip_pvt::dsp, FALSE, find_sip_method(), sip_pvt::flags, hangup_cause2sip(), sip_pvt::hangupcause, ast_channel::hangupcause, sip_pvt::initreq, INV_CALLING, INV_CANCELLED, INV_COMPLETED, INV_TERMINATED, sip_pvt::invitestate, sip_pkt::is_resp, IS_SIP_TECH, sip_pvt::lastinvite, LOG_WARNING, sip_pkt::method, ast_channel::name, sip_pvt::needdestroy, sip_pkt::next, sip_pvt::owner, sip_pvt::packets, pbx_builtin_setvar_helper(), sip_pvt::pendinginvite, sip_pvt::provisional_keepalive_sched_id, pvt_set_needdestroy(), sip_pvt::refer, sip_pvt::rtp, RTPQOS_SUMMARY, ast_module_info::self, sip_pkt::seqno, SIP_BYE, SIP_CANCEL, sip_cancel_destroy(), SIP_DEFER_BYE_ON_TRANSFER, SIP_INC_COUNT, SIP_NEEDREINVITE, SIP_OUTGOING, SIP_PAGE2_CALL_ONHOLD, SIP_PENDINGBYE, sip_pvt_lock, sip_pvt_trylock, sip_pvt_unlock, sip_scheddestroy(), sip_st_dlg::st_active, sip_pvt::stimer, stop_media_flows(), stop_session_timer(), ast_channel::tech, ast_channel::tech_pvt, transmit_request(), transmit_request_with_auth(), transmit_response_reliable(), sip_pvt::trtp, TRUE, update_call_counter(), sip_pvt::username, sip_pvt::vrtp, sip_pvt::waitid, and XMIT_RELIABLE.

{
   struct sip_pvt *p = ast->tech_pvt;
   int needcancel = FALSE;
   int needdestroy = 0;
   struct ast_channel *oldowner = ast;

   if (!p) {
      ast_debug(1, "Asked to hangup channel that was not connected\n");
      return 0;
   }
   if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
      ast_debug(1, "This call was answered elsewhere");
      if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
         ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
      }
      append_history(p, "Cancel", "Call answered elsewhere");
      p->answered_elsewhere = TRUE;
   }

   /* Store hangupcause locally in PVT so we still have it before disconnect */
   if (p->owner)
      p->hangupcause = p->owner->hangupcause;

   if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
      if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
         if (sipdebug)
            ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
         update_call_counter(p, DEC_CALL_LIMIT);
      }
      ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
      if (p->autokillid > -1 && sip_cancel_destroy(p))
         ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
      p->needdestroy = 0;
      p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
      sip_pvt_lock(p);
      p->owner = NULL;  /* Owner will be gone after we return, so take it away */
      sip_pvt_unlock(p);
      ast_module_unref(ast_module_info->self);
      return 0;
   }

   if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
      if (p->refer)
         ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
      else
         ast_debug(1, "Hanging up zombie call. Be scared.\n");
   } else
      ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);

   sip_pvt_lock(p);
   if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
      if (sipdebug)
         ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
      update_call_counter(p, DEC_CALL_LIMIT);
   }

   /* Determine how to disconnect */
   if (p->owner != ast) {
      ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
      sip_pvt_unlock(p);
      return 0;
   }
   /* If the call is not UP, we need to send CANCEL instead of BYE */
   /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
   if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
      needcancel = TRUE;
      ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
   }

   stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */

   append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");

   /* Disconnect */
   if (p->dsp)
      ast_dsp_free(p->dsp);

   p->owner = NULL;
   ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");

   ast_module_unref(ast_module_info->self);
   /* Do not destroy this pvt until we have timeout or
      get an answer to the BYE or INVITE/CANCEL 
      If we get no answer during retransmit period, drop the call anyway.
      (Sorry, mother-in-law, you can't deny a hangup by sending
      603 declined to BYE...)
   */
   if (p->alreadygone)
      needdestroy = 1;  /* Set destroy flag at end of this function */
   else if (p->invitestate != INV_CALLING)
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);

   /* Start the process if it's not already started */
   if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
      if (needcancel) { /* Outgoing call, not up */
         if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
            /* stop retransmitting an INVITE that has not received a response */
            /* if we can't send right now, mark it pending */
            if (p->invitestate == INV_CALLING) {
               /* We can't send anything in CALLING state */
               ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
               /* Do we need a timer here if we don't hear from them at all? Yes we do or else we will get hung dialogs and those are no fun. */
               sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
               append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
            } else {
               struct sip_pkt *cur;

               for (cur = p->packets; cur; cur = cur->next) {
                  __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
               }
               p->invitestate = INV_CANCELLED;
               /* Send a new request: CANCEL */
               transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
               /* Actually don't destroy us yet, wait for the 487 on our original 
                  INVITE, but do set an autodestruct just in case we never get it. */
               needdestroy = 0;
               sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
            }
         } else { /* Incoming call, not up */
            const char *res;
            AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
            if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
               transmit_response_reliable(p, res, &p->initreq);
            else 
               transmit_response_reliable(p, "603 Declined", &p->initreq);
            p->invitestate = INV_TERMINATED;
         }
      } else { /* Call is in UP state, send BYE */
         if (p->stimer->st_active == TRUE) {
            stop_session_timer(p);
         }

         if (!p->pendinginvite) {
            struct ast_channel *bridge = ast_bridged_channel(oldowner);
            char *audioqos = "";
            char *videoqos = "";
            char *textqos = "";

            /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
             * to lock the bridge. This may get hairy...
             */
            while (bridge && ast_channel_trylock(bridge)) {
               sip_pvt_unlock(p);
               do {
                  /* Use oldowner since p->owner is already NULL */
                  CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
               } while (sip_pvt_trylock(p));
               bridge = ast_bridged_channel(oldowner);
            }

            if (p->rtp)
               ast_rtp_set_vars(oldowner, p->rtp);

            if (bridge) {
               struct sip_pvt *q = bridge->tech_pvt;

               if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
                  ast_rtp_set_vars(bridge, q->rtp);
               ast_channel_unlock(bridge);
            }

            if (p->vrtp)
               videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
            if (p->trtp)
               textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
            /* Send a hangup */
            if (oldowner->_state == AST_STATE_UP) {
               transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
            }

            /* Get RTCP quality before end of call */
            if (p->do_history) {
               if (p->rtp)
                  append_history(p, "RTCPaudio", "Quality:%s", audioqos);
               if (p->vrtp)
                  append_history(p, "RTCPvideo", "Quality:%s", videoqos);
               if (p->trtp)
                  append_history(p, "RTCPtext", "Quality:%s", textqos);
            }
            if (p->rtp && oldowner)
               pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
            if (p->vrtp && oldowner)
               pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
            if (p->trtp && oldowner)
               pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
         } else {
            /* Note we will need a BYE when this all settles out
               but we can't send one while we have "INVITE" outstanding. */
            ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
            ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
            AST_SCHED_DEL_UNREF(sched, p->waitid, dialog_unref(p, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
            if (sip_cancel_destroy(p))
               ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
         }
      }
   }
   if (needdestroy) {
      pvt_set_needdestroy(p, "hangup");
   }
   sip_pvt_unlock(p);
   return 0;
}
static int sip_indicate ( struct ast_channel ast,
int  condition,
const void *  data,
size_t  datalen 
) [static]

Play indication to user With SIP a lot of indications is sent as messages, letting the device play the indication - busy signal, congestion etc.

Returns:
-1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message

Definition at line 6727 of file chan_sip.c.

References ast_channel::_state, AST_CONTROL_BUSY, AST_CONTROL_CONGESTION, AST_CONTROL_HOLD, AST_CONTROL_PROCEEDING, AST_CONTROL_PROGRESS, AST_CONTROL_RINGING, AST_CONTROL_SRCCHANGE, AST_CONTROL_SRCUPDATE, AST_CONTROL_T38_PARAMETERS, AST_CONTROL_UNHOLD, AST_CONTROL_VIDUPDATE, ast_log(), ast_moh_start(), ast_moh_stop(), ast_rtp_change_source(), ast_rtp_new_source(), ast_set_flag, AST_SOFTHANGUP_DEV, ast_softhangup_nolock(), AST_STATE_RING, AST_STATE_UP, ast_test_flag, sip_request::data, sip_pvt::flags, sip_pvt::initreq, interpret_t38_parameters(), INV_COMPLETED, INV_EARLY_MEDIA, INV_PROCEEDING, sip_pvt::invitestate, LOG_ERROR, LOG_WARNING, sip_pvt::mohinterpret, sip_pvt::novideo, sip_pvt::rtp, sip_alreadygone(), SIP_OUTGOING, SIP_PROG_INBAND, SIP_PROG_INBAND_NEVER, SIP_PROG_INBAND_YES, SIP_PROGRESS_SENT, sip_pvt_lock, sip_pvt_unlock, SIP_RINGING, ast_channel::tech_pvt, transmit_info_with_vidupdate(), transmit_provisional_response(), transmit_response(), transmit_response_reliable(), TRUE, and sip_pvt::vrtp.

{
   struct sip_pvt *p = ast->tech_pvt;
   int res = 0;

   sip_pvt_lock(p);
   switch(condition) {
   case AST_CONTROL_RINGING:
      if (ast->_state == AST_STATE_RING) {
         p->invitestate = INV_EARLY_MEDIA;
         if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
             (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
            /* Send 180 ringing if out-of-band seems reasonable */
            transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
            ast_set_flag(&p->flags[0], SIP_RINGING);
            if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
               break;
         } else {
            /* Well, if it's not reasonable, just send in-band */
         }
      }
      res = -1;
      break;
   case AST_CONTROL_BUSY:
      if (ast->_state != AST_STATE_UP) {
         transmit_response_reliable(p, "486 Busy Here", &p->initreq);
         p->invitestate = INV_COMPLETED;
         sip_alreadygone(p);
         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
         break;
      }
      res = -1;
      break;
   case AST_CONTROL_CONGESTION:
      if (ast->_state != AST_STATE_UP) {
         transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
         p->invitestate = INV_COMPLETED;
         sip_alreadygone(p);
         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
         break;
      }
      res = -1;
      break;
   case AST_CONTROL_PROCEEDING:
      if ((ast->_state != AST_STATE_UP) &&
          !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
          !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
         transmit_response(p, "100 Trying", &p->initreq);
         p->invitestate = INV_PROCEEDING;  
         break;
      }
      res = -1;
      break;
   case AST_CONTROL_PROGRESS:
      if ((ast->_state != AST_STATE_UP) &&
          !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
          !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
         p->invitestate = INV_EARLY_MEDIA;
         transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
         ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
         break;
      }
      res = -1;
      break;
   case AST_CONTROL_HOLD:
      ast_rtp_new_source(p->rtp);
      ast_moh_start(ast, data, p->mohinterpret);
      break;
   case AST_CONTROL_UNHOLD:
      ast_rtp_new_source(p->rtp);
      ast_moh_stop(ast);
      break;
   case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
      if (p->vrtp && !p->novideo) {
         transmit_info_with_vidupdate(p);
         /* ast_rtcp_send_h261fur(p->vrtp); */
      } else
         res = -1;
      break;
   case AST_CONTROL_T38_PARAMETERS:
      if (datalen != sizeof(struct ast_control_t38_parameters)) {
         ast_log(LOG_ERROR, "Invalid datalen for AST_CONTROL_T38_PARAMETERS. Expected %d, got %d\n", (int) sizeof(struct ast_control_t38_parameters), (int) datalen);
         res = -1;
      } else {
         const struct ast_control_t38_parameters *parameters = data;
         res = interpret_t38_parameters(p, parameters);
      }
      break;
   case AST_CONTROL_SRCUPDATE:
      ast_rtp_new_source(p->rtp);
      break;
   case AST_CONTROL_SRCCHANGE:
      ast_rtp_change_source(p->rtp);
      break;
   case -1:
      res = -1;
      break;
   default:
      ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
      res = -1;
      break;
   }
   sip_pvt_unlock(p);
   return res;
}
static const char * sip_nat_mode ( const struct sip_pvt p) [static]

Display SIP nat mode.

Definition at line 3621 of file chan_sip.c.

References ast_test_flag, sip_pvt::flags, SIP_NAT, and SIP_NAT_ROUTE.

Referenced by check_via(), retrans_pkt(), and send_response().

{
   return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
}
static struct ast_channel* sip_new ( struct sip_pvt i,
int  state,
const char *  title 
) [static, read]

Initiate a call in the SIP channel called from sip_request_call (calls from the pbx ) for outbound channels and from handle_request_invite for inbound channels.

Definition at line 6839 of file chan_sip.c.

References accountcode, sip_pvt::accountcode, ast_channel::adsicpe, ast_channel::amaflags, sip_pvt::amaflags, append_history, AST_ADSI_UNAVAILABLE, ast_atomic_fetchadd_int(), ast_best_codec(), AST_CAUSE_SWITCH_CONGESTION, ast_channel_alloc(), ast_channel_set_fd(), ast_codec_choose(), ast_copy_string(), ast_debug, ast_dsp_new(), ast_dsp_set_digitmode(), ast_dsp_set_features(), ast_exists_extension(), AST_FORMAT_TEXT_MASK, AST_FORMAT_VIDEO_MASK, ast_get_encoded_str(), ast_getformatname_multiple(), ast_hangup(), ast_jb_configure(), ast_log(), ast_module_ref(), ast_pbx_start(), ast_rtcp_fd(), ast_rtp_fd(), AST_STATE_DOWN, AST_STATE_RING, ast_strdup, ast_strdupa, ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_udptl_fd(), ast_uri_decode(), buf, sip_settings::callevents, sip_pvt::callgroup, ast_channel::callgroup, sip_pvt::callid, sip_pvt::callingpres, sip_pvt::capability, sip_pvt::chanvars, ast_channel::cid, ast_callerid::cid_ani, ast_callerid::cid_dnid, sip_pvt::cid_name, sip_pvt::cid_num, ast_callerid::cid_pres, ast_callerid::cid_rdnis, ast_channel::context, sip_pvt::context, dialog_ref(), sip_pvt::do_history, sip_pvt::domain, sip_pvt::dsp, DSP_DIGITMODE_DTMF, DSP_DIGITMODE_RELAXDTMF, DSP_FEATURE_DIGIT_DETECT, DSP_FEATURE_FAX_DETECT, EVENT_FLAG_SYSTEM, ast_channel::exten, sip_pvt::exten, sip_pvt::flags, sip_pvt::fromdomain, sip_pvt::fullcontact, global_capability, global_jbconf, ast_channel::hangupcause, sip_pvt::jointcapability, language, sip_pvt::language, LOG_WARNING, manager_event, ast_channel::name, ast_variable::name, ast_channel::nativeformats, ast_variable::next, sip_pvt::owner, parkinglot, sip_pvt::parkinglot, pbx_builtin_setvar_helper(), sip_pvt::pickupgroup, ast_channel::pickupgroup, sip_pvt::prefcodec, sip_pvt::prefs, ast_channel::priority, ast_channel::rawreadformat, ast_channel::rawwriteformat, sip_pvt::rdnis, ast_channel::readformat, ast_channel::rings, sip_pvt::rtp, ast_module_info::self, sip_cfg, SIP_DTMF, SIP_DTMF_AUTO, SIP_DTMF_INBAND, SIP_DTMF_INFO, SIP_DTMF_SHORTINFO, SIP_PAGE2_FAX_DETECT, SIP_PAGE2_VIDEOSUPPORT, sip_pvt_lock, sip_pvt_unlock, sip_tech_info, SIPBUFSIZE, ast_channel::tech, ast_channel::tech_pvt, text, sip_pvt::trtp, sip_pvt::udptl, ast_channel::uniqueid, sip_pvt::uri, ast_variable::value, sip_pvt::vrtp, and ast_channel::writeformat.

Referenced by handle_request_invite(), and sip_request_call().

{
   struct ast_channel *tmp;
   struct ast_variable *v = NULL;
   int fmt;
   int what;
   int video;
   int text;
   int needvideo = 0;
   int needtext = 0;
   char buf[SIPBUFSIZE];
   char *decoded_exten;

   {
      const char *my_name; /* pick a good name */
   
      if (title) {
         my_name = title;
      } else {
         char *port = NULL;
         my_name = ast_strdupa(i->fromdomain);
         if ((port = strchr(i->fromdomain, ':'))) {
            *port = '\0';
         }
      }

      sip_pvt_unlock(i);
      /* Don't hold a sip pvt lock while we allocate a channel */
      tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "SIP/%s-%08x", my_name, ast_atomic_fetchadd_int((int *)&chan_idx, +1));

   }
   if (!tmp) {
      ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
      sip_pvt_lock(i);
      return NULL;
   }
   sip_pvt_lock(i);

   tmp->tech = ( ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO || ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO) ?  &sip_tech_info : &sip_tech;

   /* Select our native format based on codec preference until we receive
      something from another device to the contrary. */
   if (i->jointcapability) {  /* The joint capabilities of us and peer */
      what = i->jointcapability;
      video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
      text = i->jointcapability & AST_FORMAT_TEXT_MASK;
   } else if (i->capability) {      /* Our configured capability for this peer */
      what = i->capability;
      video = i->capability & AST_FORMAT_VIDEO_MASK;
      text = i->capability & AST_FORMAT_TEXT_MASK;
   } else {
      what = global_capability;  /* Global codec support */
      video = global_capability & AST_FORMAT_VIDEO_MASK;
      text = global_capability & AST_FORMAT_TEXT_MASK;
   }

   /* Set the native formats for audio  and merge in video */
   tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
   ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
   ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
   ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
   ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
   if (i->prefcodec)
      ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));

   /* XXX Why are we choosing a codec from the native formats?? */
   fmt = ast_best_codec(tmp->nativeformats);

   /* If we have a prefcodec setting, we have an inbound channel that set a 
      preferred format for this call. Otherwise, we check the jointcapability
      We also check for vrtp. If it's not there, we are not allowed do any video anyway.
    */
   if (i->vrtp) {
      if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
         needvideo = AST_FORMAT_VIDEO_MASK;
      else if (i->prefcodec)
         needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
      else
         needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
   }

   if (i->trtp) {
      if (i->prefcodec)
         needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
      else
         needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
   }

   if (needvideo) 
      ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
   else
      ast_debug(3, "This channel will not be able to handle video.\n");

   if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
       (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
      int features = 0;

      if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
         features |= DSP_FEATURE_DIGIT_DETECT;
      }

      if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
         features |= DSP_FEATURE_FAX_DETECT;
      }

      i->dsp = ast_dsp_new();
      ast_dsp_set_features(i->dsp, features);
      if (global_relaxdtmf)
         ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
         }

   /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
   if (i->rtp) {
      ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
      ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
   }
   if (needvideo && i->vrtp) {
      ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
      ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
   }
   if (needtext && i->trtp) 
      ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
   if (i->udptl)
      ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));

   if (state == AST_STATE_RING)
      tmp->rings = 1;
   tmp->adsicpe = AST_ADSI_UNAVAILABLE;
   tmp->writeformat = fmt;
   tmp->rawwriteformat = fmt;
   tmp->readformat = fmt;
   tmp->rawreadformat = fmt;
   tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");

   tmp->callgroup = i->callgroup;
   tmp->pickupgroup = i->pickupgroup;
   tmp->cid.cid_pres = i->callingpres;
   if (!ast_strlen_zero(i->parkinglot))
      ast_string_field_set(tmp, parkinglot, i->parkinglot);
   if (!ast_strlen_zero(i->accountcode))
      ast_string_field_set(tmp, accountcode, i->accountcode);
   if (i->amaflags)
      tmp->amaflags = i->amaflags;
   if (!ast_strlen_zero(i->language))
      ast_string_field_set(tmp, language, i->language);
   i->owner = tmp;
   ast_module_ref(ast_module_info->self);
   ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
   /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
    * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
    * structure so that there aren't issues when forming URI's
    */
   if (ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
      /* encoded in dialplan, so keep extension encoded */
      ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
   } else {
      decoded_exten = ast_strdupa(i->exten);
      ast_uri_decode(decoded_exten);
      ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
   }

   /* Don't use ast_set_callerid() here because it will
    * generate an unnecessary NewCallerID event  */
   tmp->cid.cid_ani = ast_strdup(i->cid_num);
   if (!ast_strlen_zero(i->rdnis))
      tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
   
   if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
      tmp->cid.cid_dnid = ast_strdup(i->exten);

   tmp->priority = 1;
   if (!ast_strlen_zero(i->uri))
      pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
   if (!ast_strlen_zero(i->domain))
      pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
   if (!ast_strlen_zero(i->callid))
      pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
   if (i->rtp)
      ast_jb_configure(tmp, &global_jbconf);

   /* Set channel variables for this call from configuration */
   for (v = i->chanvars ; v ; v = v->next) {
      char valuebuf[1024];
      pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
   }

   if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
      ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
      tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
      ast_hangup(tmp);
      tmp = NULL;
   }

   if (i->do_history)
      append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);

   /* Inform manager user about new channel and their SIP call ID */
   if (sip_cfg.callevents)
      manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
         "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
         tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);

   return tmp;
}
static int sip_park ( struct ast_channel chan1,
struct ast_channel chan2,
struct sip_request req,
int  seqno 
) [static]

Park a call using the subsystem in res_features.c This is executed in a separate thread.

Definition at line 19375 of file chan_sip.c.

References ast_channel::accountcode, ast_channel::amaflags, ast_calloc, AST_CAUSE_SWITCH_CONGESTION, ast_channel_alloc(), ast_channel_lock, ast_channel_masquerade(), ast_channel_trylock, ast_channel_unlock, ast_copy_string(), ast_debug, ast_do_masquerade(), ast_free, ast_hangup(), ast_log(), ast_pthread_create_detached_background, AST_STATE_DOWN, ast_string_field_set, ast_strlen_zero(), sip_dual::chan1, sip_dual::chan2, ast_channel::context, copy_request(), deinit_req(), ast_channel::exten, ast_channel::hangupcause, LOG_WARNING, ast_channel::name, parkinglot, ast_channel::parkinglot, ast_channel::priority, ast_channel::readformat, sip_dual::req, sip_dual::seqno, sip_park_thread(), sip_pvt_lock, sip_pvt_unlock, ast_channel::tech_pvt, and ast_channel::writeformat.

Referenced by handle_request_refer().

{
   struct sip_dual *d;
   struct ast_channel *transferee, *transferer;
      /* Chan2m: The transferer, chan1m: The transferee */
   pthread_t th;

   transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
   transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
   if ((!transferer) || (!transferee)) {
      if (transferee) {
         transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
         ast_hangup(transferee);
      }
      if (transferer) {
         transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
         ast_hangup(transferer);
      }
      return -1;
   }

   /* Make formats okay */
   transferee->readformat = chan1->readformat;
   transferee->writeformat = chan1->writeformat;

   /* Prepare for taking over the channel */
   ast_channel_masquerade(transferee, chan1);

   /* Setup the extensions and such */
   ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
   ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
   transferee->priority = chan1->priority;
      
   /* We make a clone of the peer channel too, so we can play
      back the announcement */

   /* Make formats okay */
   transferer->readformat = chan2->readformat;
   transferer->writeformat = chan2->writeformat;
   if (!ast_strlen_zero(chan2->parkinglot))
      ast_string_field_set(transferer, parkinglot, chan2->parkinglot);

   /* Prepare for taking over the channel.  Go ahead and grab this channel
    * lock here to avoid a deadlock with callbacks into the channel driver
    * that hold the channel lock and want the pvt lock.  */
   while (ast_channel_trylock(chan2)) {
      struct sip_pvt *pvt = chan2->tech_pvt;
      sip_pvt_unlock(pvt);
      usleep(1);
      sip_pvt_lock(pvt);
   }
   ast_channel_masquerade(transferer, chan2);
   ast_channel_unlock(chan2);

   /* Setup the extensions and such */
   ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
   ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
   transferer->priority = chan2->priority;

   ast_channel_lock(transferer);
   if (ast_do_masquerade(transferer)) {
      ast_log(LOG_WARNING, "Masquerade failed :(\n");
      ast_channel_unlock(transferer);
      transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
      ast_hangup(transferer);
      return -1;
   }
   ast_channel_unlock(transferer);
   if (!transferer || !transferee) {
      if (!transferer) { 
         ast_debug(1, "No transferer channel, giving up parking\n");
      }
      if (!transferee) {
         ast_debug(1, "No transferee channel, giving up parking\n");
      }
      return -1;
   }
   if (!(d = ast_calloc(1, sizeof(*d)))) {
      return -1;
   }

   /* Save original request for followup */
   copy_request(&d->req, req);
   d->chan1 = transferee;  /* Transferee */
   d->chan2 = transferer;  /* Transferer */
   d->seqno = seqno;
   if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
      /* Could not start thread */
      deinit_req(&d->req);
      ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
               by sip_park_thread() */
      return -1;
   }
   return 0;
}
static void * sip_park_thread ( void *  stuff) [static]

Park SIP call support function Starts in a new thread, then parks the call XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the audio can't be heard before hangup.

Definition at line 19307 of file chan_sip.c.

References append_history, AST_CAUSE_NORMAL_CLEARING, ast_channel_lock, ast_channel_unlock, ast_debug, ast_do_masquerade(), ast_free, ast_hangup(), ast_log(), ast_park_call(), buf, sip_dual::chan1, sip_dual::chan2, copy_request(), deinit_req(), ext, ast_channel::hangupcause, LOG_ERROR, LOG_WARNING, ast_channel::name, sip_dual::req, sip_dual::seqno, ast_channel::tech_pvt, transmit_message_with_text(), transmit_notify_with_sipfrag(), transmit_response(), and TRUE.

Referenced by sip_park().

{
   struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
   struct sip_dual *d;
   struct sip_request req = {0,};
   int ext;
   int res;

   d = stuff;
   transferee = d->chan1;
   transferer = d->chan2;
   copy_request(&req, &d->req);

   if (!transferee || !transferer) {
      ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
      deinit_req(&d->req);
      ast_free(d);
      return NULL;
   }
   ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);

   ast_channel_lock(transferee);
   if (ast_do_masquerade(transferee)) {
      ast_log(LOG_WARNING, "Masquerade failed.\n");
      transmit_response(transferer->tech_pvt, "503 Internal error", &req);
      ast_channel_unlock(transferee);
      deinit_req(&d->req);
      ast_free(d);
      return NULL;
   } 
   ast_channel_unlock(transferee);

   res = ast_park_call(transferee, transferer, 0, &ext);
   

#ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
   if (!res) {
      transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
   } else {
      /* Then tell the transferer what happened */
      sprintf(buf, "Call parked on extension '%d'", ext);
      transmit_message_with_text(transferer->tech_pvt, buf);
   }
#endif

   /* Any way back to the current call??? */
   /* Transmit response to the REFER request */
   if (!res)   {
      /* Transfer succeeded */
      append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
      transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
      transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
      ast_hangup(transferer); /* This will cause a BYE */
      ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
   } else {
      transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
      append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
      ast_debug(1, "SIP Call parked failed \n");
      /* Do not hangup call */
   }
   deinit_req(&d->req);
   ast_free(d);
   return NULL;
}
static int sip_parse_host ( char *  line,
int  lineno,
char **  hostname,
int *  portnum,
enum sip_transport transport 
) [static]

Small function to parse a config line for a host with a transport i.e. tls://www.google.com:8056.

Definition at line 22866 of file chan_sip.c.

References ast_log(), hostname, sip_request::line, LOG_NOTICE, SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, SIP_TRANSPORT_UDP, STANDARD_SIP_PORT, and STANDARD_TLS_PORT.

Referenced by reload_config(), and sip_subscribe_mwi().

{
   char *port;

   if ((*hostname = strstr(line, "://"))) {
      *hostname += 3;

      if (!strncasecmp(line, "tcp", 3))
         *transport = SIP_TRANSPORT_TCP;
      else if (!strncasecmp(line, "tls", 3))
         *transport = SIP_TRANSPORT_TLS;
      else if (!strncasecmp(line, "udp", 3))
         *transport = SIP_TRANSPORT_UDP;
      else
         ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
   } else {
      *hostname = line;
      *transport = SIP_TRANSPORT_UDP;
   }

   if ((line = strrchr(*hostname, '@')))
      line++;
   else
      line = *hostname;

   if ((port = strrchr(line, ':'))) {
      *port++ = '\0';

      if (!sscanf(port, "%5u", portnum)) {
         ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
         port = NULL;
      }
   }

   if (!port) {
      if (*transport & SIP_TRANSPORT_TLS) {
         *portnum = STANDARD_TLS_PORT;
      } else {
         *portnum = STANDARD_SIP_PORT;
      }
   }

   return 0;
}
static void sip_peer_hold ( struct sip_pvt p,
int  hold 
) [static]

Change onhold state of a peer using a pvt structure.

Definition at line 13281 of file chan_sip.c.

References ast_atomic_fetchadd_int(), AST_DEVICE_UNKNOWN, ast_devstate_changed(), FALSE, find_peer(), FINDALLDEVICES, sip_peer::name, sip_peer::onHold, sip_pvt::peername, and unref_peer().

Referenced by change_hold_state(), and update_call_counter().

{
   struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);

   if (!peer)
      return;

   /* If they put someone on hold, increment the value... otherwise decrement it */
   ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));

   /* Request device state update */
   ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
   unref_peer(peer, "sip_peer_hold: from find_peer operation");
   
   return;
}
static void sip_poke_all_peers ( void  ) [static]

Send a poke to all known peers.

Definition at line 26298 of file chan_sip.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_lock(), ao2_t_iterator_next, ao2_unlock(), AST_SCHED_REPLACE_UNREF, global_qualify_gap, num, sip_peer::pokeexpire, ref_peer(), sip_poke_peer_s(), and unref_peer().

Referenced by load_module(), and sip_do_reload().

{
   int ms = 0, num = 0;
   struct ao2_iterator i;
   struct sip_peer *peer;

   if (!speerobjs)   /* No peers, just give up */
      return;

   i = ao2_iterator_init(peers, 0);
   while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
      ao2_lock(peer);
      if (num == global_qualify_peers) {
         ms += global_qualify_gap;
         num = 0;
      } else {
         num++;
      }
      AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
            unref_peer(_data, "removing poke peer ref"),
            unref_peer(peer, "removing poke peer ref"),
            ref_peer(peer, "adding poke peer ref"));
      ao2_unlock(peer);
      unref_peer(peer, "toss iterator peer ptr");
   }
   ao2_iterator_destroy(&i);
}
static int sip_poke_noanswer ( const void *  data) [static]

React to lack of answer to Qualify poke.

Definition at line 23491 of file chan_sip.c.

References ast_check_realtime(), AST_DEVICE_UNKNOWN, ast_devstate_changed(), ast_log(), AST_SCHED_REPLACE_UNREF, ast_update_realtime(), sip_peer::call, DEFAULT_FREQ_NOTOK, dialog_unlink_all(), dialog_unref(), EVENT_FLAG_SYSTEM, FALSE, sip_peer::lastms, LOG_NOTICE, manager_event, sip_peer::name, sip_settings::peer_rtupdate, sip_peer::pokeexpire, ref_peer(), sip_settings::regextenonqualify, register_peer_exten(), SENTINEL, sip_cfg, sip_poke_peer_s(), TRUE, and unref_peer().

Referenced by sip_poke_peer(), and sip_show_sched().

{
   struct sip_peer *peer = (struct sip_peer *)data;

   peer->pokeexpire = -1;

   if (peer->lastms > -1) {
      ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
      if (sip_cfg.peer_rtupdate) {
         ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
      }
      manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
      if (sip_cfg.regextenonqualify) {
         register_peer_exten(peer, FALSE);
      }
   }

   if (peer->call) {
      dialog_unlink_all(peer->call, TRUE, TRUE);
      peer->call = dialog_unref(peer->call, "unref dialog peer->call");
      /* peer->call = sip_destroy(peer->call);*/
   }

   /* Don't send a devstate change if nothing changed. */
   if (peer->lastms > -1) {
      peer->lastms = -1;
      ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
   }

   /* Try again quickly */
   AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
         DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
         unref_peer(_data, "removing poke peer ref"),
         unref_peer(peer, "removing poke peer ref"),
         ref_peer(peer, "adding poke peer ref"));

   /* Release the ref held by the running scheduler entry */
   unref_peer(peer, "release peer poke noanswer ref");

   return 0;
}
static int sip_poke_peer ( struct sip_peer peer,
int  force 
) [static]

Check availability of peer, also keep NAT open.

Note:
This is done with 60 seconds between each ping, unless forced by cli or manager. If peer is unreachable, we check every 10th second by default.

Definition at line 23538 of file chan_sip.c.

References sip_peer::addr, ao2_t_link, ao2_t_unlink, ast_copy_flags, ast_copy_string(), ast_inet_ntoa(), ast_log(), AST_SCHED_DEL_UNREF, AST_SCHED_REPLACE_UNREF, ast_set_flag, ast_sip_ouraddrfor(), ast_string_field_set, ast_strlen_zero(), ast_tvnow(), build_callid_pvt(), build_via(), sip_peer::call, copy_socket_data(), dialog_ref(), dialog_unlink_all(), dialog_unref(), sip_peer::flags, sip_pvt::flags, sip_pvt::fullcontact, sip_peer::fullcontact, sip_peer::lastms, LOG_NOTICE, sip_peer::maxms, sip_pvt::ourip, sip_peer::pokeexpire, sip_peer::ps, sip_pvt::recv, ref_peer(), sip_pvt::relatedpeer, sip_pvt::sa, sip_alloc(), SIP_FLAGS_TO_COPY, SIP_INVITE, SIP_OPTIONS, SIP_OUTGOING, SIP_PAGE2_FLAGS_TO_COPY, sip_poke_noanswer(), sip_peer::socket, sip_pvt::socket, sip_pvt::tohost, sip_peer::tohost, transmit_invite(), TRUE, unref_peer(), sip_pvt::username, and XMIT_ERROR.

Referenced by _sip_qualify_peer(), build_peer(), parse_register_contact(), reg_source_db(), and sip_poke_peer_s().

{
   struct sip_pvt *p;
   int xmitres = 0;
   
   if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
      /* IF we have no IP, or this isn't to be monitored, return
        immediately after clearing things out */
      AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
            unref_peer(peer, "removing poke peer ref"));
      
      peer->lastms = 0;
      if (peer->call) {
         peer->call = dialog_unref(peer->call, "unref dialog peer->call");
      }
      return 0;
   }
   if (peer->call) {
      if (sipdebug) {
         ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
      }
      dialog_unlink_all(peer->call, TRUE, TRUE);
      peer->call = dialog_unref(peer->call, "unref dialog peer->call");
      /* peer->call = sip_destroy(peer->call); */
   }
   if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
      return -1;
   }
   peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
   
   p->sa = peer->addr;
   p->recv = peer->addr;
   copy_socket_data(&p->socket, &peer->socket);
   ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
   ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);

   /* Send OPTIONs to peer's fullcontact */
   if (!ast_strlen_zero(peer->fullcontact))
      ast_string_field_set(p, fullcontact, peer->fullcontact);

   if (!ast_strlen_zero(peer->tohost))
      ast_string_field_set(p, tohost, peer->tohost);
   else
      ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));

   /* Recalculate our side, and recalculate Call ID */
   ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
   build_via(p);
   ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
   build_callid_pvt(p);
   ao2_t_link(dialogs, p, "Linking in under new name");

   AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
         unref_peer(peer, "removing poke peer ref"));
   
   if (p->relatedpeer)
      p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
   p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
   ast_set_flag(&p->flags[0], SIP_OUTGOING);
#ifdef VOCAL_DATA_HACK
   ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
   xmitres = transmit_invite(p, SIP_INVITE, 0, 2); /* sinks the p refcount */
#else
   xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2); /* sinks the p refcount */
#endif
   peer->ps = ast_tvnow();
   if (xmitres == XMIT_ERROR) {
      sip_poke_noanswer(peer);   /* Immediately unreachable, network problems */
   } else if (!force) {
      AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
            unref_peer(_data, "removing poke peer ref"),
            unref_peer(peer, "removing poke peer ref"),
            ref_peer(peer, "adding poke peer ref"));
   }
   dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
   return 0;
}
static int sip_poke_peer_s ( const void *  data) [static]

Poke peer (send qualify to check if peer is alive and well)

Definition at line 12556 of file chan_sip.c.

References ao2_find, sip_peer::name, OBJ_POINTER, sip_peer::pokeexpire, sip_poke_peer(), and unref_peer().

Referenced by handle_response_peerpoke(), reg_source_db(), sip_poke_all_peers(), sip_poke_noanswer(), and sip_show_sched().

{
   struct sip_peer *peer = (struct sip_peer *)data;
   struct sip_peer *foundpeer;

   peer->pokeexpire = -1;

   foundpeer = ao2_find(peers, peer, OBJ_POINTER);
   if (!foundpeer) {
      unref_peer(peer, "removing poke peer ref");
      return 0;
   } else if (foundpeer->name != peer->name) {
      unref_peer(foundpeer, "removing above peer ref");
      unref_peer(peer, "removing poke peer ref");
      return 0;
   }

   unref_peer(foundpeer, "removing above peer ref");
   sip_poke_peer(peer, 0);
   unref_peer(peer, "removing poke peer ref");

   return 0;
}
static int sip_prepare_socket ( struct sip_pvt p) [static]
Todo:
Get socket for dialog, prepare if needed, and return file handle

Todo:
Check this... This might be wrong, depending on the proxy configuration If proxy is in "force" mode its correct.

Definition at line 22732 of file chan_sip.c.

References ast_tcptls_session_args::accept_fd, ao2_alloc, ao2_ref, ao2_t_ref, ao2_t_unlink, ast_calloc, ast_copy_string(), ast_debug, ast_pthread_create_background, ast_strdup, ast_strlen_zero(), ast_tcptls_client_create(), ast_tls_config::cafile, ast_tls_config::capath, ast_tls_config::certfile, ast_tls_config::cipher, default_tls_cfg, ast_tcptls_session_instance::fd, sip_socket::fd, ast_tcptls_session_args::hostname, ast_tcptls_session_args::master, ast_tcptls_session_args::name, name, sip_pvt::outboundproxy, ast_tcptls_session_args::remote_address, s, sip_real_dst(), sip_tcp_locate(), sip_tcp_worker_fn(), sip_tcptls_client_args_destructor(), sip_threadinfo_create(), SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, SIP_TRANSPORT_UDP, sipsock, sip_pvt::socket, sip_socket::tcptls_session, ast_tcptls_session_args::tls_cfg, sip_pvt::tohost, sip_proxy::transport, and sip_socket::type.

Referenced by __sip_xmit().

{
   struct sip_socket *s = &p->socket;
   static const char name[] = "SIP socket";
   struct sip_threadinfo *th = NULL;
   struct ast_tcptls_session_instance *tcptls_session;
   struct ast_tcptls_session_args tmp_ca = {
      .name = name,
      .accept_fd = -1,
   };
   struct ast_tcptls_session_args *ca;

   /* check to see if a socket is already active */
   if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
      return s->fd;
   }
   if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
         (s->tcptls_session) &&
         (s->tcptls_session->fd != -1)) {
      return s->tcptls_session->fd;
   }

   /*! \todo Check this... This might be wrong, depending on the proxy configuration
      If proxy is in "force" mode its correct.
    */
   if (p->outboundproxy && p->outboundproxy->transport) {
      s->type = p->outboundproxy->transport;
   }

   if (s->type == SIP_TRANSPORT_UDP) {
      s->fd = sipsock;
      return s->fd;
   }

   /* At this point we are dealing with a TCP/TLS connection
    * 1. We need to check to see if a connectin thread exists
    *    for this address, if so use that.
    * 2. If a thread does not exist for this address, but the tcptls_session
    *    exists on the socket, the connection was closed.
    * 3. If no tcptls_session thread exists for the address, and no tcptls_session
    *    already exists on the socket, create a new one and launch a new thread.
    */

   /* 1.  check for existing threads */
   tmp_ca.remote_address = *(sip_real_dst(p));
   if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
      s->fd = tcptls_session->fd;
      if (s->tcptls_session) {
         ao2_ref(s->tcptls_session, -1);
         s->tcptls_session = NULL;
      }
      s->tcptls_session = tcptls_session;
      return s->fd;
   /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
   } else if (s->tcptls_session) {
      return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
   }

   /* 3.  Create a new TCP/TLS client connection */
   /* create new session arguments for the client connection */
   if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
      !(ca->name = ast_strdup(name))) {
      goto create_tcptls_session_fail;
   }
   ca->accept_fd = -1;
   ca->remote_address = *(sip_real_dst(p));
   /* if type is TLS, we need to create a tls cfg for this session arg */
   if (s->type == SIP_TRANSPORT_TLS) {
      if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
         goto create_tcptls_session_fail;
      }
      memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));

      if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
         !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
         !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
         !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {

         goto create_tcptls_session_fail;
      }

      /* this host is used as the common name in ssl/tls */
      if (!ast_strlen_zero(p->tohost)) {
         ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
      }
   }
   /* Create a client connection for address, this does not start the connection, just sets it up. */
   if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
      goto create_tcptls_session_fail;
   }

   s->fd = s->tcptls_session->fd;

   /* client connections need to have the sip_threadinfo object created before
    * the thread is detached.  This ensures the alert_pipe is up before it will
    * be used.  Note that this function links the new threadinfo object into the
    * threadt container. */
   if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
      goto create_tcptls_session_fail;

   }

   /* Give the new thread a reference to the tcptls_session */
   ao2_ref(s->tcptls_session, +1);

   if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
      ast_debug(1, "Unable to launch '%s'.", ca->name);
      ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
      goto create_tcptls_session_fail;
   }

   return s->fd;

create_tcptls_session_fail:
   if (ca) {
      ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
   }
   if (s->tcptls_session) {
      close(tcptls_session->fd);
      s->fd = tcptls_session->fd = -1;
      ao2_ref(s->tcptls_session, -1);
      s->tcptls_session = NULL;
   }
   if (th) {
      ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
   }

   return -1;
}
static char * sip_prune_realtime ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Remove temporary realtime objects from memory (CLI)

Todo:
XXXX Propably needs an overhaul after removal of the devices

Definition at line 15596 of file chan_sip.c.

References sip_peer::addr, ao2_iterator_destroy(), ao2_iterator_init(), ao2_lock(), ao2_t_find, ao2_t_iterator_next, ao2_t_link, ao2_t_unlink, ao2_unlock(), ast_cli_args::argc, ast_cli_args::argv, ast_cli(), ast_cli_complete(), ast_copy_string(), ast_test_flag, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, complete_sip_peer(), FALSE, ast_cli_args::fd, sip_peer::flags, ast_cli_args::n, sip_peer::name, name, OBJ_POINTER, OBJ_UNLINK, ast_cli_args::pos, SIP_PAGE2_RTCACHEFRIENDS, sip_peer::the_mark, TRUE, unlink_marked_peers_from_tables(), unref_peer(), ast_cli_entry::usage, and ast_cli_args::word.

{
   struct sip_peer *peer, *pi;
   int prunepeer = FALSE;
   int multi = FALSE;
   char *name = NULL;
   regex_t regexbuf;
   struct ao2_iterator i;
   static char *choices[] = { "all", "like", NULL };
   char *cmplt;
   
   if (cmd == CLI_INIT) {
      e->command = "sip prune realtime [peer|all]";
      e->usage =
         "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
         "       Prunes object(s) from the cache.\n"
         "       Optional regular expression pattern is used to filter the objects.\n";
      return NULL;
   } else if (cmd == CLI_GENERATE) {
      if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
         cmplt = ast_cli_complete(a->word, choices, a->n);
         if (!cmplt)
            cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
         return cmplt;
      }
      if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
         return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
      return NULL;
   }
   switch (a->argc) {
   case 4:
      name = a->argv[3];
      /* we accept a name in position 3, but keywords are not good. */
      if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
         return CLI_SHOWUSAGE;
      prunepeer = TRUE;
      if (!strcasecmp(name, "all")) {
         multi = TRUE;
         name = NULL;
      }
      /* else a single name, already set */
      break;
   case 5:
      /* sip prune realtime {peer|like} name */
      name = a->argv[4];
      if (!strcasecmp(a->argv[3], "peer"))
         prunepeer = TRUE;
      else if (!strcasecmp(a->argv[3], "like")) {
         prunepeer = TRUE;
         multi = TRUE;
      } else
         return CLI_SHOWUSAGE;
      if (!strcasecmp(name, "like"))
         return CLI_SHOWUSAGE;
      if (!multi && !strcasecmp(name, "all")) {
         multi = TRUE;
         name = NULL;
      }
      break;
   case 6:
      name = a->argv[5];
      multi = TRUE;
      /* sip prune realtime {peer} like name */
      if (strcasecmp(a->argv[4], "like"))
         return CLI_SHOWUSAGE;
      if (!strcasecmp(a->argv[3], "peer")) {
         prunepeer = TRUE;
      } else
         return CLI_SHOWUSAGE;
      break;
   default:
      return CLI_SHOWUSAGE;
   }

   if (multi && name) {
      if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
         return CLI_SHOWUSAGE;
   }

   if (multi) {
      if (prunepeer) {
         int pruned = 0;
         
         i = ao2_iterator_init(peers, 0);
         while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
            ao2_lock(pi);
            if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
               unref_peer(pi, "toss iterator peer ptr before continue");
               ao2_unlock(pi);
               continue;
            };
            if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
               pi->the_mark = 1;
               pruned++;
            }
            ao2_unlock(pi);
            unref_peer(pi, "toss iterator peer ptr");
         }
         ao2_iterator_destroy(&i);
         if (pruned) {
            unlink_marked_peers_from_tables();
            ast_cli(a->fd, "%d peers pruned.\n", pruned);
         } else
            ast_cli(a->fd, "No peers found to prune.\n");
      }
   } else {
      if (prunepeer) {
         struct sip_peer tmp;
         ast_copy_string(tmp.name, name, sizeof(tmp.name));
         if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
            if (peer->addr.sin_addr.s_addr) {
               ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
            }
            if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
               ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
               /* put it back! */
               ao2_t_link(peers, peer, "link peer into peer table");
               if (peer->addr.sin_addr.s_addr) {
                  ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
               }
               
            } else
               ast_cli(a->fd, "Peer '%s' pruned.\n", name);
            unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
         } else
            ast_cli(a->fd, "Peer '%s' not found.\n", name);
      }
   }

   return CLI_SUCCESS;
}
static char * sip_qualify_peer ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Send an OPTIONS packet to a SIP peer.

Definition at line 15880 of file chan_sip.c.

References _sip_qualify_peer(), ast_cli_args::argc, ast_cli_args::argv, CLI_GENERATE, CLI_INIT, ast_cli_entry::command, complete_sip_show_peer(), ast_cli_args::fd, ast_cli_args::line, ast_cli_args::n, ast_cli_args::pos, ast_cli_entry::usage, and ast_cli_args::word.

{
   switch (cmd) {
   case CLI_INIT:
      e->command = "sip qualify peer";
      e->usage =
         "Usage: sip qualify peer <name> [load]\n"
         "       Requests a response from one SIP peer and the current status.\n"
         "       Option \"load\" forces lookup of peer in realtime storage.\n";
      return NULL;
   case CLI_GENERATE:
      return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
   }
   return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
}
static int sip_queryoption ( struct ast_channel chan,
int  option,
void *  data,
int *  datalen 
) [static]

Query an option on a SIP dialog.

Definition at line 4468 of file chan_sip.c.

References ast_log(), AST_OPTION_T38_STATE, ast_test_flag, sip_pvt::flags, LOG_ERROR, SIP_PAGE2_T38SUPPORT, sip_pvt_lock, sip_pvt_unlock, t38properties::state, sip_pvt::t38, T38_ENABLED, T38_LOCAL_REINVITE, T38_PEER_REINVITE, T38_STATE_NEGOTIATED, T38_STATE_NEGOTIATING, T38_STATE_UNAVAILABLE, T38_STATE_UNKNOWN, and ast_channel::tech_pvt.

{
   int res = -1;
   enum ast_t38_state state = T38_STATE_UNAVAILABLE;
   struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;

   switch (option) {
   case AST_OPTION_T38_STATE:
      /* Make sure we got an ast_t38_state enum passed in */
      if (*datalen != sizeof(enum ast_t38_state)) {
         ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
         return -1;
      }

      sip_pvt_lock(p);

      /* Now if T38 support is enabled we need to look and see what the current state is to get what we want to report back */
      if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
         switch (p->t38.state) {
         case T38_LOCAL_REINVITE:
         case T38_PEER_REINVITE:
            state = T38_STATE_NEGOTIATING;
            break;
         case T38_ENABLED:
            state = T38_STATE_NEGOTIATED;
            break;
         default:
            state = T38_STATE_UNKNOWN;
         }
      }

      sip_pvt_unlock(p);

      *((enum ast_t38_state *) data) = state;
      res = 0;

      break;
   default:
      break;
   }

   return res;
}
static struct ast_frame * sip_read ( struct ast_channel ast) [static, read]

Read SIP RTP from channel.

Definition at line 7290 of file chan_sip.c.

References ast_channel::_state, ast_async_goto(), ast_channel_lock, ast_channel_unlock, ast_exists_extension(), AST_FRAME_VOICE, ast_log(), ast_null_frame, AST_STATE_UP, ast_test_flag, ast_verbose(), ast_channel::cid, ast_callerid::cid_num, ast_channel::context, ast_channel::exten, FALSE, sip_pvt::flags, ast_frame::frametype, INV_EARLY_MEDIA, sip_pvt::invitestate, sip_pvt::lastrtprx, LOG_NOTICE, ast_channel::macrocontext, ast_channel::name, pbx_builtin_setvar_helper(), S_OR, SIP_PAGE2_FAX_DETECT_CNG, sip_pvt_lock, sip_pvt_unlock, sip_rtp_read(), ast_channel::tech_pvt, and VERBOSE_PREFIX_2.

{
   struct ast_frame *fr;
   struct sip_pvt *p = ast->tech_pvt;
   int faxdetected = FALSE;

   sip_pvt_lock(p);
   fr = sip_rtp_read(ast, p, &faxdetected);
   p->lastrtprx = time(NULL);

   /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
   if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
      ast_channel_lock(ast);
      if (strcmp(ast->exten, "fax")) {
         const char *target_context = S_OR(ast->macrocontext, ast->context);
         ast_channel_unlock(ast);
         if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
            ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
            pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
            if (ast_async_goto(ast, target_context, "fax", 1)) {
               ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
            }
            fr = &ast_null_frame;
         } else {
            ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
                        }
      } else {
         ast_channel_unlock(ast);
                }
        }

   /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
   if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
      fr = &ast_null_frame;
   }

   sip_pvt_unlock(p);

   return fr;
}
static struct sockaddr_in * sip_real_dst ( const struct sip_pvt p) [static, read]

The real destination address for a write.

Definition at line 3612 of file chan_sip.c.

References ast_test_flag, sip_pvt::flags, sip_proxy::ip, sip_pvt::outboundproxy, sip_pvt::recv, sip_pvt::sa, SIP_NAT, and SIP_NAT_ROUTE.

Referenced by __sip_xmit(), check_via(), retrans_pkt(), send_response(), show_channels_cb(), sip_debug_test_pvt(), and sip_prepare_socket().

{
   if (p->outboundproxy)
      return &p->outboundproxy->ip;

   return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
}
static int sip_refer_allocate ( struct sip_pvt p) [static]

Allocate SIP refer structure.

Definition at line 12315 of file chan_sip.c.

References ast_calloc, and sip_pvt::refer.

Referenced by get_also_info(), handle_request_invite(), handle_request_refer(), and transmit_refer().

{
   p->refer = ast_calloc(1, sizeof(struct sip_refer)); 
   return p->refer ? 1 : 0;
}
static int sip_reg_timeout ( const void *  data) [static]

Registration timeout, register again Registered as a timeout handler during transmit_register(), to retransmit the packet if a reply does not come back. This is called by the scheduler so the event is not pending anymore when we are called.

Definition at line 11996 of file chan_sip.c.

References __sip_pretend_ack(), ast_dnsmgr_refresh(), ast_log(), sip_registry::call, dialog_unref(), sip_registry::dnsmgr, EVENT_FLAG_SYSTEM, sip_registry::hostname, LOG_NOTICE, manager_event, pvt_set_needdestroy(), REG_STATE_FAILED, REG_STATE_UNREGISTERED, sip_registry::regattempts, sip_pvt::registry, registry_unref(), sip_registry::regstate, regstate2str(), sip_pvt_lock, sip_pvt_unlock, SIP_REGISTER, sip_registry::timeout, transmit_register(), and sip_registry::username.

Referenced by sip_show_sched(), and transmit_register().

{

   /* if we are here, our registration timed out, so we'll just do it over */
   struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
   struct sip_pvt *p;
   int res;

   /* if we couldn't get a reference to the registry object, punt */
   if (!r)
      return 0;

   if (r->dnsmgr) {
      /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
      ast_dnsmgr_refresh(r->dnsmgr);
   }

   ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts); 
   /* If the initial tranmission failed, we may not have an existing dialog,
    * so it is possible that r->call == NULL.
    * Otherwise destroy it, as we have a timeout so we don't want it.
    */
   if (r->call) {
      /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
         in the single SIP manager thread. */
      p = r->call;
      sip_pvt_lock(p);
      pvt_set_needdestroy(p, "registration timeout");
      /* Pretend to ACK anything just in case */
      __sip_pretend_ack(p);
      sip_pvt_unlock(p);

      /* decouple the two objects */
      /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
      if (p->registry)
         p->registry = registry_unref(p->registry, "p->registry unreffed");
      r->call = dialog_unref(r->call, "unrefing r->call");
   }
   /* If we have a limit, stop registration and give up */
   r->timeout = -1;
   if (global_regattempts_max && r->regattempts > global_regattempts_max) {
      /* Ok, enough is enough. Don't try any more */
      /* We could add an external notification here... 
         steal it from app_voicemail :-) */
      ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
      r->regstate = REG_STATE_FAILED;
   } else {
      r->regstate = REG_STATE_UNREGISTERED;
      res=transmit_register(r, SIP_REGISTER, NULL, NULL);
   }
   manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
   registry_unref(r, "unreffing registry_unref r");
   return 0;
}
static int sip_register ( const char *  value,
int  lineno 
) [static]

Parse register=> line in sip.conf and add to registry.

register => [peer?][transport://]user[][:secret[:authuser]][:port][/extension][~expiry] becomes userpart => [peer?][transport://]user[][:secret[:authuser]] hostpart => host[:port][/extension][~expiry]

pre1.peer => peer pre1.userpart => [transport://]user[][:secret[:authuser]] hostpart => host[:port][/extension][~expiry]

pre1.peer => peer pre2.transport = transport pre2.userpart => user[][:secret[:authuser]] hostpart => host[:port][/extension][~expiry]

pre1.peer => peer pre2.transport = transport user1.userpart => user[] user1.secret => secret user1.authuser => authuser hostpart => host[:port][/extension][~expiry]

pre1.peer => peer pre2.transport = transport user1.userpart => user[] user1.secret => secret user1.authuser => authuser host1.hostpart => host[:port][/extension] host1.expiry => [expiry]

pre1.peer => peer pre2.transport = transport user1.userpart => user[] user1.secret => secret user1.authuser => authuser host2.hostpart => host[:port] host2.extension => [extension] host1.expiry => [expiry]

pre1.peer => peer pre2.transport = transport user1.userpart => user[] user1.secret => secret user1.authuser => authuser host3.host => host host3.port => port host2.extension => extension host1.expiry => expiry

Definition at line 7894 of file chan_sip.c.

References AST_APP_ARG, ast_atomic_fetchadd_int(), ast_calloc, ast_copy_string(), AST_DECLARE_APP_ARGS, ast_free, ast_log(), AST_NONSTANDARD_RAW_ARGS, ast_string_field_init, ast_string_field_set, ast_strip_quoted(), ast_strlen_zero(), ASTOBJ_CONTAINER_LINK, ASTOBJ_INIT, sip_registry::authuser, buf, sip_registry::callback, sip_registry::callid_valid, sip_registry::configured_expiry, default_expiry, sip_registry::expire, sip_registry::expiry, FALSE, hostname, INITIAL_CSEQ, LOG_ERROR, LOG_NOTICE, LOG_WARNING, sip_registry::ocseq, sip_registry::peername, port_str2int(), sip_registry::portno, sip_registry::refresh, registry_unref(), regl, S_OR, secret, SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, SIP_TRANSPORT_UDP, STANDARD_SIP_PORT, STANDARD_TLS_PORT, sip_registry::timeout, sip_registry::transport, and sip_registry::username.

Referenced by build_peer(), and reload_config().

{
   struct sip_registry *reg;
   int portnum = 0;
   enum sip_transport transport = SIP_TRANSPORT_UDP;
   char buf[256] = "";
   char *userpart = NULL, *hostpart = NULL;
   /* register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] */
   AST_DECLARE_APP_ARGS(pre1,
      AST_APP_ARG(peer);
      AST_APP_ARG(userpart);
   );
   AST_DECLARE_APP_ARGS(pre2,
      AST_APP_ARG(transport);
      AST_APP_ARG(blank);
      AST_APP_ARG(userpart);
   );
   AST_DECLARE_APP_ARGS(user1,
      AST_APP_ARG(userpart);
      AST_APP_ARG(secret);
      AST_APP_ARG(authuser);
   );
   AST_DECLARE_APP_ARGS(host1,
      AST_APP_ARG(hostpart);
      AST_APP_ARG(expiry);
   );
   AST_DECLARE_APP_ARGS(host2,
      AST_APP_ARG(hostpart);
      AST_APP_ARG(extension);
   );
   AST_DECLARE_APP_ARGS(host3,
      AST_APP_ARG(host);
      AST_APP_ARG(port);
   );

   if (!value)
      return -1;
   ast_copy_string(buf, value, sizeof(buf));

   /*! register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry]
    * becomes
    *   userpart => [peer?][transport://]user[@domain][:secret[:authuser]]
    *   hostpart => host[:port][/extension][~expiry]
    */
   if ((hostpart = strrchr(buf, '@'))) {
      *hostpart++ = '\0';
      userpart = buf;
   }

   if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
      ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
      return -1;
   }

   /*!
    * pre1.peer => peer
    * pre1.userpart => [transport://]user[@domain][:secret[:authuser]]
    * hostpart => host[:port][/extension][~expiry]
    */
   AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
   if (ast_strlen_zero(pre1.userpart)) {
      pre1.userpart = pre1.peer;
      pre1.peer = NULL;
   }

   /*!
    * pre1.peer => peer
    * pre2.transport = transport
    * pre2.userpart => user[@domain][:secret[:authuser]]
    * hostpart => host[:port][/extension][~expiry]
    */
   AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
   if (ast_strlen_zero(pre2.userpart)) {
      pre2.userpart = pre2.transport;
      pre2.transport = NULL;
   } else {
      pre2.transport[strlen(pre2.transport) - 1] = '\0'; /* Remove trailing : */
   }

   if (!ast_strlen_zero(pre2.blank)) {
      ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
      return -1;
   }

   /*!
    * pre1.peer => peer
    * pre2.transport = transport
    * user1.userpart => user[@domain]
    * user1.secret => secret
    * user1.authuser => authuser
    * hostpart => host[:port][/extension][~expiry]
    */
   AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');

   /*!
    * pre1.peer => peer
    * pre2.transport = transport
    * user1.userpart => user[@domain]
    * user1.secret => secret
    * user1.authuser => authuser
    * host1.hostpart => host[:port][/extension]
    * host1.expiry => [expiry]
    */
   AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');

   /*!
    * pre1.peer => peer
    * pre2.transport = transport
    * user1.userpart => user[@domain]
    * user1.secret => secret
    * user1.authuser => authuser
    * host2.hostpart => host[:port]
    * host2.extension => [extension]
    * host1.expiry => [expiry]
    */
   AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');

   /*!
    * pre1.peer => peer
    * pre2.transport = transport
    * user1.userpart => user[@domain]
    * user1.secret => secret
    * user1.authuser => authuser
    * host3.host => host
    * host3.port => port
    * host2.extension => extension
    * host1.expiry => expiry
    */
   AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');

   if (host3.port) {
      if (!(portnum = port_str2int(host3.port, 0))) {
         ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
      }
   }

   /* set transport type */
   if (!pre2.transport) {
      transport = SIP_TRANSPORT_UDP;
   } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
      transport = SIP_TRANSPORT_TCP;
   } else if (!strncasecmp(pre2.transport, "tls", 3)) {
      transport = SIP_TRANSPORT_TLS;
   } else if (!strncasecmp(pre2.transport, "udp", 3)) {
      transport = SIP_TRANSPORT_UDP;
   } else {
      transport = SIP_TRANSPORT_UDP;
      ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
   }

   /* if no portnum specified, set default for transport */
   if (!portnum) {
      if (transport == SIP_TRANSPORT_TLS) {
         portnum = STANDARD_TLS_PORT;
      } else {
         portnum = STANDARD_SIP_PORT;
      }
   }

   if (!(reg = ast_calloc(1, sizeof(*reg)))) {
      ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
      return -1;
   }

   if (ast_string_field_init(reg, 256)) {
      ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
      ast_free(reg);
      return -1;
   }

   ast_atomic_fetchadd_int(&regobjs, 1);
   ASTOBJ_INIT(reg);
   ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
   ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
   ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
   ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
   ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
   ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));

   reg->transport = transport;
   reg->timeout = reg->expire = -1;
   reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
   reg->portno = portnum;
   reg->callid_valid = FALSE;
   reg->ocseq = INITIAL_CSEQ;
   ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
   registry_unref(reg, "unref the reg pointer");   /* release the reference given by ASTOBJ_INIT. The container has another reference */
   return 0;
}
static void sip_registry_destroy ( struct sip_registry reg) [static]

Destroy registry object Objects created with the register= statement in static configuration.

Definition at line 5676 of file chan_sip.c.

References ast_atomic_fetchadd_int(), ast_debug, ast_dnsmgr_release(), ast_free, AST_SCHED_DEL, ast_string_field_free_memory, sip_registry::call, dialog_unlink_all(), dialog_unref(), sip_registry::dnsmgr, sip_registry::expire, sip_registry::hostname, sip_pvt::registry, registry_unref(), sip_registry::timeout, TRUE, and sip_registry::username.

Referenced by registry_unref(), reload_config(), and unload_module().

{
   /* Really delete */
   ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);

   if (reg->call) {
      /* Clear registry before destroying to ensure
         we don't get reentered trying to grab the registry lock */
      reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
      ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
      dialog_unlink_all(reg->call, TRUE, TRUE);
      reg->call = dialog_unref(reg->call, "unref reg->call");
      /* reg->call = sip_destroy(reg->call); */
   }
   AST_SCHED_DEL(sched, reg->expire);  
   AST_SCHED_DEL(sched, reg->timeout);
   
   ast_string_field_free_memory(reg);
   ast_atomic_fetchadd_int(&regobjs, -1);
   ast_dnsmgr_release(reg->dnsmgr);
   ast_free(reg);
}
static int sip_reinvite_retry ( const void *  data) [static]

Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite to avoid race conditions between asterisk servers. Called from the scheduler.

Definition at line 18143 of file chan_sip.c.

References ast_channel_trylock, ast_channel_unlock, ast_set_flag, check_pendings(), dialog_unref(), sip_pvt::flags, sip_pvt::owner, SIP_NEEDREINVITE, sip_pvt_lock, sip_pvt_unlock, and sip_pvt::waitid.

Referenced by handle_response_invite(), and sip_show_sched().

{
   struct sip_pvt *p = (struct sip_pvt *) data;
   struct ast_channel *owner;

   sip_pvt_lock(p); /* called from schedule thread which requires a lock */
   while ((owner = p->owner) && ast_channel_trylock(owner)) {
      sip_pvt_unlock(p);
      usleep(1);
      sip_pvt_lock(p);
   }
   ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
   p->waitid = -1;
   check_pendings(p);
   sip_pvt_unlock(p);
   if (owner) {
      ast_channel_unlock(owner);
   }
   dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
   return 0;
}
static char * sip_reload ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Force reload of module from cli.

Definition at line 26394 of file chan_sip.c.

References ast_mutex_lock(), ast_mutex_unlock(), ast_verbose(), CHANNEL_CLI_RELOAD, CHANNEL_MODULE_RELOAD, CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, restart_monitor(), sip_reload_lock, TRUE, and ast_cli_entry::usage.

Referenced by reload().

{
   
   switch (cmd) {
   case CLI_INIT:
      e->command = "sip reload";
      e->usage =
         "Usage: sip reload\n"
         "       Reloads SIP configuration from sip.conf\n";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }

   ast_mutex_lock(&sip_reload_lock);
   if (sip_reloading) 
      ast_verbose("Previous SIP reload not yet done\n");
   else {
      sip_reloading = TRUE;
      sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
   }
   ast_mutex_unlock(&sip_reload_lock);
   restart_monitor();

   return CLI_SUCCESS;
}
static int sip_removeheader ( struct ast_channel chan,
void *  data 
) [static]

Remove SIP headers added previously with SipAddHeader application.

Definition at line 26199 of file chan_sip.c.

References ast_channel_lock, ast_channel_unlock, AST_LIST_REMOVE_CURRENT, AST_LIST_TRAVERSE_SAFE_BEGIN, AST_LIST_TRAVERSE_SAFE_END, ast_log(), ast_strlen_zero(), ast_var_delete(), ast_var_name(), ast_var_value(), inbuf(), LOG_DEBUG, and ast_channel::varshead.

Referenced by load_module().

{
   struct ast_var_t *newvariable;
   struct varshead *headp;
   int removeall = 0;
   char *inbuf = (char *) data;

   if (ast_strlen_zero(inbuf)) {
      removeall = 1;
   }
   ast_channel_lock(chan);
 
   headp=&chan->varshead;
   AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
      if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
         if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
            if (sipdebug)
               ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
                  ast_var_value(newvariable),
                  ast_var_name(newvariable));
            AST_LIST_REMOVE_CURRENT(entries);
            ast_var_delete(newvariable);
         }
      }
   }
   AST_LIST_TRAVERSE_SAFE_END;
 
   ast_channel_unlock(chan);
   return 0;
}
static struct ast_channel * sip_request_call ( const char *  type,
int  format,
void *  data,
int *  cause 
) [static, read]

PBX interface function -build SIP pvt structure SIP calls initiated by the PBX arrive here.

 * 	SIP Dial string syntax
 *		SIP/exten@host!dnid
 *	or	SIP/host/exten!dnid
 *	or	SIP/host!dnid
 * 

Definition at line 23728 of file chan_sip.c.

References ao2_t_link, ao2_t_unlink, ast_calloc, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, AST_CAUSE_CHANNEL_UNACCEPTABLE, AST_CAUSE_SWITCH_CONGESTION, AST_CAUSE_UNREGISTERED, ast_copy_string(), ast_debug, AST_FORMAT_AUDIO_MASK, ast_getformatname(), ast_getformatname_multiple(), ast_log(), ast_sip_ouraddrfor(), AST_STATE_DOWN, ast_string_field_set, ast_strlen_zero(), ast_update_use_count(), build_callid_pvt(), build_via(), sip_settings::callevents, sip_pvt::callid, sip_pvt::capability, create_addr(), sip_request::data, dialog_unlink_all(), dialog_unref(), EVENT_FLAG_SYSTEM, ext, format, sip_pvt::fullcontact, sip_pvt::jointcapability, LOG_ERROR, LOG_NOTICE, LOG_WARNING, manager_event, ast_channel::name, sip_pvt::options, sip_pvt::ourip, sip_pvt::outgoing_call, sip_pvt::owner, sip_pvt::peername, sip_pvt::prefcodec, restart_monitor(), sip_pvt::sa, secret, set_socket_transport(), sip_alloc(), sip_cfg, SIP_INVITE, sip_new(), sip_pvt_lock, sip_pvt_unlock, SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, SIP_TRANSPORT_UDP, sip_pvt::socket, and TRUE.

{
   struct sip_pvt *p;
   struct ast_channel *tmpc = NULL;
   char *ext = NULL, *host;
   char tmp[256];
   char *dest = data;
   char *dnid;
   char *secret = NULL;
   char *md5secret = NULL;
   char *authname = NULL;
   char *trans = NULL;
   enum sip_transport transport = 0;
   int oldformat = format;

   /* mask request with some set of allowed formats.
    * XXX this needs to be fixed.
    * The original code uses AST_FORMAT_AUDIO_MASK, but it is
    * unclear what to use here. We have global_capabilities, which is
    * configured from sip.conf, and sip_tech.capabilities, which is
    * hardwired to all audio formats.
    */
   format &= AST_FORMAT_AUDIO_MASK;
   if (!format) {
      ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(global_capability));
      *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
      return NULL;
   }
   ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));

   if (ast_strlen_zero(dest)) {
      ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
      *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
      return NULL;
   }

   if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
      ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
      *cause = AST_CAUSE_SWITCH_CONGESTION;
      return NULL;
   }

   p->outgoing_call = TRUE;

   if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
      dialog_unlink_all(p, TRUE, TRUE);
      dialog_unref(p, "unref dialog p from mem fail");
      /* sip_destroy(p); */
      ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
      *cause = AST_CAUSE_SWITCH_CONGESTION;
      return NULL;
   }

   /* Save the destination, the SIP dial string */
   ast_copy_string(tmp, dest, sizeof(tmp));


   /* Find DNID and take it away */
   dnid = strchr(tmp, '!');
   if (dnid != NULL) {
      *dnid++ = '\0';
      ast_string_field_set(p, todnid, dnid);
   }

   /* Find at sign - @ */
   host = strchr(tmp, '@');
   if (host) {
      *host++ = '\0';
      ext = tmp;
      secret = strchr(ext, ':');
   }
   if (secret) {
      *secret++ = '\0';
      md5secret = strchr(secret, ':');
   }
   if (md5secret) {
      *md5secret++ = '\0';
      authname = strchr(md5secret, ':');
   }
   if (authname) {
      *authname++ = '\0';
      trans = strchr(authname, ':');
   }
   if (trans) {
      *trans++ = '\0';
      if (!strcasecmp(trans, "tcp"))
         transport = SIP_TRANSPORT_TCP;
      else if (!strcasecmp(trans, "tls"))
         transport = SIP_TRANSPORT_TLS;
      else {
         if (strcasecmp(trans, "udp"))
            ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
         transport = SIP_TRANSPORT_UDP;
      }
   } else { /* use default */
      transport = SIP_TRANSPORT_UDP;
   }

   if (!host) {
      ext = strchr(tmp, '/');
      if (ext) 
         *ext++ = '\0';
      host = tmp;
   }

   set_socket_transport(&p->socket, transport);

   /* We now have 
      host = peer name, DNS host name or DNS domain (for SRV) 
      ext = extension (user part of URI)
      dnid = destination of the call (applies to the To: header)
   */
   if (create_addr(p, host, NULL, 1)) {
      *cause = AST_CAUSE_UNREGISTERED;
      ast_debug(3, "Cant create SIP call - target device not registered\n");
      dialog_unlink_all(p, TRUE, TRUE);
      dialog_unref(p, "unref dialog p UNREGISTERED");
      /* sip_destroy(p); */
      return NULL;
   }
   if (ast_strlen_zero(p->peername) && ext)
      ast_string_field_set(p, peername, ext);
   /* Recalculate our side, and recalculate Call ID */
   ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
   build_via(p);
   ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
   build_callid_pvt(p);
   ao2_t_link(dialogs, p, "Linking in under new name");
   
   /* We have an extension to call, don't use the full contact here */
   /* This to enable dialing registered peers with extension dialling,
      like SIP/peername/extension   
      SIP/peername will still use the full contact 
    */
   if (ext) {
      ast_string_field_set(p, username, ext);
      ast_string_field_set(p, fullcontact, NULL);
   }
   if (secret && !ast_strlen_zero(secret))
      ast_string_field_set(p, peersecret, secret);

   if (md5secret && !ast_strlen_zero(md5secret))
      ast_string_field_set(p, peermd5secret, md5secret);

   if (authname && !ast_strlen_zero(authname))
      ast_string_field_set(p, authname, authname);
#if 0
   printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
#endif
   p->prefcodec = oldformat;           /* Format for this call */
   p->jointcapability = oldformat & p->capability;
   sip_pvt_lock(p);
   tmpc = sip_new(p, AST_STATE_DOWN, host);  /* Place the call */
   if (sip_cfg.callevents)
      manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
         "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
         p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
   sip_pvt_unlock(p);
   if (!tmpc) {
      dialog_unlink_all(p, TRUE, TRUE);
      /* sip_destroy(p); */
   }
   dialog_unref(p, "toss pvt ptr at end of sip_request_call");
   ast_update_use_count();
   restart_monitor();
   return tmpc;
}
static int sip_reregister ( const void *  data) [static]

Update registration with SIP Proxy. Called from the scheduler when the previous registration expires, so we don't have to cancel the pending event. We assume the reference so the sip_registry is valid, since it is stored in the scheduled event anyways.

Definition at line 11958 of file chan_sip.c.

References __sip_do_register(), append_history, ast_log(), sip_registry::call, sip_registry::configured_expiry, sip_pvt::do_history, sip_registry::expire, sip_registry::expiry, sip_registry::hostname, LOG_NOTICE, registry_unref(), and sip_registry::username.

Referenced by handle_response_register(), sip_send_all_registers(), and sip_show_sched().

{
   /* if we are here, we know that we need to reregister. */
   struct sip_registry *r= (struct sip_registry *) data;

   /* if we couldn't get a reference to the registry object, punt */
   if (!r)
      return 0;

   if (r->call && r->call->do_history)
      append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
   /* Since registry's are only added/removed by the the monitor thread, this
      may be overkill to reference/dereference at all here */
   if (sipdebug)
      ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);

   r->expire = -1;
   r->expiry = r->configured_expiry;
   __sip_do_register(r);
   registry_unref(r, "unref the re-register scheduled event");
   return 0;
}
static struct ast_frame * sip_rtp_read ( struct ast_channel ast,
struct sip_pvt p,
int *  faxdetect 
) [static, read]

Read RTP from network.

Definition at line 7200 of file chan_sip.c.

References ast_debug, ast_dsp_free(), ast_dsp_process(), ast_dsp_set_features(), AST_FORMAT_AUDIO_MASK, AST_FORMAT_TEXT_MASK, AST_FORMAT_VIDEO_MASK, AST_FRAME_DTMF, AST_FRAME_DTMF_BEGIN, AST_FRAME_DTMF_END, AST_FRAME_VOICE, ast_getformatname(), ast_log(), ast_null_frame, ast_rtcp_read(), ast_rtp_read(), ast_set_read_format(), ast_set_write_format(), ast_test_flag, ast_udptl_read(), ast_verbose(), ast_frame::data, ast_frame::datalen, sip_pvt::dsp, DSP_FEATURE_DIGIT_DETECT, f, ast_channel::fdno, sip_pvt::flags, ast_frame::frametype, sip_pvt::jointcapability, LOG_DEBUG, ast_channel::name, ast_channel::nativeformats, option_debug, sip_pvt::owner, ast_frame::ptr, ast_channel::readformat, sip_pvt::rtp, SIP_DTMF, SIP_DTMF_INBAND, SIP_DTMF_RFC2833, SIP_PAGE2_FAX_DETECT, ast_frame::subclass, sip_pvt::trtp, sip_pvt::udptl, sip_pvt::vrtp, and ast_channel::writeformat.

Referenced by sip_read().

{
   /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
   struct ast_frame *f;
   
   if (!p->rtp) {
      /* We have no RTP allocated for this channel */
      return &ast_null_frame;
   }

   switch(ast->fdno) {
   case 0:
      f = ast_rtp_read(p->rtp);  /* RTP Audio */
      break;
   case 1:
      f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
      break;
   case 2:
      f = ast_rtp_read(p->vrtp); /* RTP Video */
      break;
   case 3:
      f = ast_rtcp_read(p->vrtp);   /* RTCP Control Channel for video */
      break;
   case 4:
      f = ast_rtp_read(p->trtp); /* RTP Text */
      if (sipdebug_text) {
         int i;
         unsigned char* arr = f->data.ptr;
         for (i=0; i < f->datalen; i++)
            ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
         ast_verbose(" -> ");
         for (i=0; i < f->datalen; i++)
            ast_verbose("%02X ", arr[i]);
         ast_verbose("\n");
      }
      break;
   case 5:
      f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
      break;
   default:
      f = &ast_null_frame;
   }
   /* Don't forward RFC2833 if we're not supposed to */
   if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
       (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
      ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
      return &ast_null_frame;
   }

   /* We already hold the channel lock */
   if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
      return f;

   if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
      if (!(f->subclass & p->jointcapability)) {
         ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
            ast_getformatname(f->subclass), p->owner->name);
         return &ast_null_frame;
      }
      ast_debug(1, "Oooh, format changed to %d %s\n",
         f->subclass, ast_getformatname(f->subclass));
      p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
      ast_set_read_format(p->owner, p->owner->readformat);
      ast_set_write_format(p->owner, p->owner->writeformat);
   }

   if (f && ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT)) && p->dsp) {
      f = ast_dsp_process(p->owner, p->dsp, f);
                if (f && f->frametype == AST_FRAME_DTMF) {
         if (f->subclass == 'f') {
                                if (option_debug)
                                        ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
                                *faxdetect = 1;
            /* If we only needed this DSP for fax detection purposes we can just drop it now */
            if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
               ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
            } else {
               ast_dsp_free(p->dsp);
               p->dsp = NULL;
            }
         } else {
            ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
         }
      }
   }
   
   return f;
}
static void sip_scheddestroy ( struct sip_pvt p,
int  ms 
) [static]

Schedule destruction of SIP dialog.

Definition at line 4192 of file chan_sip.c.

References __sip_autodestruct(), append_history, ast_log(), ast_sched_add(), ast_verbose(), sip_pvt::autokillid, sip_pvt::callid, dialog_ref(), sip_pvt::do_history, global_t1, global_timer_b, LOG_WARNING, sip_pvt::method, sip_cancel_destroy(), sip_debug_test_pvt(), sip_methods, sip_st_dlg::st_active, sip_st_dlg::st_schedid, sip_pvt::stimer, stop_session_timer(), cfsip_methods::text, sip_pvt::timer_b, sip_pvt::timer_t1, and TRUE.

Referenced by __sip_autodestruct(), auto_congest(), cb_extensionstate(), check_auth(), check_pendings(), handle_incoming(), handle_invite_replaces(), handle_request_bye(), handle_request_cancel(), handle_request_info(), handle_request_invite(), handle_request_notify(), handle_request_options(), handle_request_register(), handle_request_subscribe(), handle_response_invite(), handle_response_register(), manager_sipnotify(), receive_message(), sip_cli_notify(), sip_hangup(), sip_send_mwi_to_peer(), sip_sipredirect(), and transmit_fake_auth_response().

{
   if (ms < 0) {
      if (p->timer_t1 == 0) {
         p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
         p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
      }
      ms = p->timer_t1 * 64;
   }
   if (sip_debug_test_pvt(p))
      ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
   if (sip_cancel_destroy(p))
      ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");

   if (p->do_history)
      append_history(p, "SchedDestroy", "%d ms", ms);
   p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));

   if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
      stop_session_timer(p);
}
static void sip_send_all_mwi_subscriptions ( void  ) [static]

Send all MWI subscriptions.

Definition at line 26350 of file chan_sip.c.

References ast_sched_add(), AST_SCHED_DEL, ASTOBJ_CONTAINER_TRAVERSE, ASTOBJ_REF, ASTOBJ_UNLOCK, ASTOBJ_UNREF, ASTOBJ_WRLOCK, sip_subscribe_mwi_destroy(), sip_subscribe_mwi_do(), and submwil.

Referenced by load_module(), and sip_do_reload().

{
   ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
      ASTOBJ_WRLOCK(iterator);
      AST_SCHED_DEL(sched, iterator->resub);
      if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
         ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
      }
      ASTOBJ_UNLOCK(iterator);
   } while (0));
}
static void sip_send_all_registers ( void  ) [static]

Send all known registrations.

Definition at line 26327 of file chan_sip.c.

References AST_SCHED_REPLACE_UNREF, ASTOBJ_CONTAINER_TRAVERSE, ASTOBJ_UNLOCK, ASTOBJ_WRLOCK, registry_addref(), registry_unref(), regl, regobjs, and sip_reregister().

Referenced by load_module(), and sip_do_reload().

{
   int ms;
   int regspacing;
   if (!regobjs)
      return;
   regspacing = default_expiry * 1000/regobjs;
   if (regspacing > 100)
      regspacing = 100;
   ms = regspacing;
   ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
      ASTOBJ_WRLOCK(iterator);
      ms += regspacing;
      AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator, 
                        registry_unref(_data, "REPLACE sched del decs the refcount"),
                        registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
                        registry_addref(iterator, "REPLACE sched add incs the refcount"));
      ASTOBJ_UNLOCK(iterator);
   } while (0)
   );
}
static int sip_send_mwi_to_peer ( struct sip_peer peer,
const struct ast_event event,
int  cache_only 
) [static]

Send message waiting indication to alert peer that they've got voicemail.

Definition at line 22937 of file chan_sip.c.

References sip_peer::addr, ao2_t_link, ao2_t_unlink, ast_app_inboxcount(), ast_event_get_ie_uint(), AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_OLDMSGS, ast_set_flag, ast_sip_ouraddrfor(), ast_str_alloca, ast_test_flag, build_callid_pvt(), build_via(), create_addr_from_peer(), sip_peer::defaddr, DEFAULT_TRANS_TIMEOUT, dialog_ref(), dialog_unlink_all(), dialog_unref(), sip_pvt::flags, sip_peer::flags, get_cached_mwi(), sip_peer::mwipvt, sip_pvt::ourip, peer_mailboxes_to_str(), sip_pvt::sa, set_socket_transport(), sip_alloc(), SIP_NOTIFY, SIP_OUTGOING, SIP_PAGE2_SUBSCRIBEMWIONLY, sip_scheddestroy(), sip_pvt::socket, transmit_notify_with_mwi(), TRUE, and sip_peer::vmexten.

Referenced by build_peer(), handle_request_subscribe(), and mwi_event_cb().

{
   /* Called with peerl lock, but releases it */
   struct sip_pvt *p;
   int newmsgs = 0, oldmsgs = 0;

   if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
      return 0;

   /* Do we have an IP address? If not, skip this peer */
   if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr) 
      return 0;

   if (event) {
      newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
      oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
   } else if (!cache_only) { /* Fall back to manually checking the mailbox */
      struct ast_str *mailbox_str = ast_str_alloca(512);
      peer_mailboxes_to_str(&mailbox_str, peer);
      ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
   } else {
      get_cached_mwi(peer, &newmsgs, &oldmsgs);
   }
   
   if (peer->mwipvt) {
      /* Base message on subscription */
      p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
   } else {
      /* Build temporary dialog for this message */
      if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) 
         return -1;
      /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
       * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy 
       * the peer's socket information to the sip_pvt we just allocated
       */
      set_socket_transport(&p->socket, 0);
      if (create_addr_from_peer(p, peer)) {
         /* Maybe they're not registered, etc. */
         dialog_unlink_all(p, TRUE, TRUE);
         dialog_unref(p, "unref dialog p just created via sip_alloc");
         /* sip_destroy(p); */
         return 0;
      }
      /* Recalculate our side, and recalculate Call ID */
      ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
      build_via(p);
      ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
      build_callid_pvt(p);
      ao2_t_link(dialogs, p, "Linking in under new name");
      /* Destroy this session after 32 secs */
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
   }

   /* Send MWI */
   ast_set_flag(&p->flags[0], SIP_OUTGOING);
   /* the following will decrement the refcount on p as it finishes */
   transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
   dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
   return 0;
}
static int sip_senddigit_begin ( struct ast_channel ast,
char  digit 
) [static]

Definition at line 6573 of file chan_sip.c.

References ast_rtp_senddigit_begin(), ast_test_flag, sip_pvt::flags, sip_pvt::rtp, SIP_DTMF, SIP_DTMF_INBAND, SIP_DTMF_RFC2833, sip_pvt_lock, sip_pvt_unlock, and ast_channel::tech_pvt.

{
   struct sip_pvt *p = ast->tech_pvt;
   int res = 0;

   sip_pvt_lock(p);
   switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
   case SIP_DTMF_INBAND:
      res = -1; /* Tell Asterisk to generate inband indications */
      break;
   case SIP_DTMF_RFC2833:
      if (p->rtp)
         ast_rtp_senddigit_begin(p->rtp, digit);
      break;
   default:
      break;
   }
   sip_pvt_unlock(p);

   return res;
}
static int sip_senddigit_end ( struct ast_channel ast,
char  digit,
unsigned int  duration 
) [static]

Send DTMF character on SIP channel within one call, we're able to transmit in many methods simultaneously.

Definition at line 6597 of file chan_sip.c.

References ast_rtp_senddigit_end_with_duration(), ast_test_flag, sip_pvt::flags, sip_pvt::rtp, SIP_DTMF, SIP_DTMF_INBAND, SIP_DTMF_INFO, SIP_DTMF_RFC2833, SIP_DTMF_SHORTINFO, sip_pvt_lock, sip_pvt_unlock, ast_channel::tech_pvt, and transmit_info_with_digit().

{
   struct sip_pvt *p = ast->tech_pvt;
   int res = 0;

   sip_pvt_lock(p);
   switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
   case SIP_DTMF_INFO:
   case SIP_DTMF_SHORTINFO:
      transmit_info_with_digit(p, digit, duration);
      break;
   case SIP_DTMF_RFC2833:
      if (p->rtp)
         ast_rtp_senddigit_end_with_duration(p->rtp, digit, duration);
      break;
   case SIP_DTMF_INBAND:
      res = -1; /* Tell Asterisk to stop inband indications */
      break;
   }
   sip_pvt_unlock(p);

   return res;
}
static int sip_sendhtml ( struct ast_channel chan,
int  subclass,
const char *  data,
int  datalen 
) [static]

Send message with Access-URL header, if this is an HTML URL only!

Definition at line 4675 of file chan_sip.c.

References ast_channel::_state, ast_debug, AST_HTML_URL, ast_log(), ast_set_flag, AST_STATE_RING, AST_STATE_RINGING, AST_STATE_UP, ast_string_field_build, ast_test_flag, FALSE, sip_pvt::flags, sip_pvt::initreq, LOG_WARNING, sip_pvt::pendinginvite, sip_debug_test_pvt(), SIP_NEEDREINVITE, SIP_PENDINGBYE, ast_channel::tech_pvt, transmit_reinvite_with_sdp(), transmit_response(), and url.

{
   struct sip_pvt *p = chan->tech_pvt;

   if (subclass != AST_HTML_URL)
      return -1;

   ast_string_field_build(p, url, "<%s>;mode=active", data);

   if (sip_debug_test_pvt(p))
      ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);

   switch (chan->_state) {
   case AST_STATE_RING:
      transmit_response(p, "100 Trying", &p->initreq);
      break;
   case AST_STATE_RINGING:
      transmit_response(p, "180 Ringing", &p->initreq);
      break;
   case AST_STATE_UP:
      if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
         transmit_reinvite_with_sdp(p, FALSE, FALSE);
      } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
         ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
      }  
      break;
   default:
      ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
   }

   return 0;
}
static int sip_sendtext ( struct ast_channel ast,
const char *  text 
) [static]

Send SIP MESSAGE text within a call Called from PBX core sendtext() application.

Definition at line 4716 of file chan_sip.c.

References ast_verbose(), sip_request::debug, ast_channel::name, sip_debug_test_pvt(), ast_channel::tech_pvt, and transmit_message_with_text().

{
   struct sip_pvt *p = ast->tech_pvt;
   int debug = sip_debug_test_pvt(p);

   if (debug)
      ast_verbose("Sending text %s on %s\n", text, ast->name);
   if (!p)
      return -1;
   /* NOT ast_strlen_zero, because a zero-length message is specifically
    * allowed by RFC 3428 (See section 10, Examples) */
   if (!text)
      return 0;
   if (debug)
      ast_verbose("Really sending text %s on %s\n", text, ast->name);
   transmit_message_with_text(p, text);
   return 0;   
}
static char * sip_set_history ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Enable/Disable SIP History logging (CLI)

Definition at line 17536 of file chan_sip.c.

References ast_cli_args::argc, ast_cli_entry::args, ast_cli_args::argv, ast_cli(), CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, FALSE, ast_cli_args::fd, TRUE, and ast_cli_entry::usage.

{
   switch (cmd) {
   case CLI_INIT:
      e->command = "sip set history {on|off}";
      e->usage =
         "Usage: sip set history {on|off}\n"
         "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
         "       Use 'sip show history' to view the history of a call number.\n";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }

   if (a->argc != e->args)
      return CLI_SHOWUSAGE;

   if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
      recordhistory = TRUE;
      ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
   } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
      recordhistory = FALSE;
      ast_cli(a->fd, "SIP History Recording Disabled\n");
   } else {
      return CLI_SHOWUSAGE;
   }
   return CLI_SUCCESS;
}
static void sip_set_redirstr ( struct sip_pvt p,
char *  reason 
) [static]

Translate referring cause.

Definition at line 13726 of file chan_sip.c.

References ast_string_field_set.

Referenced by get_rdnis().

                                                              {

   if (!strcmp(reason, "unknown")) {
      ast_string_field_set(p, redircause, "UNKNOWN");
   } else if (!strcmp(reason, "user-busy")) {
      ast_string_field_set(p, redircause, "BUSY");
   } else if (!strcmp(reason, "no-answer")) {
      ast_string_field_set(p, redircause, "NOANSWER");
   } else if (!strcmp(reason, "unavailable")) {
      ast_string_field_set(p, redircause, "UNREACHABLE");
   } else if (!strcmp(reason, "unconditional")) {
      ast_string_field_set(p, redircause, "UNCONDITIONAL");
   } else if (!strcmp(reason, "time-of-day")) {
      ast_string_field_set(p, redircause, "UNKNOWN");
   } else if (!strcmp(reason, "do-not-disturb")) {
      ast_string_field_set(p, redircause, "UNKNOWN");
   } else if (!strcmp(reason, "deflection")) {
      ast_string_field_set(p, redircause, "UNKNOWN");
   } else if (!strcmp(reason, "follow-me")) {
      ast_string_field_set(p, redircause, "UNKNOWN");
   } else if (!strcmp(reason, "out-of-service")) {
      ast_string_field_set(p, redircause, "UNREACHABLE");
   } else if (!strcmp(reason, "away")) {
      ast_string_field_set(p, redircause, "UNREACHABLE");
   } else {
      ast_string_field_set(p, redircause, "UNKNOWN");
   }
}
static int sip_set_rtp_peer ( struct ast_channel chan,
struct ast_rtp rtp,
struct ast_rtp vrtp,
struct ast_rtp trtp,
int  codecs,
int  nat_active 
) [static]

Set the RTP peer for this call.

Definition at line 26027 of file chan_sip.c.

References ast_channel::_state, sip_pvt::alreadygone, append_history, ast_bridged_channel(), ast_debug, ast_inet_ntoa(), ast_rtp_get_peer(), ast_set_flag, AST_STATE_UP, ast_test_flag, sip_pvt::callid, sip_settings::directrtpsetup, sip_pvt::do_history, FALSE, sip_pvt::flags, sip_pvt::lastrtprx, sip_pvt::lastrtptx, sip_pvt::ourip, sip_pvt::pendinginvite, sip_pvt::redircodecs, sip_pvt::redirip, sip_cfg, SIP_DEFER_BYE_ON_TRANSFER, SIP_DIRECT_MEDIA_NAT, SIP_GOTREFER, SIP_NEEDREINVITE, SIP_PENDINGBYE, sip_pvt_lock, sip_pvt_unlock, ast_channel::tech_pvt, transmit_reinvite_with_sdp(), sip_pvt::tredirip, and sip_pvt::vredirip.

Referenced by sip_fixup().

{
   struct sip_pvt *p;
   int changed = 0;

   p = chan->tech_pvt;
   if (!p) 
      return -1;

   /* Disable early RTP bridge  */
   if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)  /* We are in early state */
      return 0;

   sip_pvt_lock(p);
   if (p->alreadygone) {
      /* If we're destroyed, don't bother */
      sip_pvt_unlock(p);
      return 0;
   }

   /* if this peer cannot handle reinvites of the media stream to devices
      that are known to be behind a NAT, then stop the process now
   */
        if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
                sip_pvt_unlock(p);
                return 0;
        }

   if (rtp) {
      changed |= ast_rtp_get_peer(rtp, &p->redirip);
   } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
      memset(&p->redirip, 0, sizeof(p->redirip));
      changed = 1;
   }
   if (vrtp) {
      changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
   } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
      memset(&p->vredirip, 0, sizeof(p->vredirip));
      changed = 1;
   }
   if (trtp) {
      changed |= ast_rtp_get_peer(trtp, &p->tredirip);
   } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
      memset(&p->tredirip, 0, sizeof(p->tredirip));
      changed = 1;
   }
   if (codecs && (p->redircodecs != codecs)) {
      p->redircodecs = codecs;
      changed = 1;
   }
   if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
      if (chan->_state != AST_STATE_UP) { /* We are in early state */
         if (p->do_history)
            append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
         ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
      } else if (!p->pendinginvite) {     /* We are up, and have no outstanding invite */
         ast_debug(3, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
         transmit_reinvite_with_sdp(p, FALSE, FALSE);
      } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
         ast_debug(3, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
         /* We have a pending Invite. Send re-invite when we're done with the invite */
         ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
      }
   }
   /* Reset lastrtprx timer */
   p->lastrtprx = p->lastrtptx = time(NULL);
   sip_pvt_unlock(p);
   return 0;
}
static int sip_set_udptl_peer ( struct ast_channel chan,
struct ast_udptl udptl 
) [static]

Definition at line 25920 of file chan_sip.c.

References ast_debug, ast_inet_ntoa(), ast_set_flag, ast_test_flag, ast_udptl_get_peer(), sip_pvt::callid, FALSE, sip_pvt::flags, sip_pvt::lastrtprx, sip_pvt::lastrtptx, sip_pvt::ourip, sip_pvt::pendinginvite, SIP_GOTREFER, SIP_NEEDREINVITE, SIP_PENDINGBYE, sip_pvt_lock, sip_pvt_unlock, ast_channel::tech_pvt, transmit_reinvite_with_sdp(), TRUE, and sip_pvt::udptlredirip.

{
   struct sip_pvt *p;
   
   p = chan->tech_pvt;
   if (!p)
      return -1;
   sip_pvt_lock(p);
   if (udptl)
      ast_udptl_get_peer(udptl, &p->udptlredirip);
   else
      memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
   if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
      if (!p->pendinginvite) {
         ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
         transmit_reinvite_with_sdp(p, TRUE, FALSE);
      } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
         ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
         ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
      }
   }
   /* Reset lastrtprx timer */
   p->lastrtprx = p->lastrtptx = time(NULL);
   sip_pvt_unlock(p);
   return 0;
}
static char * sip_show_channel ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Show details of one active dialog.

Definition at line 16992 of file chan_sip.c.

References sip_pvt::allowtransfer, ao2_iterator_destroy(), ao2_iterator_init(), ao2_t_iterator_next, ao2_t_ref, ast_cli_args::argc, ast_cli_args::argv, ARRAY_LEN, ast_cli(), ast_getformatname_multiple(), ast_inet_ntoa(), ast_strlen_zero(), ast_test_flag, sip_pvt::callid, sip_pvt::capability, sip_pvt::cid_num, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, cli_yesno(), ast_cli_entry::command, complete_sipch(), dtmfmode2str(), ast_cli_args::fd, sip_pvt::flags, sip_route::hop, cfsip_options::id, sip_pvt::jointcapability, sip_pvt::lastmsg, sip_request::len, ast_cli_args::line, sip_pvt::maxcallbitrate, ast_cli_args::n, ast_channel::name, nat2str(), ast_channel::nativeformats, sip_pvt::needdestroy, sip_pvt::noncodeccapability, NONE, sip_pvt::ourip, sip_pvt::owner, sip_pvt::peercapability, sip_pvt::peername, ast_cli_args::pos, sip_pvt::recv, sip_pvt::redirip, sip_pvt::route, sip_pvt::sa, SIP_DTMF, SIP_NAT, sip_options, SIP_OUTGOING, SIP_PROMISCREDIR, sip_pvt_lock, sip_pvt_unlock, SIPBUFSIZE, sip_pvt::sipoptions, sip_st_dlg::st_active, sip_st_dlg::st_active_peer_ua, sip_st_dlg::st_cached_max_se, sip_st_dlg::st_cached_min_se, sip_st_dlg::st_cached_mode, sip_st_dlg::st_cached_ref, sip_st_dlg::st_expirys, sip_st_dlg::st_interval, sip_st_dlg::st_ref, sip_st_dlg::st_schedid, sip_pvt::stimer, stmode2str(), strefresher2str(), sip_pvt::subscribed, subscription_type2str(), sip_pvt::tag, cfsip_options::text, sip_pvt::theirtag, transfermode2str(), TRUE, sip_pvt::udptl, sip_pvt::uri, ast_cli_entry::usage, sip_pvt::useragent, sip_pvt::username, sip_pvt::vrtp, and ast_cli_args::word.

{
   struct sip_pvt *cur;
   size_t len;
   int found = 0;
   struct ao2_iterator i;

   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show channel";
      e->usage =
         "Usage: sip show channel <call-id>\n"
         "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
      return NULL;
   case CLI_GENERATE:
      return complete_sipch(a->line, a->word, a->pos, a->n);
   }

   if (a->argc != 4)
      return CLI_SHOWUSAGE;
   len = strlen(a->argv[3]);
   
   i = ao2_iterator_init(dialogs, 0);
   while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
      sip_pvt_lock(cur);

      if (!strncasecmp(cur->callid, a->argv[3], len)) {
         char formatbuf[SIPBUFSIZE/2];
         ast_cli(a->fd, "\n");
         if (cur->subscribed != NONE)
            ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
         else
            ast_cli(a->fd, "  * SIP Call\n");
         ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
         ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
         ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
         ast_cli(a->fd, "  Our Codec Capability:   %d\n", cur->capability);
         ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
         ast_cli(a->fd, "  Their Codec Capability:   %d\n", cur->peercapability);
         ast_cli(a->fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
         ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
         ast_cli(a->fd, "  T.38 support            %s\n", cli_yesno(cur->udptl != NULL));
         ast_cli(a->fd, "  Video support           %s\n", cli_yesno(cur->vrtp != NULL));
         ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
         ast_cli(a->fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
         ast_cli(a->fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
         ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
         ast_cli(a->fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
         ast_cli(a->fd, "  Audio IP:               %s %s\n", ast_inet_ntoa(cur->redirip.sin_addr.s_addr ? cur->redirip.sin_addr : cur->ourip.sin_addr), cur->redirip.sin_addr.s_addr ? "(Outside bridge)" : "(local)" );
         ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
         ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
         ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
         if (!ast_strlen_zero(cur->username))
            ast_cli(a->fd, "  Username:               %s\n", cur->username);
         if (!ast_strlen_zero(cur->peername))
            ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
         if (!ast_strlen_zero(cur->uri))
            ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
         if (!ast_strlen_zero(cur->cid_num))
            ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
         ast_cli(a->fd, "  Need Destroy:           %s\n", cli_yesno(cur->needdestroy));
         ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
         ast_cli(a->fd, "  Promiscuous Redir:      %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
         ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
         ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
         ast_cli(a->fd, "  SIP Options:            ");
         if (cur->sipoptions) {
            int x;
            for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
               if (cur->sipoptions & sip_options[x].id)
                  ast_cli(a->fd, "%s ", sip_options[x].text);
            }
            ast_cli(a->fd, "\n");
         } else
            ast_cli(a->fd, "(none)\n");

         if (!cur->stimer)
            ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
         else {
            ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
            if (cur->stimer->st_active == TRUE) {
               ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
               ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
               ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
               ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
               ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
               ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
               ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
               ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
               ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
            }
         }

         ast_cli(a->fd, "\n\n");

         found++;
      }

      sip_pvt_unlock(cur);

      ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
   }
   ao2_iterator_destroy(&i);

   if (!found) 
      ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);

   return CLI_SUCCESS;
}
static char* sip_show_channels ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

CLI for show channels or subscriptions. This is a new-style CLI handler so a single function contains the prototype for the function, the 'generator' to produce multiple entries in case it is required, and the actual handler for the command.

Definition at line 16813 of file chan_sip.c.

References ao2_t_callback, ast_cli_args::argc, ast_cli_entry::args, ast_cli_args::argv, ast_cli(), CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, ESS, ast_cli_args::fd, __show_chan_arg::fd, FORMAT2, FORMAT3, __show_chan_arg::numchans, OBJ_NODATA, show_channels_cb(), __show_chan_arg::subscriptions, and ast_cli_entry::usage.

{
   struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };


   if (cmd == CLI_INIT) {
      e->command = "sip show {channels|subscriptions}";
      e->usage =
         "Usage: sip show channels\n"
         "       Lists all currently active SIP calls (dialogs).\n"
         "Usage: sip show subscriptions\n"
         "       Lists active SIP subscriptions.\n";
      return NULL;
   } else if (cmd == CLI_GENERATE)
      return NULL;

   if (a->argc != e->args)
      return CLI_SHOWUSAGE;
   arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
   if (!arg.subscriptions)
      ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
   else
      ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");

   /* iterate on the container and invoke the callback on each item */
   ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
   
   /* print summary information */
   ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
      (arg.subscriptions ? "subscription" : "dialog"),
      ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
   return CLI_SUCCESS;
#undef FORMAT
#undef FORMAT2
#undef FORMAT3
}
static char * sip_show_channelstats ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

SIP show channelstats CLI (main function)

Definition at line 16468 of file chan_sip.c.

References ao2_t_callback, ast_cli_args::argc, ast_cli(), CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, __show_chan_arg::fd, FORMAT2, __show_chan_arg::numchans, OBJ_NODATA, show_chanstats_cb(), and ast_cli_entry::usage.

{
   struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };

   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show channelstats";
      e->usage =
         "Usage: sip show channelstats\n"
         "       Lists all currently active SIP channel's RTCP statistics.\n"
         "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }

   if (a->argc != 3)
      return CLI_SHOWUSAGE;

   ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
   /* iterate on the container and invoke the callback on each item */
   ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
   ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : ""); 
   return CLI_SUCCESS;
}
static char * sip_show_domains ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

CLI command to list local domains.

Definition at line 15760 of file chan_sip.c.

References ast_cli(), AST_LIST_EMPTY, AST_LIST_LOCK, AST_LIST_TRAVERSE, AST_LIST_UNLOCK, CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, domain::context, domain::domain, domain_mode_to_text(), ast_cli_args::fd, FORMAT, domain::mode, S_OR, and ast_cli_entry::usage.

{
   struct domain *d;
#define FORMAT "%-40.40s %-20.20s %-16.16s\n"

   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show domains";
      e->usage =
         "Usage: sip show domains\n"
         "       Lists all configured SIP local domains.\n"
         "       Asterisk only responds to SIP messages to local domains.\n";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }

   if (AST_LIST_EMPTY(&domain_list)) {
      ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
      return CLI_SUCCESS;
   } else {
      ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
      AST_LIST_LOCK(&domain_list);
      AST_LIST_TRAVERSE(&domain_list, d, list)
         ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
            domain_mode_to_text(d->mode));
      AST_LIST_UNLOCK(&domain_list);
      ast_cli(a->fd, "\n");
      return CLI_SUCCESS;
   }
}
static char * sip_show_history ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Show history details of one dialog.

Definition at line 17103 of file chan_sip.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_t_iterator_next, ao2_t_ref, ast_cli_args::argc, ast_cli_args::argv, ast_cli(), AST_LIST_TRAVERSE, sip_pvt::callid, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, complete_sip_show_history(), sip_history::event, ast_cli_args::fd, sip_pvt::history, sip_request::len, ast_cli_args::line, ast_cli_args::n, NONE, ast_cli_args::pos, sip_pvt_lock, sip_pvt_unlock, sip_pvt::subscribed, ast_cli_entry::usage, and ast_cli_args::word.

{
   struct sip_pvt *cur;
   size_t len;
   int found = 0;
   struct ao2_iterator i;

   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show history";
      e->usage =
         "Usage: sip show history <call-id>\n"
         "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
      return NULL;
   case CLI_GENERATE:
      return complete_sip_show_history(a->line, a->word, a->pos, a->n);
   }

   if (a->argc != 4)
      return CLI_SHOWUSAGE;

   if (!recordhistory)
      ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");

   len = strlen(a->argv[3]);

   i = ao2_iterator_init(dialogs, 0);
   while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
      sip_pvt_lock(cur);
      if (!strncasecmp(cur->callid, a->argv[3], len)) {
         struct sip_history *hist;
         int x = 0;

         ast_cli(a->fd, "\n");
         if (cur->subscribed != NONE)
            ast_cli(a->fd, "  * Subscription\n");
         else
            ast_cli(a->fd, "  * SIP Call\n");
         if (cur->history)
            AST_LIST_TRAVERSE(cur->history, hist, list)
               ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
         if (x == 0)
            ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
         found++;
      }
      sip_pvt_unlock(cur);
      ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
   }
   ao2_iterator_destroy(&i);

   if (!found) 
      ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);

   return CLI_SUCCESS;
}
static char * sip_show_inuse ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

CLI Command to show calls within limits set by call_limit.

Definition at line 14862 of file chan_sip.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_lock(), ao2_t_iterator_next, ao2_unlock(), ast_cli_args::argc, ast_cli_args::argv, ast_cli(), ast_copy_string(), sip_peer::call_limit, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, FALSE, ast_cli_args::fd, FORMAT, FORMAT2, sip_peer::inRinging, sip_peer::inUse, sip_peer::name, sip_peer::onHold, TRUE, unref_peer(), and ast_cli_entry::usage.

{
#define FORMAT "%-25.25s %-15.15s %-15.15s \n"
#define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
   char ilimits[40];
   char iused[40];
   int showall = FALSE;
   struct ao2_iterator i;
   struct sip_peer *peer;
   
   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show inuse";
      e->usage =
         "Usage: sip show inuse [all]\n"
         "       List all SIP devices usage counters and limits.\n"
         "       Add option \"all\" to show all devices, not only those with a limit.\n";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }

   if (a->argc < 3) 
      return CLI_SHOWUSAGE;

   if (a->argc == 4 && !strcmp(a->argv[3], "all")) 
      showall = TRUE;
   
   ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");

   i = ao2_iterator_init(peers, 0);
   while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
      ao2_lock(peer);
      if (peer->call_limit)
         snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
      else 
         ast_copy_string(ilimits, "N/A", sizeof(ilimits));
      snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
      if (showall || peer->call_limit)
         ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
      ao2_unlock(peer);
      unref_peer(peer, "toss iterator pointer");
   }
   ao2_iterator_destroy(&i);

   return CLI_SUCCESS;
#undef FORMAT
#undef FORMAT2
}
static char * sip_show_mwi ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Definition at line 16697 of file chan_sip.c.

References ast_cli(), ASTOBJ_CONTAINER_TRAVERSE, ASTOBJ_RDLOCK, ASTOBJ_UNLOCK, CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, FORMAT, STANDARD_SIP_PORT, submwil, and ast_cli_entry::usage.

{
#define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
   char host[80];
   
   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show mwi";
      e->usage =
         "Usage: sip show mwi\n"
         "       Provides a list of MWI subscriptions and status.\n";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }
   
   ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
   
   ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
      ASTOBJ_RDLOCK(iterator);
      snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
      ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
      ASTOBJ_UNLOCK(iterator);
   } while(0));

   return CLI_SUCCESS;
#undef FORMAT
}
static char * sip_show_objects ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

List all allocated SIP Objects (realtime or static)

Definition at line 15445 of file chan_sip.c.

References ao2_t_callback, ast_cli_args::argc, ast_cli(), ASTOBJ_CONTAINER_DUMP, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, dialog_dump_func(), ast_cli_args::fd, OBJ_NODATA, peer_dump_func(), regl, and ast_cli_entry::usage.

{
   char tmp[256];
   
   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show objects";
      e->usage =
         "Usage: sip show objects\n"
         "       Lists status of known SIP objects\n";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }  

   if (a->argc != 3)
      return CLI_SHOWUSAGE;
   ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
   ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
   ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
   ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
   ast_cli(a->fd, "-= Dialog objects:\n\n");
   ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
   return CLI_SUCCESS;
}
static char * sip_show_peer ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Show one peer in detail.

Definition at line 15821 of file chan_sip.c.

References _sip_show_peer(), ast_cli_args::argc, ast_cli_args::argv, CLI_GENERATE, CLI_INIT, ast_cli_entry::command, complete_sip_show_peer(), ast_cli_args::fd, ast_cli_args::line, ast_cli_args::n, ast_cli_args::pos, ast_cli_entry::usage, and ast_cli_args::word.

{
   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show peer";
      e->usage =
         "Usage: sip show peer <name> [load]\n"
         "       Shows all details on one SIP peer and the current status.\n"
         "       Option \"load\" forces lookup of peer in realtime storage.\n";
      return NULL;
   case CLI_GENERATE:
      return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
   }
   return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
}
static char * sip_show_peers ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

CLI Show Peers command.

Definition at line 15221 of file chan_sip.c.

References _sip_show_peers(), ast_cli_args::argc, ast_cli_args::argv, CLI_GENERATE, CLI_INIT, ast_cli_entry::command, ast_cli_args::fd, and ast_cli_entry::usage.

{
   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show peers";
      e->usage =
         "Usage: sip show peers [like <pattern>]\n"
         "       Lists all known SIP peers.\n"
         "       Optional regular expression pattern is used to filter the peer list.\n";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }

   return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
}
static char * sip_show_registry ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Show SIP Registry (registrations with other SIP proxies.

Definition at line 16326 of file chan_sip.c.

References ast_cli_args::argc, ast_cli(), ast_localtime(), ast_strftime(), ASTOBJ_CONTAINER_TRAVERSE, ASTOBJ_RDLOCK, ASTOBJ_UNLOCK, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, FORMAT, FORMAT2, regl, regstate2str(), STANDARD_SIP_PORT, and ast_cli_entry::usage.

{
#define FORMAT2 "%-30.30s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
#define FORMAT  "%-30.30s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
   char host[80];
   char tmpdat[256];
   struct ast_tm tm;
   int counter = 0;

   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show registry";
      e->usage =
         "Usage: sip show registry\n"
         "       Lists all registration requests and status.\n";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }

   if (a->argc != 3)
      return CLI_SHOWUSAGE;
   ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
   
   ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
      ASTOBJ_RDLOCK(iterator);
      snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
      if (iterator->regtime.tv_sec) {
         ast_localtime(&iterator->regtime, &tm, NULL);
         ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
      } else 
         tmpdat[0] = '\0';
      ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
      ASTOBJ_UNLOCK(iterator);
      counter++;
   } while(0));
   ast_cli(a->fd, "%d SIP registrations.\n", counter);
   return CLI_SUCCESS;
#undef FORMAT
#undef FORMAT2
}
static char * sip_show_sched ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Definition at line 16283 of file chan_sip.c.

References __sip_autodestruct(), ast_cli(), ast_sched_report(), ast_str_alloca, auto_congest(), CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, expire_register(), ast_cli_args::fd, retrans_pkt(), sip_poke_noanswer(), sip_poke_peer_s(), sip_reg_timeout(), sip_reinvite_retry(), sip_reregister(), and ast_cli_entry::usage.

{
   struct ast_str *cbuf;
   struct ast_cb_names cbnames = {9, { "retrans_pkt",
                                        "__sip_autodestruct",
                                        "expire_register",
                                        "auto_congest",
                                        "sip_reg_timeout",
                                        "sip_poke_peer_s",
                                        "sip_poke_noanswer",
                                        "sip_reregister",
                                        "sip_reinvite_retry"},
                           { retrans_pkt,
                                     __sip_autodestruct,
                                     expire_register,
                                     auto_congest,
                                     sip_reg_timeout,
                                     sip_poke_peer_s,
                                     sip_poke_noanswer,
                                     sip_reregister,
                                     sip_reinvite_retry}};
   
   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show sched";
      e->usage =
         "Usage: sip show sched\n"
         "       Shows stats on what's in the sched queue at the moment\n";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }

   cbuf = ast_str_alloca(2048);

   ast_cli(a->fd, "\n");
   ast_sched_report(sched, &cbuf, &cbnames);
   ast_cli(a->fd, "%s", cbuf->str);

   return CLI_SUCCESS;
}
static char * sip_show_settings ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

List global settings for the SIP channel.

Definition at line 16497 of file chan_sip.c.

References sip_settings::allow_external_domains, sip_settings::allowguest, sip_settings::allowtransfer, sip_settings::alwaysauthreject, ast_cli_args::argc, ast_check_realtime(), ast_cli(), ast_getformatname_multiple(), ast_inet_ntoa(), AST_JB_ENABLED, AST_JB_FORCED, AST_JB_LOG, AST_LIST_EMPTY, ast_strlen_zero(), ast_test_flag, ast_tos2str(), sip_settings::autocreatepeer, bindaddr, buf, sip_settings::callevents, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, cli_yesno(), ast_cli_entry::command, sip_settings::compactheaders, sip_settings::default_context, default_prefs, default_tls_cfg, sip_settings::directrtpsetup, dtmfmode2str(), ast_tls_config::enabled, externip, FALSE, faxec2str(), ast_cli_args::fd, sip_proxy::force, get_transport(), get_transport_list(), global_jbconf, IGNORE_CONTEXT, sip_settings::ignore_regexpire, ast_jb_conf::impl, ast_tcptls_session_args::local_address, ast_jb_conf::max_size, msg, sip_proxy::name, nat2str(), ast_ha::netaddr, ast_ha::netmask, ast_ha::next, sip_settings::notifycid, sip_settings::notifyhold, sip_settings::notifyringing, sip_settings::outboundproxy, sip_settings::pedanticsipchecking, sip_settings::peer_rtupdate, prefix, print_codec_to_cli(), sip_settings::realm, sip_settings::regextenonqualify, ast_jb_conf::resync_threshold, sip_settings::rtautoclear, sip_settings::rtsave_sysname, S_OR, sip_cfg, SIP_DTMF, SIP_NAT, SIP_PAGE2_ALLOWOVERLAP, SIP_PAGE2_ALLOWSUBSCRIBE, SIP_PAGE2_FORWARD_LOOP_DETECTED, SIP_PAGE2_IGNORESDPVERSION, SIP_PAGE2_RFC2833_COMPENSATE, SIP_PAGE2_RTAUTOCLEAR, SIP_PAGE2_RTCACHEFRIENDS, SIP_PAGE2_T38SUPPORT, SIP_PAGE2_TEXTSUPPORT, SIP_PAGE2_VIDEOSUPPORT, SIP_PROG_INBAND, SIP_PROG_INBAND_NEVER, SIP_PROG_INBAND_NO, SIP_PROMISCREDIR, SIP_USECLIENTCODE, SIP_USEREQPHONE, SIPBUFSIZE, sip_settings::srvlookup, stmode2str(), strefresher2str(), stunaddr, transfermode2str(), and ast_cli_entry::usage.

{
   int realtimepeers;
   int realtimeregs;
   char codec_buf[SIPBUFSIZE];
   const char *msg;  /* temporary msg pointer */

   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show settings";
      e->usage =
         "Usage: sip show settings\n"
         "       Provides detailed list of the configuration of the SIP channel.\n";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }


   realtimepeers = ast_check_realtime("sippeers");
   realtimeregs = ast_check_realtime("sipregs");

   if (a->argc != 3)
      return CLI_SHOWUSAGE;
   ast_cli(a->fd, "\n\nGlobal Settings:\n");
   ast_cli(a->fd, "----------------\n");
   ast_cli(a->fd, "  UDP SIP Port:           %d\n", ntohs(bindaddr.sin_port));
   ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_inet_ntoa(bindaddr.sin_addr));
   ast_cli(a->fd, "  TCP SIP Port:           ");
   if (sip_tcp_desc.local_address.sin_family == AF_INET) {
      ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
      ast_cli(a->fd, "  TCP Bindaddress:        %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
   } else {
      ast_cli(a->fd, "Disabled\n");
   }
   ast_cli(a->fd, "  TLS SIP Port:           ");
   if (default_tls_cfg.enabled != FALSE) {
      ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
      ast_cli(a->fd, "  TLS Bindaddress:        %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
   } else {
      ast_cli(a->fd, "Disabled\n");
   }
   ast_cli(a->fd, "  Videosupport:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
   ast_cli(a->fd, "  Textsupport:            %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
   ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
   ast_cli(a->fd, "  AutoCreate Peer:        %s\n", cli_yesno(sip_cfg.autocreatepeer));
   ast_cli(a->fd, "  Match Auth Username:    %s\n", cli_yesno(global_match_auth_username));
   ast_cli(a->fd, "  Allow unknown access:   %s\n", cli_yesno(sip_cfg.allowguest));
   ast_cli(a->fd, "  Allow subscriptions:    %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
   ast_cli(a->fd, "  Allow overlap dialing:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
   ast_cli(a->fd, "  Allow promsic. redir:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
   ast_cli(a->fd, "  Enable call counters:   %s\n", cli_yesno(global_callcounter));
   ast_cli(a->fd, "  SIP domain support:     %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
   ast_cli(a->fd, "  Realm. auth:            %s\n", cli_yesno(authl != NULL));
   ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
   ast_cli(a->fd, "  Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
   ast_cli(a->fd, "  URI user is phone no:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
   ast_cli(a->fd, "  Always auth rejects:    %s\n", cli_yesno(sip_cfg.alwaysauthreject));
   ast_cli(a->fd, "  Direct RTP setup:       %s\n", cli_yesno(sip_cfg.directrtpsetup));
   ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
   ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
   ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
   ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(global_regcontext, "(not set)"));
   ast_cli(a->fd, "  Regexten on Qualify:    %s\n", cli_yesno(sip_cfg.regextenonqualify));
   ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
   ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
   ast_cli(a->fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
   ast_cli(a->fd, "  Call Events:            %s\n", sip_cfg.callevents ? "On" : "Off");
   ast_cli(a->fd, "  Auth. Failure Events:   %s\n", global_authfailureevents ? "On" : "Off");

   ast_cli(a->fd, "  T.38 support:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
   ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
   ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);

   if (!realtimepeers && !realtimeregs)
      ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
   else
      ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
   ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
   ast_cli(a->fd, "\nNetwork QoS Settings:\n");
   ast_cli(a->fd, "---------------------------\n");
   ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
   ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
   ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
   ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
   ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
   ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
   ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
   ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
   ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
   ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
   ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
   ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
   ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
   ast_cli(a->fd, "  Jitterbuffer log:       %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));

   ast_cli(a->fd, "\nNetwork Settings:\n");
   ast_cli(a->fd, "---------------------------\n");
   /* determine if/how SIP address can be remapped */
   if (localaddr == NULL)
      msg = "Disabled, no localnet list";
   else if (externip.sin_addr.s_addr == 0)
      msg = "Disabled, externip is 0.0.0.0";
   else if (stunaddr.sin_addr.s_addr != 0)
      msg = "Enabled using STUN";
   else if (!ast_strlen_zero(externhost))
      msg = "Enabled using externhost";
   else
      msg = "Enabled using externip";
   ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
   ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
   ast_cli(a->fd, "  Externip:               %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
   ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
   {
      struct ast_ha *d;
      const char *prefix = "Localnet:";
      char buf[INET_ADDRSTRLEN]; /* need to print two addresses */

      for (d = localaddr; d ; prefix = "", d = d->next) {
         ast_cli(a->fd, "  %-24s%s/%s\n",
             prefix, ast_inet_ntoa(d->netaddr),
             inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
      }
   }
   ast_cli(a->fd, "  STUN server:            %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
 
   ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
   ast_cli(a->fd, "---------------------------\n");
   ast_cli(a->fd, "  Codecs:                 ");
   ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
   ast_cli(a->fd, "%s\n", codec_buf);
   ast_cli(a->fd, "  Codec Order:            ");
   print_codec_to_cli(a->fd, &default_prefs);
   ast_cli(a->fd, "\n");
   ast_cli(a->fd, "  Relax DTMF:             %s\n", cli_yesno(global_relaxdtmf));
   ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
   ast_cli(a->fd, "  Compact SIP headers:    %s\n", cli_yesno(sip_cfg.compactheaders));
   ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
   ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
   ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
   ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
   ast_cli(a->fd, "  DNS SRV lookup:         %s\n", cli_yesno(sip_cfg.srvlookup));
   ast_cli(a->fd, "  Pedantic SIP support:   %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
   ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
   ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
   ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
   ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
   ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
   ast_cli(a->fd, "  Notify ringing state:   %s\n", cli_yesno(sip_cfg.notifyringing));
   if (sip_cfg.notifyringing) {
      ast_cli(a->fd, "    Include CID:          %s%s\n",
            cli_yesno(sip_cfg.notifycid),
            sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
   }
   ast_cli(a->fd, "  Notify hold state:      %s\n", cli_yesno(sip_cfg.notifyhold));
   ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
   ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
   ast_cli(a->fd, "  Auto-Framing:           %s\n", cli_yesno(global_autoframing));
   ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
                     sip_cfg.outboundproxy.force ? "(forced)" : "");
   ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
   ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
   ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
   ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
   ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
   ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
   ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
   ast_cli(a->fd, "  No premature media:     %s\n", global_prematuremediafilter ? "Yes" : "No");

   ast_cli(a->fd, "\nDefault Settings:\n");
   ast_cli(a->fd, "-----------------\n");
   ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports)); 
   ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
   ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
   ast_cli(a->fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
   ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
   ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
   ast_cli(a->fd, "  Use ClientCode:         %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
   ast_cli(a->fd, "  Progress inband:        %s\n", (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NO) ? "No" : "Yes" );
   ast_cli(a->fd, "  Language:               %s\n", default_language);
   ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
   ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
   ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
   ast_cli(a->fd, "  Forward Detected Loops: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
   
   if (realtimepeers || realtimeregs) {
      ast_cli(a->fd, "\nRealtime SIP Settings:\n");
      ast_cli(a->fd, "----------------------\n");
      ast_cli(a->fd, "  Realtime Peers:         %s\n", cli_yesno(realtimepeers));
      ast_cli(a->fd, "  Realtime Regs:          %s\n", cli_yesno(realtimeregs));
      ast_cli(a->fd, "  Cache Friends:          %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
      ast_cli(a->fd, "  Update:                 %s\n", cli_yesno(sip_cfg.peer_rtupdate));
      ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", cli_yesno(sip_cfg.ignore_regexpire));
      ast_cli(a->fd, "  Save sys. name:         %s\n", cli_yesno(sip_cfg.rtsave_sysname));
      ast_cli(a->fd, "  Auto Clear:             %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
   }
   ast_cli(a->fd, "\n----\n");
   return CLI_SUCCESS;
}
static char* sip_show_tcp ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Show active TCP connections.

Definition at line 15033 of file chan_sip.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_t_iterator_next, ao2_t_ref, ast_cli_args::argc, ast_cli(), ast_inet_ntoa(), CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_tcptls_session_instance::client, ast_cli_entry::command, ast_cli_args::fd, FORMAT, FORMAT2, get_transport(), ast_tcptls_session_instance::remote_address, sip_threadinfo::tcptls_session, sip_threadinfo::type, and ast_cli_entry::usage.

{
   struct sip_threadinfo *th;
   struct ao2_iterator i;

#define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
#define FORMAT  "%-30.30s %-6d %-9.9s %-6.6s\n"

   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show tcp";
      e->usage =
         "Usage: sip show tcp\n"
         "       Lists all active TCP/TLS sessions.\n";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }

   if (a->argc != 3)
      return CLI_SHOWUSAGE;

   ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
   i = ao2_iterator_init(threadt, 0);
   while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
      ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr), 
         ntohs(th->tcptls_session->remote_address.sin_port), 
         get_transport(th->type), 
         (th->tcptls_session->client ? "Client" : "Server"));
      ao2_t_ref(th, -1, "decrement ref from iterator");
   }
   ao2_iterator_destroy(&i);
   return CLI_SUCCESS;
#undef FORMAT
#undef FORMAT2
}
static char* sip_show_user ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Show one user in detail.

Definition at line 16208 of file chan_sip.c.

References sip_peer::accountcode, sip_peer::allowtransfer, sip_peer::amaflags, ao2_lock(), ao2_unlock(), ast_cli_args::argc, ast_cli_args::argv, ast_callerid_merge(), ast_cdr_flags2str(), ast_cli(), ast_describe_caller_presentation(), ast_strlen_zero(), sip_peer::autoframing, sip_peer::call_limit, sip_peer::callgroup, sip_peer::callingpres, sip_peer::chanvars, sip_peer::cid_name, sip_peer::cid_num, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, cli_yesno(), ast_cli_entry::command, complete_sip_show_user(), sip_peer::context, FALSE, ast_cli_args::fd, find_peer(), FINDUSERS, sip_peer::ha, sip_peer::language, ast_cli_args::line, sip_peer::maxcallbitrate, sip_peer::md5secret, ast_cli_args::n, ast_variable::name, sip_peer::name, ast_variable::next, sip_peer::pickupgroup, ast_cli_args::pos, sip_peer::prefs, print_codec_to_cli(), print_group(), sip_peer::secret, sip_st_cfg::st_max_se, sip_st_cfg::st_min_se, sip_st_cfg::st_mode_oper, sip_st_cfg::st_ref, sip_peer::stimer, stmode2str(), strefresher2str(), transfermode2str(), TRUE, unref_peer(), ast_cli_entry::usage, user, ast_variable::value, and ast_cli_args::word.

{
   char cbuf[256];
   struct sip_peer *user;
   struct ast_variable *v;
   int load_realtime;

   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show user";
      e->usage =
         "Usage: sip show user <name> [load]\n"
         "       Shows all details on one SIP user and the current status.\n"
         "       Option \"load\" forces lookup of peer in realtime storage.\n";
      return NULL;
   case CLI_GENERATE:
      return complete_sip_show_user(a->line, a->word, a->pos, a->n);
   }

   if (a->argc < 4)
      return CLI_SHOWUSAGE;

   /* Load from realtime storage? */
   load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;

   if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
      ao2_lock(user);
      ast_cli(a->fd, "\n\n");
      ast_cli(a->fd, "  * Name       : %s\n", user->name);
      ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
      ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
      ast_cli(a->fd, "  Context      : %s\n", user->context);
      ast_cli(a->fd, "  Language     : %s\n", user->language);
      if (!ast_strlen_zero(user->accountcode))
         ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
      ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
      ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
      ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
      ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
      ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
      ast_cli(a->fd, "  Callgroup    : ");
      print_group(a->fd, user->callgroup, 0);
      ast_cli(a->fd, "  Pickupgroup  : ");
      print_group(a->fd, user->pickupgroup, 0);
      ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
      ast_cli(a->fd, "  ACL          : %s\n", cli_yesno(user->ha != NULL));
      ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
      ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
      ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
      ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);

      ast_cli(a->fd, "  Codec Order  : (");
      print_codec_to_cli(a->fd, &user->prefs);
      ast_cli(a->fd, ")\n");

      ast_cli(a->fd, "  Auto-Framing:  %s \n", cli_yesno(user->autoframing));
      if (user->chanvars) {
         ast_cli(a->fd, "  Variables    :\n");
         for (v = user->chanvars ; v ; v = v->next)
            ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
      }

      ast_cli(a->fd, "\n");

      ao2_unlock(user);
      unref_peer(user, "sip show user");
   } else {
      ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
      ast_cli(a->fd, "\n");
   }

   return CLI_SUCCESS;
}
static char* sip_show_users ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

CLI Command 'SIP Show Users'.

Definition at line 15071 of file chan_sip.c.

References sip_peer::accountcode, ao2_iterator_destroy(), ao2_iterator_init(), ao2_iterator_next, ao2_lock(), ao2_unlock(), ast_cli_args::argc, ast_cli_args::argv, ast_cli(), ast_test_flag, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, cli_yesno(), ast_cli_entry::command, sip_peer::context, FALSE, ast_cli_args::fd, sip_peer::flags, FORMAT, sip_peer::ha, sip_peer::name, nat2str(), sip_peer::secret, SIP_NAT, SIP_TYPE_USER, TRUE, sip_peer::type, unref_peer(), ast_cli_entry::usage, and user.

{
   regex_t regexbuf;
   int havepattern = FALSE;
   struct ao2_iterator user_iter;
   struct sip_peer *user;

#define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"

   switch (cmd) {
   case CLI_INIT:
      e->command = "sip show users";
      e->usage =
         "Usage: sip show users [like <pattern>]\n"
         "       Lists all known SIP users.\n"
         "       Optional regular expression pattern is used to filter the user list.\n";
      return NULL;
   case CLI_GENERATE:
      return NULL;
   }

   switch (a->argc) {
   case 5:
      if (!strcasecmp(a->argv[3], "like")) {
         if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
            return CLI_SHOWUSAGE;
         havepattern = TRUE;
      } else
         return CLI_SHOWUSAGE;
   case 3:
      break;
   default:
      return CLI_SHOWUSAGE;
   }

   ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");

   user_iter = ao2_iterator_init(peers, 0);
   while ((user = ao2_iterator_next(&user_iter))) {
      ao2_lock(user);
      if (!(user->type & SIP_TYPE_USER)) {
         ao2_unlock(user);
         unref_peer(user, "sip show users");
         continue;
      }

      if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
         ao2_unlock(user);
         unref_peer(user, "sip show users");
         continue;
      }

      ast_cli(a->fd, FORMAT, user->name, 
         user->secret, 
         user->accountcode,
         user->context,
         cli_yesno(user->ha != NULL),
         nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
      ao2_unlock(user);
      unref_peer(user, "sip show users");
   }
   ao2_iterator_destroy(&user_iter);

   if (havepattern)
      regfree(&regexbuf);

   return CLI_SUCCESS;
#undef FORMAT
}
static int sip_sipredirect ( struct sip_pvt p,
const char *  dest 
) [static]

Transfer call before connect with a 302 redirect.

Note:
Called by the transfer() dialplan application through the sip_transfer() pbx interface function if the call is in ringing state
Todo:
Fix this function so that we wait for reply to the REFER and react to errors, denials or other issues the other end might have.

Definition at line 26236 of file chan_sip.c.

References ast_copy_string(), ast_log(), ast_strdupa, ast_string_field_build, ast_strlen_zero(), get_header(), sip_pvt::initreq, LOG_ERROR, sip_alreadygone(), sip_scheddestroy(), SIP_TRANS_TIMEOUT, strcasestr(), strsep(), and transmit_response_reliable().

Referenced by sip_transfer().

{
   char *cdest;
   char *extension, *host, *port;
   char tmp[80];

   cdest = ast_strdupa(dest);
   
   extension = strsep(&cdest, "@");
   host = strsep(&cdest, ":");
   port = strsep(&cdest, ":");
   if (ast_strlen_zero(extension)) {
      ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
      return 0;
   }

   /* we'll issue the redirect message here */
   if (!host) {
      char *localtmp;

      ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
      if (ast_strlen_zero(tmp)) {
         ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
         return 0;
      }
      if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) ) 
         && (localtmp = strchr(localtmp, '@'))) {
         char lhost[80], lport[80];

         memset(lhost, 0, sizeof(lhost));
         memset(lport, 0, sizeof(lport));
         localtmp++;
         /* This is okey because lhost and lport are as big as tmp */
         sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
         if (ast_strlen_zero(lhost)) {
            ast_log(LOG_ERROR, "Can't find the host address\n");
            return 0;
         }
         host = ast_strdupa(lhost);
         if (!ast_strlen_zero(lport)) {
            port = ast_strdupa(lport);
         }
      }
   }

   ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
   transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);

   sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
   sip_alreadygone(p);
   /* hangup here */
   return 0;
}
static struct sip_st_dlg * sip_st_alloc ( struct sip_pvt *const  p) [static, read]

Allocate Session-Timers struct w/in dialog.

Definition at line 7373 of file chan_sip.c.

References ast_calloc, ast_log(), LOG_ERROR, sip_st_dlg::st_schedid, and sip_pvt::stimer.

Referenced by handle_request_invite(), and st_get_mode().

{
   struct sip_st_dlg *stp;

   if (p->stimer) {
      ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
      return p->stimer;
   }

   if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
      return NULL;

   p->stimer = stp;

   stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */

   return p->stimer;
}
static int sip_standard_port ( enum sip_transport  type,
int  port 
) [static]

Returns the port to use for this socket.

Parameters:
typeThe type of transport used
portPort we are checking to see if it's the standard port.
Note:
port is expected in host byte order

Definition at line 22694 of file chan_sip.c.

References SIP_TRANSPORT_TLS, STANDARD_SIP_PORT, and STANDARD_TLS_PORT.

Referenced by build_contact(), initreqprep(), and transmit_notify_with_mwi().

{
   if (type & SIP_TRANSPORT_TLS)
      return port == STANDARD_TLS_PORT;
   else
      return port == STANDARD_SIP_PORT;
}
static int sip_subscribe_mwi ( const char *  value,
int  lineno 
) [static]

Parse mwi=> line in sip.conf and add to list.

--- SIP MWI Subscription support

Definition at line 8085 of file chan_sip.c.

References ast_calloc, ast_copy_string(), ast_free, ast_log(), ast_string_field_init, ast_string_field_set, ast_strlen_zero(), ASTOBJ_CONTAINER_LINK, ASTOBJ_INIT, ASTOBJ_UNREF, sip_subscription_mwi::authuser, buf, hostname, LOG_WARNING, mailbox, sip_subscription_mwi::portno, sip_subscription_mwi::resub, secret, sip_parse_host(), sip_subscribe_mwi_destroy(), SIP_TRANSPORT_UDP, submwil, sip_subscription_mwi::transport, and sip_subscription_mwi::username.

Referenced by reload_config().

{
   struct sip_subscription_mwi *mwi;
   int portnum = 0;
   enum sip_transport transport = SIP_TRANSPORT_UDP;
   char buf[256] = "";
   char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
   
   if (!value) {
      return -1;
   }
   
   ast_copy_string(buf, value, sizeof(buf));

   sip_parse_host(buf, lineno, &username, &portnum, &transport);
   
   if ((hostname = strrchr(username, '@'))) {
      *hostname++ = '\0';
   }
   
   if ((secret = strchr(username, ':'))) {
      *secret++ = '\0';
      if ((authuser = strchr(secret, ':'))) {
         *authuser++ = '\0';
      }
   }
   
   if ((mailbox = strchr(hostname, '/'))) {
      *mailbox++ = '\0';
   }

   if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
      ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
      return -1;
   }
   
   if ((porta = strchr(hostname, ':'))) {
      *porta++ = '\0';
      if (!(portnum = atoi(porta))) {
         ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
         return -1;
      }
   }
   
   if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
      return -1;
   }
   
   if (ast_string_field_init(mwi, 256)) {
      ast_free(mwi);
      return -1;
   }
   
   ASTOBJ_INIT(mwi);
   ast_string_field_set(mwi, username, username);
   if (secret) {
      ast_string_field_set(mwi, secret, secret);
   }
   if (authuser) {
      ast_string_field_set(mwi, authuser, authuser);
   }
   ast_string_field_set(mwi, hostname, hostname);
   ast_string_field_set(mwi, mailbox, mailbox);
   mwi->resub = -1;
   mwi->portno = portnum;
   mwi->transport = transport;
   
   ASTOBJ_CONTAINER_LINK(&submwil, mwi);
   ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
   
   return 0;
}
static int sip_subscribe_mwi_do ( const void *  data) [static]

Send a subscription or resubscription for MWI.

Definition at line 11447 of file chan_sip.c.

References __sip_subscribe_mwi_do(), ASTOBJ_UNREF, sip_subscription_mwi::resub, and sip_subscribe_mwi_destroy().

Referenced by handle_response_subscribe(), and sip_send_all_mwi_subscriptions().

{
   struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
   
   if (!mwi) {
      return -1;
   }
   
   mwi->resub = -1;
   __sip_subscribe_mwi_do(mwi);
   ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
   
   return 0;
}
static int sip_t38_abort ( const void *  data) [static]

Called to deny a T38 reinvite if the core does not respond to our request.

Definition at line 20207 of file chan_sip.c.

References change_t38_state(), dialog_unref(), sip_pvt::initreq, sip_pvt_lock, sip_pvt_unlock, T38_DISABLED, sip_pvt::t38id, and transmit_response_reliable().

Referenced by handle_request_invite().

{
   struct sip_pvt *p = (struct sip_pvt *) data;

   sip_pvt_lock(p);
   /* an application may have taken ownership of the T.38 negotiation on this
    * channel while we were waiting to grab the lock... if it did, the scheduler
    * id will have been reset to -1, which is our indication that we do *not*
    * want to abort the negotiation process
    */
   if (p->t38id != -1) {
      change_t38_state(p, T38_DISABLED);
      transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
      p->t38id = -1;
      dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
   }
   sip_pvt_unlock(p);
   return 0;
}
static struct ast_tcptls_session_instance* sip_tcp_locate ( struct sockaddr_in *  s) [static, read]

Find thread for TCP/TLS session (based on IP/Port.

Note:
This function returns an astobj2 reference

Definition at line 22719 of file chan_sip.c.

References ao2_callback, ao2_ref, ao2_t_ref, sip_threadinfo::tcptls_session, and threadinfo_locate_cb().

Referenced by sip_prepare_socket().

{
   struct sip_threadinfo *th;
   struct ast_tcptls_session_instance *tcptls_instance = NULL;

   if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
      tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
      ao2_t_ref(th, -1, "decrement ref from callback");
   }
   return tcptls_instance;
}
static void * sip_tcp_worker_fn ( void *  data) [static]

SIP TCP connection handler.

Definition at line 2916 of file chan_sip.c.

References _sip_tcp_helper_thread(), and sip_request::data.

Referenced by sip_prepare_socket().

{
   struct ast_tcptls_session_instance *tcptls_session = data;

   return _sip_tcp_helper_thread(NULL, tcptls_session);
}
static void sip_tcptls_client_args_destructor ( void *  obj) [static]
static int sip_tcptls_write ( struct ast_tcptls_session_instance tcptls_session,
const void *  buf,
size_t  len 
) [static]

used to indicate to a tcptls thread that data is ready to be written

Definition at line 2858 of file chan_sip.c.

References sip_threadinfo::alert_pipe, ao2_alloc, ao2_lock(), ao2_t_find, ao2_t_ref, ao2_unlock(), AST_LIST_INSERT_TAIL, ast_log(), ast_mutex_lock(), ast_mutex_unlock(), ast_str_create(), ast_str_set(), tcptls_packet::data, errno, ast_tcptls_session_instance::fd, tcptls_packet::len, sip_request::len, ast_tcptls_session_instance::lock, LOG_ERROR, OBJ_POINTER, sip_threadinfo::packet_q, TCPTLS_ALERT_DATA, tcptls_packet_destructor(), sip_threadinfo::tcptls_session, and XMIT_ERROR.

Referenced by __sip_xmit().

{
   int res = len;
   struct sip_threadinfo *th = NULL;
   struct tcptls_packet *packet = NULL;
   struct sip_threadinfo tmp = {
      .tcptls_session = tcptls_session,
   };
   enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;

   if (!tcptls_session) {
      return XMIT_ERROR;
   }

   ast_mutex_lock(&tcptls_session->lock);

   if ((tcptls_session->fd == -1) ||
      !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
      !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
      !(packet->data = ast_str_create(len))) {
      goto tcptls_write_setup_error;
   }

   /* goto tcptls_write_error should _NOT_ be used beyond this point */
   ast_str_set(&packet->data, 0, "%s", (char *) buf);
   packet->len = len;

   /* alert tcptls thread handler that there is a packet to be sent.
    * must lock the thread info object to guarantee control of the
    * packet queue */
   ao2_lock(th);
   if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
      ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
      ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
      packet = NULL;
      res = XMIT_ERROR;
   } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
      AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
   }
   ao2_unlock(th);

   ast_mutex_unlock(&tcptls_session->lock);
   ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
   return res;

tcptls_write_setup_error:
   if (th) {
      ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
   }
   if (packet) {
      ao2_t_ref(packet, -1, "could not allocate packet's data");
   }
   ast_mutex_unlock(&tcptls_session->lock);

   return XMIT_ERROR;
}
static struct sip_threadinfo* sip_threadinfo_create ( struct ast_tcptls_session_instance tcptls_session,
int  transport 
) [static, read]

creates a sip_threadinfo object and links it into the threadt table.

Definition at line 2834 of file chan_sip.c.

References sip_threadinfo::alert_pipe, ao2_alloc, ao2_t_link, ao2_t_ref, ast_log(), errno, LOG_ERROR, sip_threadinfo_destructor(), SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, ast_tcptls_session_instance::ssl, sip_threadinfo::tcptls_session, and sip_threadinfo::type.

Referenced by _sip_tcp_helper_thread(), and sip_prepare_socket().

{
   struct sip_threadinfo *th;

   if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
      return NULL;
   }

   th->alert_pipe[0] = th->alert_pipe[1] = -1;

   if (pipe(th->alert_pipe) == -1) {
      ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
      ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
      return NULL;
   }
   ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
   th->tcptls_session = tcptls_session;
   th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
   ao2_t_link(threadt, th, "Adding new tcptls helper thread");
   ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
   return th;
}
static void sip_threadinfo_destructor ( void *  obj) [static]

Definition at line 2812 of file chan_sip.c.

References sip_threadinfo::alert_pipe, ao2_t_ref, AST_LIST_REMOVE_HEAD, sip_threadinfo::packet_q, and sip_threadinfo::tcptls_session.

Referenced by sip_threadinfo_create().

{
   struct sip_threadinfo *th = obj;
   struct tcptls_packet *packet;
   if (th->alert_pipe[1] > -1) {
      close(th->alert_pipe[0]);
   }
   if (th->alert_pipe[1] > -1) {
      close(th->alert_pipe[1]);
   }
   th->alert_pipe[0] = th->alert_pipe[1] = -1;

   while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
      ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
   }

   if (th->tcptls_session) {
      ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
   }
}
static int sip_transfer ( struct ast_channel ast,
const char *  dest 
) [static]

Transfer SIP call.

Definition at line 6622 of file chan_sip.c.

References ast_channel::_state, AST_STATE_RING, sip_pvt_lock, sip_pvt_unlock, sip_sipredirect(), ast_channel::tech_pvt, and transmit_refer().

{
   struct sip_pvt *p = ast->tech_pvt;
   int res;

   if (dest == NULL) /* functions below do not take a NULL */
      dest = "";
   sip_pvt_lock(p);
   if (ast->_state == AST_STATE_RING)
      res = sip_sipredirect(p, dest);
   else
      res = transmit_refer(p, dest);
   sip_pvt_unlock(p);
   return res;
}
static char * sip_unregister ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Unregister (force expiration) a SIP peer in the registry via CLI.

Note:
This function does not tell the SIP device what's going on, so use it with great care.

Definition at line 16372 of file chan_sip.c.

References ast_cli_args::argc, ast_cli_args::argv, ast_cli(), AST_SCHED_DEL_UNREF, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, complete_sip_unregister(), sip_peer::expire, expire_register(), ast_cli_args::fd, find_peer(), FINDPEERS, ast_cli_args::line, ast_cli_args::n, ast_cli_args::pos, ref_peer(), TRUE, unref_peer(), ast_cli_entry::usage, and ast_cli_args::word.

{
   struct sip_peer *peer;
   int load_realtime = 0;

   switch (cmd) {
   case CLI_INIT:
      e->command = "sip unregister";
      e->usage =
         "Usage: sip unregister <peer>\n"
         "       Unregister (force expiration) a SIP peer from the registry\n";
      return NULL;
   case CLI_GENERATE:
      return complete_sip_unregister(a->line, a->word, a->pos, a->n);
   }
   
   if (a->argc != 3)
      return CLI_SHOWUSAGE;
   
   if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
      if (peer->expire > 0) {
         AST_SCHED_DEL_UNREF(sched, peer->expire,
            unref_peer(peer, "remove register expire ref"));
         expire_register(ref_peer(peer, "ref for expire_register"));
         ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
      } else {
         ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
      }
      unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
   } else {
      ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
   }
   
   return CLI_SUCCESS;
}
static int sip_uri_cmp ( const char *  input1,
const char *  input2 
) [static]

Definition at line 20102 of file chan_sip.c.

References ast_strdupa, S_OR, sip_uri_headers_cmp(), sip_uri_params_cmp(), and strsep().

Referenced by handle_request_invite().

{
   char *uri1 = ast_strdupa(input1);
   char *uri2 = ast_strdupa(input2);
   char *host1;
   char *host2;
   char *params1;
   char *params2;
   char *headers1;
   char *headers2;

   /* Strip off "sip:" from the URI. We know this is present
    * because it was checked back in parse_request()
    */
   strsep(&uri1, ":");
   strsep(&uri2, ":");

   if ((host1 = strchr(uri1, '@'))) {
      *host1++ = '\0';
   }
   if ((host2 = strchr(uri2, '@'))) {
      *host2++ = '\0';
   }

   /* Check for mismatched username and passwords. This is the
    * only case-sensitive comparison of a SIP URI
    */
   if ((host1 && !host2) ||
         (host2 && !host1) ||
         (host1 && host2 && strcmp(uri1, uri2))) {
      return 1;
   }

   if (!host1)
      host1 = uri1;
   if (!host2)
      host2 = uri2;

   /* Strip off the parameters and headers so we can compare
    * host and port
    */

   if ((params1 = strchr(host1, ';'))) {
      *params1++ = '\0';
   }
   if ((params2 = strchr(host2, ';'))) {
      *params2++ = '\0';
   }

   /* Headers come after parameters, but there may be headers without
    * parameters, thus the S_OR
    */
   if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
      *headers1++ = '\0';
   }
   if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
      *headers2++ = '\0';
   }

   /* Now the host/port are properly isolated. We can get by with a string comparison
    * because the SIP URI checking rules have some interesting exceptions that make
    * this possible. I will note 2 in particular
    * 1. hostnames which resolve to the same IP address as well as a hostname and its
    *    IP address are not considered a match with SIP URI's.
    * 2. If one URI specifies a port and the other does not, then the URIs do not match.
    *    This includes if one URI explicitly contains port 5060 and the other implies it
    *    by not having a port specified.
    */

   if (strcasecmp(host1, host2)) {
      return 1;
   }

   /* Headers have easier rules to follow, so do those first */
   if (sip_uri_headers_cmp(headers1, headers2)) {
      return 1;
   }

   /* And now the parameters. Ugh */
   return sip_uri_params_cmp(params1, params2);
}
static int sip_uri_headers_cmp ( const char *  input1,
const char *  input2 
) [static]

helper routine for sip_uri_cmp

This takes the "headers" from two SIP URIs and determines if the URIs match. The rules for headers is simple. If a header appears in one URI, then it must also appear in the other URI. The order in which the headers appear does not matter.

Parameters:
input1Headers from URI 1
input2Headers from URI 2
Returns:
Return 0 if the URIs' headers match, 1 if they do not

Definition at line 20056 of file chan_sip.c.

References ast_strdupa, ast_strlen_zero(), strcasestr(), and strsep().

Referenced by sip_uri_cmp().

{
   char *headers1 = NULL;
   char *headers2 = NULL;
   int zerolength1 = 0;
   int zerolength2 = 0;
   int different = 0;
   char *header1;

   if (ast_strlen_zero(input1)) {
      zerolength1 = 1;
   } else {
      headers1 = ast_strdupa(input1);
   }
   
   if (ast_strlen_zero(input2)) {
      zerolength2 = 1;
   } else {
      headers2 = ast_strdupa(input2);
   }

   if ((zerolength1 && !zerolength2) ||
         (zerolength2 && !zerolength1))
      return 1;

   if (zerolength1 && zerolength2)
      return 0;

   /* At this point, we can definitively state that both inputs are
    * not zero-length. First, one more optimization. If the length
    * of the headers is not equal, then we definitely have no match
    */
   if (strlen(headers1) != strlen(headers2)) {
      return 1;
   }

   for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
      if (!strcasestr(headers2, header1)) {
         different = 1;
         break;
      }
   }

   return different;
}
static int sip_uri_params_cmp ( const char *  input1,
const char *  input2 
) [static]

helper routine for sip_uri_cmp to compare URI parameters

This takes the parameters from two SIP URIs and determines if the URIs match. The rules for parameters *suck*. Here's a breakdown 1. If a parameter appears in both URIs, then they must have the same value in order for the URIs to match 2. If one URI has a user, maddr, ttl, or method parameter, then the other URI must also have that parameter and must have the same value in order for the URIs to match 3. All other headers appearing in only one URI are not considered when determining if URIs match

Parameters:
input1Parameters from URI 1
input2Parameters from URI 2
Return values:
0URIs' parameters match
nonzeroURIs' parameters do not match

Definition at line 19931 of file chan_sip.c.

References ast_strdupa, ast_strlen_zero(), and strsep().

Referenced by sip_uri_cmp().

{
   char *params1 = NULL;
   char *params2 = NULL;
   char *pos1;
   char *pos2;
   int zerolength1 = 0;
   int zerolength2 = 0;
   int maddrmatch = 0;
   int ttlmatch = 0;
   int usermatch = 0;
   int methodmatch = 0;

   if (ast_strlen_zero(input1)) {
      zerolength1 = 1;
   } else {
      params1 = ast_strdupa(input1);
   }
   if (ast_strlen_zero(input2)) {
      zerolength2 = 1;
   } else {
      params2 = ast_strdupa(input2);
   }

   /* Quick optimization. If both params are zero-length, then
    * they match
    */
   if (zerolength1 && zerolength2) {
      return 0;
   }

   for (pos1 = strsep(&params1, ";"); pos1; pos1 = strsep(&params1, ";")) {
      char *value1 = pos1;
      char *name1 = strsep(&value1, "=");
      char *params2dup = NULL;
      int matched = 0;
      if (!value1) {
         value1 = "";
      }
      /* Checkpoint reached. We have the name and value parsed for param1
       * We have to duplicate params2 each time through this loop
       * or else the inner loop below will not work properly.
       */
      if (!zerolength2) {
         params2dup = ast_strdupa(params2);
      }
      for (pos2 = strsep(&params2dup, ";"); pos2; pos2 = strsep(&params2dup, ";")) {
         char *name2 = pos2;
         char *value2 = strchr(pos2, '=');
         if (!value2) {
            value2 = "";
         } else {
            *value2++ = '\0';
         }
         if (!strcasecmp(name1, name2)) {
            if (strcasecmp(value1, value2)) {
               goto fail;
            } else {
               matched = 1;
               break;
            }
         }
      }
      /* Check to see if the parameter is one of the 'must-match' parameters */
      if (!strcasecmp(name1, "maddr")) {
         if (matched) {
            maddrmatch = 1;
         } else {
            goto fail;
         }
      } else if (!strcasecmp(name1, "ttl")) {
         if (matched) {
            ttlmatch = 1;
         } else {
            goto fail;
         }
      } else if (!strcasecmp(name1, "user")) {
         if (matched) {
            usermatch = 1;
         } else {
            goto fail;
         }
      } else if (!strcasecmp(name1, "method")) {
         if (matched) {
            methodmatch = 1;
         } else {
            goto fail;
         }
      }
   }

   /* We've made it out of that horrible O(m*n) construct and there are no
    * failures yet. We're not done yet, though, because params2 could have
    * an maddr, ttl, user, or method header and params1 did not.
    */
   for (pos2 = strsep(&params2, ";"); pos2; pos2 = strsep(&params2, ";")) {
      char *value2 = pos2;
      char *name2 = strsep(&value2, "=");
      if (!value2) {
         value2 = "";
      }
      if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
            (!strcasecmp(name2, "ttl") && !ttlmatch) ||
            (!strcasecmp(name2, "user") && !usermatch) ||
            (!strcasecmp(name2, "method") && !methodmatch)) {
         goto fail;
      }
   }
   return 0;

fail:
   return 1;
}
static int sip_write ( struct ast_channel ast,
struct ast_frame frame 
) [static]

Send frame to media channel (rtp)

Definition at line 6422 of file chan_sip.c.

References ast_channel::_state, AST_FORMAT_AUDIO_MASK, AST_FRAME_IMAGE, AST_FRAME_MODEM, AST_FRAME_TEXT, AST_FRAME_VIDEO, AST_FRAME_VOICE, ast_getformatname_multiple(), ast_log(), ast_rtp_new_source(), ast_rtp_write(), ast_set_flag, AST_STATE_UP, ast_test_flag, ast_udptl_write(), sip_pvt::flags, ast_frame::frametype, sip_pvt::initreq, INV_EARLY_MEDIA, sip_pvt::invitestate, sip_pvt::lastrtptx, LOG_WARNING, ast_channel::nativeformats, ast_channel::readformat, sip_pvt::red, red_buffer_t140(), sip_pvt::rtp, SIP_OUTGOING, SIP_PROGRESS_SENT, sip_pvt_lock, sip_pvt_unlock, t38properties::state, ast_frame::subclass, sip_pvt::t38, T38_ENABLED, ast_channel::tech_pvt, transmit_provisional_response(), sip_pvt::trtp, TRUE, sip_pvt::udptl, sip_pvt::vrtp, and ast_channel::writeformat.

{
   struct sip_pvt *p = ast->tech_pvt;
   int res = 0;

   switch (frame->frametype) {
   case AST_FRAME_VOICE:
      if (!(frame->subclass & ast->nativeformats)) {
         char s1[512], s2[512], s3[512];
         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
            frame->subclass, 
            ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
            ast->nativeformats & AST_FORMAT_AUDIO_MASK,
            ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
            ast->readformat,
            ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
            ast->writeformat);
         return 0;
      }
      if (p) {
         sip_pvt_lock(p);
         if (p->rtp) {
            /* If channel is not up, activate early media session */
            if ((ast->_state != AST_STATE_UP) &&
                !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
                !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
               ast_rtp_new_source(p->rtp);
               if (!global_prematuremediafilter) {
                  p->invitestate = INV_EARLY_MEDIA;
                  transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
                  ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
               }
            } else if (p->t38.state == T38_ENABLED) {
               /* drop frame, can't sent VOICE frames while in T.38 mode */
            } else {
               p->lastrtptx = time(NULL);
               res = ast_rtp_write(p->rtp, frame);
            }
         }
         sip_pvt_unlock(p);
      }
      break;
   case AST_FRAME_VIDEO:
      if (p) {
         sip_pvt_lock(p);
         if (p->vrtp) {
            /* Activate video early media */
            if ((ast->_state != AST_STATE_UP) &&
                !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
                !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
               p->invitestate = INV_EARLY_MEDIA;
               transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
               ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
            }
            p->lastrtptx = time(NULL);
            res = ast_rtp_write(p->vrtp, frame);
         }
         sip_pvt_unlock(p);
      }
      break;
   case AST_FRAME_TEXT:
      if (p) {
         sip_pvt_lock(p);
         if (p->red) {
            red_buffer_t140(p->trtp, frame);
         } else {
            if (p->trtp) {
               /* Activate text early media */
               if ((ast->_state != AST_STATE_UP) &&
                   !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
                   !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
                  p->invitestate = INV_EARLY_MEDIA;
                  transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
                  ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
               }
               p->lastrtptx = time(NULL);
               res = ast_rtp_write(p->trtp, frame);
            }
         }
         sip_pvt_unlock(p);
      }
      break;
   case AST_FRAME_IMAGE:
      return 0;
      break;
   case AST_FRAME_MODEM:
      if (p) {
         sip_pvt_lock(p);
         /* UDPTL requires two-way communication, so early media is not needed here.
            we simply forget the frames if we get modem frames before the bridge is up.
            Fax will re-transmit.
         */
         if ((ast->_state == AST_STATE_UP) &&
             p->udptl &&
             (p->t38.state == T38_ENABLED)) {
            res = ast_udptl_write(p->udptl, frame);
         }
         sip_pvt_unlock(p);
      }
      break;
   default: 
      ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
      return 0;
   }

   return res;
}
static int sipsock_read ( int *  id,
int  fd,
short  events,
void *  ignore 
) [static]

Read data from SIP UDP socket.

Note:
sipsock_read locks the owner channel while we are processing the SIP message
Returns:
1 on error, 0 on success
Note:
Successful messages is connected to SIP call and forwarded to handle_incoming()

Definition at line 22527 of file chan_sip.c.

References AST_DYNSTR_BUILD_FAILED, ast_log(), ast_str_create(), ast_str_set(), bindaddr, sip_request::data, deinit_req(), errno, sip_socket::fd, handle_request_do(), sip_request::len, LOG_NOTICE, LOG_WARNING, sip_socket::port, set_socket_transport(), SIP_MIN_PACKET, SIP_TRANSPORT_UDP, sipsock, sip_request::socket, and sip_socket::tcptls_session.

Referenced by do_monitor().

{
   struct sip_request req;
   struct sockaddr_in sin = { 0, };
   int res;
   socklen_t len = sizeof(sin);
   static char readbuf[65535];

   memset(&req, 0, sizeof(req));
   res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
   if (res < 0) {
#if !defined(__FreeBSD__)
      if (errno == EAGAIN)
         ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
      else 
#endif
      if (errno != ECONNREFUSED)
         ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
      return 1;
   }

   readbuf[res] = '\0';

   if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
      return 1;
   }

   if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
      return -1;
   }

   req.len = res;
   req.socket.fd = sipsock;
   set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
   req.socket.tcptls_session  = NULL;
   req.socket.port = bindaddr.sin_port;

   handle_request_do(&req, &sin);
   deinit_req(&req);

   return 1;
}
enum st_mode st_get_mode ( struct sip_pvt p) [static]

Get the session-timer mode.

Parameters:
ppointer to the SIP dialog

Definition at line 23468 of file chan_sip.c.

References FALSE, find_peer(), FINDPEERS, global_st_mode, sip_pvt::peername, pp, SESSION_TIMER_MODE_INVALID, sip_st_alloc(), sip_st_dlg::st_cached_mode, sip_st_cfg::st_mode_oper, sip_peer::stimer, sip_pvt::stimer, TRUE, and unref_peer().

Referenced by add_supported_header(), handle_request_invite(), handle_response_invite(), and transmit_invite().

{
   if (!p->stimer) 
      sip_st_alloc(p);

   if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID) 
      return p->stimer->st_cached_mode;

   if (p->peername) {
      struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
      if (pp) {
         p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
         unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
         return pp->stimer.st_mode_oper;
      }
   }

   p->stimer->st_cached_mode = global_st_mode;
   return global_st_mode;
}
enum st_refresher st_get_refresher ( struct sip_pvt p) [static]

Get the entity (UAC or UAS) that's acting as the session-timer refresher.

Parameters:
ppointer to the SIP dialog

Definition at line 23446 of file chan_sip.c.

References FALSE, find_peer(), FINDPEERS, global_st_refresher, sip_pvt::peername, pp, SESSION_TIMER_REFRESHER_AUTO, sip_st_dlg::st_cached_ref, sip_st_cfg::st_ref, sip_peer::stimer, sip_pvt::stimer, TRUE, and unref_peer().

Referenced by handle_request_invite().

{
   if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) 
      return p->stimer->st_cached_ref;

   if (p->peername) {
      struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
      if (pp) {
         p->stimer->st_cached_ref = pp->stimer.st_ref;
         unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
         return pp->stimer.st_ref;
      }
   }
   
   p->stimer->st_cached_ref = global_st_refresher;
   return global_st_refresher;
}
int st_get_se ( struct sip_pvt p,
int  max 
) [static]

Get Max or Min SE (session timer expiry)

Parameters:
ppointer to the SIP dialog
maxif true, get max se, otherwise min se

Definition at line 23411 of file chan_sip.c.

References FALSE, find_peer(), FINDPEERS, global_max_se, global_min_se, sip_pvt::peername, pp, sip_st_dlg::st_cached_max_se, sip_st_dlg::st_cached_min_se, sip_st_cfg::st_max_se, sip_st_cfg::st_min_se, sip_peer::stimer, sip_pvt::stimer, TRUE, and unref_peer().

Referenced by handle_request_invite(), reqprep(), and transmit_invite().

{
   if (max == TRUE) {
      if (p->stimer->st_cached_max_se) {
         return p->stimer->st_cached_max_se;
      } else if (p->peername) {
         struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
         if (pp) {
            p->stimer->st_cached_max_se = pp->stimer.st_max_se;
            unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
            return (p->stimer->st_cached_max_se);
         }
      }
      p->stimer->st_cached_max_se = global_max_se;
      return (p->stimer->st_cached_max_se);
   } else {
      if (p->stimer->st_cached_min_se) {
         return p->stimer->st_cached_min_se;
      } else if (p->peername) {
         struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
         if (pp) {
            p->stimer->st_cached_min_se = pp->stimer.st_min_se;
            unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
            return (p->stimer->st_cached_min_se);
         }
      }
      p->stimer->st_cached_min_se = global_min_se;
      return (p->stimer->st_cached_min_se);
   }
}
static void start_session_timer ( struct sip_pvt p) [static]

Session-Timers: Start session timer.

Definition at line 23208 of file chan_sip.c.

References ast_debug, ast_log(), ast_sched_add(), sip_pvt::callid, dialog_ref(), dialog_unref(), LOG_ERROR, LOG_WARNING, proc_session_timer(), sip_st_dlg::st_interval, sip_st_dlg::st_schedid, and sip_pvt::stimer.

Referenced by handle_request_invite(), handle_response_invite(), and restart_session_timer().

{
   if (!p->stimer) {
      ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
      return;
   }

   p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, 
         dialog_ref(p, "adding session timer ref"));
   if (p->stimer->st_schedid < 0) {
      dialog_unref(p, "removing session timer ref");
      ast_log(LOG_ERROR, "ast_sched_add failed.\n");
   }
   ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
}
static const char* stmode2str ( enum st_mode  m) [static]

Definition at line 14970 of file chan_sip.c.

References map_x_s().

Referenced by _sip_show_peer(), sip_show_channel(), sip_show_settings(), and sip_show_user().

{
   return map_x_s(stmodes, m, "Unknown");
}
static void stop_media_flows ( struct sip_pvt p) [static]

Immediately stop RTP, VRTP and UDPTL as applicable.

Definition at line 18848 of file chan_sip.c.

References ast_rtp_stop(), ast_udptl_stop(), sip_pvt::rtp, sip_pvt::trtp, sip_pvt::udptl, and sip_pvt::vrtp.

Referenced by handle_request_bye(), handle_request_cancel(), handle_response(), and sip_hangup().

{
   /* Immediately stop RTP, VRTP and UDPTL as applicable */
   if (p->rtp)
      ast_rtp_stop(p->rtp);
   if (p->vrtp)
      ast_rtp_stop(p->vrtp);
   if (p->trtp)
      ast_rtp_stop(p->trtp);
   if (p->udptl)
      ast_udptl_stop(p->udptl);
}
static void stop_session_timer ( struct sip_pvt p) [static]

Session-Timers: Stop session timer.

Definition at line 23191 of file chan_sip.c.

References ast_debug, ast_log(), AST_SCHED_DEL_UNREF, sip_pvt::callid, dialog_unref(), FALSE, LOG_WARNING, sip_st_dlg::st_active, sip_st_dlg::st_schedid, sip_pvt::stimer, and TRUE.

Referenced by handle_request_bye(), proc_session_timer(), sip_hangup(), and sip_scheddestroy().

{
   if (!p->stimer) {
      ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
      return;
   }

   if (p->stimer->st_active == TRUE) {
      p->stimer->st_active = FALSE;
      AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
            dialog_unref(p, "removing session timer ref"));
      ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
   }
}
static int str2dtmfmode ( const char *  str) [static]

maps a string to dtmfmode, returns -1 on error

Definition at line 15494 of file chan_sip.c.

References map_s_x().

{
   return map_s_x(dtmfstr, str, -1);
}
static enum st_mode str2stmode ( const char *  s) [static]

Definition at line 14975 of file chan_sip.c.

References map_s_x().

Referenced by build_peer(), and reload_config().

{
   return map_s_x(stmodes, s, -1);
}
static enum st_refresher str2strefresher ( const char *  s) [static]

Definition at line 14993 of file chan_sip.c.

References map_s_x().

Referenced by build_peer(), and reload_config().

{
   return map_s_x(strefreshers, s, -1);
}
static const char * strefresher2str ( enum st_refresher  r) [static]

Definition at line 14988 of file chan_sip.c.

References map_x_s().

Referenced by _sip_show_peer(), reqprep(), respprep(), sip_show_channel(), sip_show_settings(), and sip_show_user().

{
   return map_x_s(strefreshers, r, "Unknown");
}
static const char * subscription_type2str ( enum subscriptiontype  subtype) [static]

Show subscription type in string format.

Definition at line 16728 of file chan_sip.c.

References ARRAY_LEN, subscription_types, and cfsubscription_types::text.

Referenced by show_channels_cb(), and sip_show_channel().

{
   int i;

   for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
      if (subscription_types[i].type == subtype) {
         return subscription_types[i].text;
      }
   }
   return subscription_types[0].text;
}
static unsigned int t38_get_rate ( enum ast_control_t38_rate  rate) [static]

Get Max T.38 Transmission rate from T38 capabilities.

Definition at line 10432 of file chan_sip.c.

References AST_T38_RATE_12000, AST_T38_RATE_14400, AST_T38_RATE_2400, AST_T38_RATE_4800, AST_T38_RATE_7200, and AST_T38_RATE_9600.

Referenced by add_sdp().

{
   switch (rate) {
   case AST_T38_RATE_2400:
      return 2400;
   case AST_T38_RATE_4800:
      return 4800;
   case AST_T38_RATE_7200:
      return 7200;
   case AST_T38_RATE_9600:
      return 9600;
   case AST_T38_RATE_12000:
      return 12000;
   case AST_T38_RATE_14400:
      return 14400;
   default:
      return 0;
   }
}
static void tcptls_packet_destructor ( void *  obj) [static]

Definition at line 2792 of file chan_sip.c.

References ast_free, and tcptls_packet::data.

Referenced by sip_tcptls_write().

{
   struct tcptls_packet *packet = obj;

   ast_free(packet->data);
}
static struct sip_peer * temp_peer ( const char *  name) [static, read]

Create temporary peer (used in autocreatepeer mode)

Definition at line 24326 of file chan_sip.c.

References ao2_t_alloc, ao2_t_ref, ast_atomic_fetchadd_int(), ast_copy_string(), ast_string_field_init, default_prefs, sip_peer::host_dynamic, sip_peer::name, sip_peer::prefs, reg_source_db(), sip_peer::selfdestruct, set_peer_defaults(), sip_destroy_peer_fn(), and TRUE.

Referenced by register_verify().

{
   struct sip_peer *peer;

   if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
      return NULL;

   if (ast_string_field_init(peer, 512)) {
      ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
      return NULL;
   }

   ast_atomic_fetchadd_int(&apeerobjs, 1);
   set_peer_defaults(peer);

   ast_copy_string(peer->name, name, sizeof(peer->name));

   peer->selfdestruct = TRUE;
   peer->host_dynamic = TRUE;
   peer->prefs = default_prefs;
   reg_source_db(peer);

   return peer;
}
static void temp_pvt_cleanup ( void *  data) [static]

Definition at line 10098 of file chan_sip.c.

References ast_free, ast_string_field_free_memory, and sip_request::data.

{
   struct sip_pvt *p = data;

   ast_string_field_free_memory(p);

   ast_free(data);
}
static int temp_pvt_init ( void *  data) [static]

Definition at line 10090 of file chan_sip.c.

References ast_string_field_init, sip_request::data, and sip_pvt::do_history.

{
   struct sip_pvt *p = data;

   p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
   return ast_string_field_init(p, 512);
}
static char* terminate_uri ( char *  uri) [static]

Terminate the uri at the first ';' or space. Technically we should ignore escaped space per RFC3261 (19.1.1 etc) but don't do it for the time being. Remember the uri format is: (User-parameters was added after RFC 3261)

 *
 *	sip:user:password;user-parameters@host:port;uri-parameters?headers
 *	sips:user:password;user-parameters@host:port;uri-parameters?headers
 *
 *
Todo:
As this function does not support user-parameters, it's considered broken and needs fixing.

Definition at line 13458 of file chan_sip.c.

Referenced by check_user_full(), and register_verify().

{
   char *t = uri;
   while (*t && *t > ' ' && *t != ';')
      t++;
   *t = '\0';
   return uri;
}
static int threadinfo_locate_cb ( void *  obj,
void *  arg,
int  flags 
) [static]

Definition at line 22702 of file chan_sip.c.

References CMP_MATCH, CMP_STOP, inaddrcmp(), ast_tcptls_session_instance::remote_address, s, and sip_threadinfo::tcptls_session.

Referenced by sip_tcp_locate().

{
   struct sip_threadinfo *th = obj;
   struct sockaddr_in *s = arg;

   if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
      return CMP_MATCH | CMP_STOP;
   }

   return 0;
}
static int threadt_cmp_cb ( void *  obj,
void *  arg,
int  flags 
) [static]

Definition at line 2125 of file chan_sip.c.

References CMP_MATCH, CMP_STOP, and sip_threadinfo::tcptls_session.

Referenced by load_module().

{
   struct sip_threadinfo *th = obj, *th2 = arg;

   return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
}
static int threadt_hash_cb ( const void *  obj,
const int  flags 
) [static]

Definition at line 2118 of file chan_sip.c.

References ast_tcptls_session_instance::remote_address, and sip_threadinfo::tcptls_session.

Referenced by load_module().

{
   const struct sip_threadinfo *th = obj;

   return (int) th->tcptls_session->remote_address.sin_addr.s_addr;
}
static char * transfermode2str ( enum transfermodes  mode) [static]

Convert transfer mode to text string.

Definition at line 14914 of file chan_sip.c.

References TRANSFER_CLOSED, and TRANSFER_OPENFORALL.

Referenced by _sip_show_peer(), sip_show_channel(), sip_show_settings(), and sip_show_user().

{
   if (mode == TRANSFER_OPENFORALL)
      return "open";
   else if (mode == TRANSFER_CLOSED)
      return "closed";
   return "strict";
}
static void transmit_fake_auth_response ( struct sip_pvt p,
int  sipmethod,
struct sip_request req,
enum xmittype  reliable 
) [static]

Send a fake 401 Unauthorized response when the administrator wants to hide the names of local devices from fishers.

Definition at line 13352 of file chan_sip.c.

References AST_DYNSTR_BUILD_FAILED, ast_skip_blanks(), ast_str_set(), ast_str_thread_get(), ast_strlen_zero(), buf, CHECK_AUTH_BUF_INITLEN, DEFAULT_TRANS_TIMEOUT, FALSE, get_header(), sip_request::ignore, sip_pvt::initreq, sip_pvt::randdata, s, set_nonce_randdata(), SIP_REGISTER, sip_scheddestroy(), SIP_SUBSCRIBE, strsep(), transmit_response(), and transmit_response_with_auth().

Referenced by handle_request_invite(), handle_request_subscribe(), and register_verify().

{
   /* We have to emulate EXACTLY what we'd get with a good peer
    * and a bad password, or else we leak information. */
   const char *response = "407 Proxy Authentication Required";
   const char *reqheader = "Proxy-Authorization";
   const char *respheader = "Proxy-Authenticate";
   const char *authtoken;
   struct ast_str *buf;
   char *c;

   /* table of recognised keywords, and their value in the digest */
   enum keys { K_NONCE, K_LAST };
   struct x {
      const char *key;
      const char *s;
   } *i, keys[] = {
      [K_NONCE] = { "nonce=", "" },
      [K_LAST] = { NULL, NULL}
   };

   if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
      response = "401 Unauthorized";
      reqheader = "Authorization";
      respheader = "WWW-Authenticate";
   }
   authtoken = get_header(req, reqheader);
   if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
      /* This is a retransmitted invite/register/etc, don't reconstruct authentication
       * information */
      transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
      /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      return;
   } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
      /* We have no auth, so issue challenge and request authentication */
      set_nonce_randdata(p, 1);
      transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
      /* Schedule auto destroy in 32 seconds */
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
      return;
   }

   if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
      transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
      return;
   }

   /* Make a copy of the response and parse it */
   if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
      transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
      return;
   }

   c = buf->str;

   while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
      for (i = keys; i->key != NULL; i++) {
         const char *separator = ",";  /* default */

         if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
            continue;
         }
         /* Found. Skip keyword, take text in quotes or up to the separator. */
         c += strlen(i->key);
         if (*c == '"') { /* in quotes. Skip first and look for last */
            c++;
            separator = "\"";
         }
         i->s = c;
         strsep(&c, separator);
         break;
      }
      if (i->key == NULL) { /* not found, jump after space or comma */
         strsep(&c, " ,");
      }
   }

   /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
   if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
      if (!req->ignore) {
         set_nonce_randdata(p, 1);
      }
      transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);

      /* Schedule auto destroy in 32 seconds */
      sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
   } else {
      transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
   }
}
static int transmit_info_with_digit ( struct sip_pvt p,
const char  digit,
unsigned int  duration 
) [static]

Send SIP INFO dtmf message, see Cisco documentation on cisco.com.

Definition at line 12402 of file chan_sip.c.

References add_digit(), ast_test_flag, sip_pvt::flags, sip_pvt::ocseq, reqprep(), send_request(), SIP_DTMF, SIP_DTMF_SHORTINFO, SIP_INFO, and XMIT_RELIABLE.

Referenced by sip_senddigit_end().

{
   struct sip_request req;
   
   reqprep(&req, p, SIP_INFO, 0, 1);
   add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
   return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}
static int transmit_info_with_vidupdate ( struct sip_pvt p) [static]

Send SIP INFO with video update request.

Definition at line 12412 of file chan_sip.c.

References add_vidupdate(), sip_pvt::ocseq, reqprep(), send_request(), SIP_INFO, and XMIT_RELIABLE.

Referenced by sip_indicate().

{
   struct sip_request req;
   
   reqprep(&req, p, SIP_INFO, 0, 1);
   add_vidupdate(&req);
   return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}
static int transmit_invite ( struct sip_pvt p,
int  sipmethod,
int  sdp,
int  init 
) [static]

Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it.

Parameters:
init0 = Prepare request within dialog, 1= prepare request, new branch, 2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
psip_pvt structure
sdpunknown
sipmethodunknown

Definition at line 11320 of file chan_sip.c.

References add_header(), add_sdp(), add_supported_header(), sip_invite_param::addsipheaders, ALLOWED_METHODS, append_date(), ast_channel_lock, ast_channel_unlock, ast_copy_string(), ast_debug, AST_LIST_TRAVERSE, ast_log(), ast_random(), ast_skip_blanks(), ast_strdupa, ast_strlen_zero(), ast_unescape_semicolon(), ast_var_name(), ast_var_value(), sip_invite_param::auth, sip_invite_param::authheader, sip_pvt::branch, buf, build_via(), chan, sip_request::content, ast_var_t::entries, FALSE, sip_request::header, sip_request::headers, initialize_initreq(), sip_pvt::initreq, initreqprep(), sip_pvt::invite_branch, sip_pvt::lastinvite, LOG_WARNING, sip_request::method, ast_channel::name, ast_variable::name, ast_variable::next, sip_pvt::notify_headers, sip_pvt::ocseq, sip_pvt::offered_media, sip_pvt::options, sip_pvt::owner, sip_pvt::refer, sip_refer::refer_to, sip_refer::referred_by, sip_refer::referred_by_name, sip_invite_param::replaces, reqprep(), sip_pvt::rtp, send_request(), SESSION_TIMER_MODE_ORIGINATE, SIP_REFER, SIP_SUBSCRIBE, SIPBUFSIZE, sip_st_dlg::st_active, st_get_mode(), st_get_se(), sip_st_dlg::st_interval, t38properties::state, sip_pvt::stimer, sip_pvt::t38, T38_LOCAL_REINVITE, TRUE, sip_pvt::udptl, ast_variable::value, var, ast_channel::varshead, XMIT_CRITICAL, and XMIT_RELIABLE.

Referenced by __sip_subscribe_mwi_do(), do_proxy_auth(), proc_422_rsp(), sip_call(), and sip_poke_peer().

{
   struct sip_request req;
   struct ast_variable *var;
   
   req.method = sipmethod;
   if (init) {/* Bump branch even on initial requests */
      p->branch ^= ast_random();
      p->invite_branch = p->branch;
      build_via(p);
   }
   if (init > 1)
      initreqprep(&req, p, sipmethod);
   else
      /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
      reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
      
   if (p->options && p->options->auth)
      add_header(&req, p->options->authheader, p->options->auth);
   append_date(&req);
   if (sipmethod == SIP_REFER) { /* Call transfer */
      if (p->refer) {
         char buf[SIPBUFSIZE];
         if (!ast_strlen_zero(p->refer->refer_to))
            add_header(&req, "Refer-To", p->refer->refer_to);
         if (!ast_strlen_zero(p->refer->referred_by)) {
            snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
            add_header(&req, "Referred-By", buf);
         }
      }
   } else if (sipmethod == SIP_SUBSCRIBE) { /* We only support sending MWI subscriptions right now */
      char buf[SIPBUFSIZE];

      add_header(&req, "Event", "message-summary");
      add_header(&req, "Accept", "application/simple-message-summary");
      snprintf(buf, sizeof(buf), "%d", mwi_expiry);
      add_header(&req, "Expires", buf);
   }

   /* This new INVITE is part of an attended transfer. Make sure that the
   other end knows and replace the current call with this new call */
   if (p->options && !ast_strlen_zero(p->options->replaces)) {
      add_header(&req, "Replaces", p->options->replaces);
      add_header(&req, "Require", "replaces");
   }

   /* Add Session-Timers related headers */
   if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
      char i2astr[10];

      if (!p->stimer->st_interval)
         p->stimer->st_interval = st_get_se(p, TRUE);

      p->stimer->st_active = TRUE;
      
      snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
      add_header(&req, "Session-Expires", i2astr);
      snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
      add_header(&req, "Min-SE", i2astr);
   }

   add_header(&req, "Allow", ALLOWED_METHODS);
   add_supported_header(p, &req);

   if(p->notify_headers) {
      char buf[512];
      for (var = p->notify_headers; var; var = var->next) {
         ast_copy_string(buf, var->value, sizeof(buf));
         add_header(&req, var->name, ast_unescape_semicolon(buf));
      }
   }
   if (p->options && p->options->addsipheaders && p->owner) {
      struct ast_channel *chan = p->owner; /* The owner channel */
      struct varshead *headp;
   
      ast_channel_lock(chan);

      headp = &chan->varshead;

      if (!headp)
         ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
      else {
         const struct ast_var_t *current;
         AST_LIST_TRAVERSE(headp, current, entries) {  
            /* SIPADDHEADER: Add SIP header to outgoing call */
            if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
               char *content, *end;
               const char *header = ast_var_value(current);
               char *headdup = ast_strdupa(header);

               /* Strip of the starting " (if it's there) */
               if (*headdup == '"')
                  headdup++;
               if ((content = strchr(headdup, ':'))) {
                  *content++ = '\0';
                  content = ast_skip_blanks(content); /* Skip white space */
                  /* Strip the ending " (if it's there) */
                  end = content + strlen(content) -1; 
                  if (*end == '"')
                     *end = '\0';
               
                  add_header(&req, headdup, content);
                  if (sipdebug)
                     ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
               }
            }
         }
      }

      ast_channel_unlock(chan);
   }
   if (sdp) {
      memset(p->offered_media, 0, sizeof(p->offered_media));
      if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
         ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
         add_sdp(&req, p, FALSE, FALSE, TRUE);
      } else if (p->rtp) 
         add_sdp(&req, p, FALSE, TRUE, FALSE);
   }

   if (!p->initreq.headers || init > 2)
      initialize_initreq(p, &req);
   p->lastinvite = p->ocseq;
   return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
}
static int transmit_message_with_text ( struct sip_pvt p,
const char *  text 
) [static]

Transmit text with SIP MESSAGE method.

Definition at line 12305 of file chan_sip.c.

References add_text(), sip_pvt::ocseq, reqprep(), send_request(), SIP_MESSAGE, and XMIT_RELIABLE.

Referenced by sip_park_thread(), and sip_sendtext().

{
   struct sip_request req;
   
   reqprep(&req, p, SIP_MESSAGE, 0, 1);
   add_text(&req, text);
   return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}
static int transmit_notify_custom ( struct sip_pvt p,
struct ast_variable vars 
) [static]

Notify device with custom headers from sip_notify.conf.

Definition at line 11844 of file chan_sip.c.

References add_header(), ast_copy_string(), ast_debug, ast_unescape_semicolon(), ast_variable_new(), buf, sip_request::headers, initialize_initreq(), sip_pvt::initreq, initreqprep(), ast_variable::name, ast_variable::next, sip_pvt::notify_headers, sip_pvt::ocseq, send_request(), SIP_NOTIFY, ast_variable::value, var, and XMIT_RELIABLE.

Referenced by manager_sipnotify(), and sip_cli_notify().

                                                                                {
   struct sip_request req;
   struct ast_variable *var, *newvar;

   initreqprep(&req, p, SIP_NOTIFY);

   /* Copy notify vars and add headers */
   p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
   add_header(&req, newvar->name, newvar->value);
   for (var = vars; var; var = var->next) {
      char buf[512];

      if (!strcasecmp(var->name, "Content-Length")) {
         ast_debug(2, "Ignoring pair %s=%s\n", var->name, var->value);
         continue; /* ignore content-length, it is calculated automatically */
      }

      ast_debug(2, "  Adding pair %s=%s\n", var->name, var->value);
      ast_copy_string(buf, var->value, sizeof(buf));
      add_header(&req, var->name, ast_unescape_semicolon(buf));
      newvar->next = ast_variable_new(var->name, var->value, "");
      newvar = newvar->next;
   }

   if (!p->initreq.headers) { /* Initialize first request before sending */
      initialize_initreq(p, &req);
   }

   return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}
static int transmit_notify_with_mwi ( struct sip_pvt p,
int  newmsgs,
int  oldmsgs,
const char *  vmexten 
) [static]

Notify user of messages waiting in voicemail (RFC3842)

Note:
- Notification only works for registered peers with mailbox= definitions in sip.conf
  • We use the SIP Event package message-summary MIME type defaults to "application/simple-message-summary";

Definition at line 11773 of file chan_sip.c.

References add_content(), add_header(), ast_inet_ntoa(), ast_str_alloca, ast_str_append(), ast_strlen_zero(), ast_test_flag, sip_pvt::expiry, exten, sip_pvt::flags, sip_pvt::fromdomain, get_transport(), sip_request::headers, initialize_initreq(), sip_pvt::initreq, initreqprep(), sip_pvt::ocseq, sip_pvt::ourip, ourport, S_OR, send_request(), SIP_NOTIFY, SIP_PAGE2_BUGGY_MWI, sip_standard_port(), SIP_TRANSPORT_UDP, sip_pvt::socket, sip_pvt::subscribed, sip_socket::type, and XMIT_RELIABLE.

Referenced by sip_send_mwi_to_peer().

{
   struct sip_request req;
   struct ast_str *out = ast_str_alloca(500);
   int ourport = ntohs(p->ourip.sin_port);
   const char *exten = S_OR(vmexten, default_vmexten);

   initreqprep(&req, p, SIP_NOTIFY);
   add_header(&req, "Event", "message-summary");
   add_header(&req, "Content-Type", default_notifymime);
   ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");

   if (!ast_strlen_zero(p->fromdomain)) {
      ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
   } else if (!sip_standard_port(p->socket.type, ourport)) {
      if (p->socket.type == SIP_TRANSPORT_UDP) {
         ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
      } else {
         ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
      }
   } else {
      if (p->socket.type == SIP_TRANSPORT_UDP) {
         ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
      } else {
         ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
      }
   }
   /* Cisco has a bug in the SIP stack where it can't accept the
      (0/0) notification. This can temporarily be disabled in
      sip.conf with the "buggymwi" option */
   ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
      newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));

   if (p->subscribed) {
      if (p->expiry)
         add_header(&req, "Subscription-State", "active");
      else  /* Expired */
         add_header(&req, "Subscription-State", "terminated;reason=timeout");
   }

   add_content(&req, out->str);

   if (!p->initreq.headers) 
      initialize_initreq(p, &req);
   return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}
static int transmit_notify_with_sipfrag ( struct sip_pvt p,
int  cseq,
char *  message,
int  terminate 
) [static]

Notify a transferring party of the status of transfer (RFC3515)

Definition at line 11821 of file chan_sip.c.

References add_content(), add_header(), add_supported_header(), ALLOWED_METHODS, sip_request::headers, initialize_initreq(), sip_pvt::initreq, sip_pvt::ocseq, reqprep(), send_request(), SIP_NOTIFY, SIPBUFSIZE, and XMIT_RELIABLE.

Referenced by handle_request_refer(), local_attended_transfer(), and sip_park_thread().

{
   struct sip_request req;
   char tmp[SIPBUFSIZE/2];
   
   reqprep(&req, p, SIP_NOTIFY, 0, 1);
   snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
   add_header(&req, "Event", tmp);
   add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
   add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
   add_header(&req, "Allow", ALLOWED_METHODS);
   add_supported_header(p, &req);

   snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
   add_content(&req, tmp);

   if (!p->initreq.headers)
      initialize_initreq(p, &req);

   return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}
static int transmit_provisional_response ( struct sip_pvt p,
const char *  msg,
const struct sip_request req,
int  with_sdp 
) [static]
static int transmit_refer ( struct sip_pvt p,
const char *  dest 
) [static]

Transmit SIP REFER message (initiated by the transfer() dialplan application.

Note:
this is currently broken as we have no way of telling the dialplan engine whether a transfer succeeds or fails.
Todo:
Fix the transfer() dialplan function so that a transfer may fail

Todo:
In theory, we should hang around and wait for a reply, before returning to the dial plan here. Don't know really how that would affect the transfer() app or the pbx, but, well, to make this useful we should have a STATUS code on transfer().

Definition at line 12326 of file chan_sip.c.

References add_header(), add_supported_header(), ALLOWED_METHODS, ast_copy_string(), ast_debug, ast_log(), ast_strdupa, ast_string_field_set, ast_strlen_zero(), ast_test_flag, sip_pvt::callid, FALSE, sip_pvt::flags, get_header(), get_in_brackets(), sip_request::headers, sip_pvt::initreq, LOG_NOTICE, sip_pvt::ocseq, sip_pvt::our_contact, sip_pvt::refer, REFER_SENT, sip_refer::refer_to, sip_refer::referred_by, reqprep(), send_request(), SIP_OUTGOING, SIP_REFER, sip_refer_allocate(), sip_refer::status, sip_pvt::tag, sip_pvt::theirtag, TRUE, and XMIT_RELIABLE.

Referenced by sip_transfer().

{
   struct sip_request req = { 
      .headers = 0,  
   };
   char from[256];
   const char *of;
   char *c;
   char referto[256];
   char *ttag, *ftag;
   char *theirtag = ast_strdupa(p->theirtag);
   int   use_tls=FALSE;

   if (sipdebug)
      ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);

   /* Are we transfering an inbound or outbound call ? */
   if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
      of = get_header(&p->initreq, "To");
      ttag = theirtag;
      ftag = p->tag;
   } else {
      of = get_header(&p->initreq, "From");
      ftag = theirtag;
      ttag = p->tag;
   }

   ast_copy_string(from, of, sizeof(from));
   of = get_in_brackets(from);
   ast_string_field_set(p, from, of);
   if (!strncasecmp(of, "sip:", 4)) {
      of += 4;
   }else if (!strncasecmp(of, "sips:", 5)) {
      of += 5;
      use_tls = TRUE;
   } else {
      ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
   }
   /* Get just the username part */
   if ((c = strchr(dest, '@')))
      c = NULL;
   else if ((c = strchr(of, '@')))
      *c++ = '\0';
   if (c) 
      snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
   else
      snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);

   /* save in case we get 407 challenge */
   sip_refer_allocate(p);
   ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
   ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
   p->refer->status = REFER_SENT;   /* Set refer status */

   reqprep(&req, p, SIP_REFER, 0, 1);

   add_header(&req, "Refer-To", referto);
   add_header(&req, "Allow", ALLOWED_METHODS);
   add_supported_header(p, &req);
   if (!ast_strlen_zero(p->our_contact))
      add_header(&req, "Referred-By", p->our_contact);

   return send_request(p, &req, XMIT_RELIABLE, p->ocseq);

   /* We should propably wait for a NOTIFY here until we ack the transfer */
   /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */

   /*! \todo In theory, we should hang around and wait for a reply, before
   returning to the dial plan here. Don't know really how that would
   affect the transfer() app or the pbx, but, well, to make this
   useful we should have a STATUS code on transfer().
   */
}
static int transmit_register ( struct sip_registry r,
int  sipmethod,
const char *  auth,
const char *  authheader 
) [static]

Transmit register to SIP proxy or UA auth = NULL on the initial registration (from sip_reregister())

Definition at line 12054 of file chan_sip.c.

References add_header(), append_history, ast_debug, ast_dnsmgr_lookup(), ast_log(), ast_random(), ast_sched_add(), AST_SCHED_REPLACE_UNREF, ast_set_flag, ast_sip_ouraddrfor(), ast_string_field_set, ast_strlen_zero(), ast_verbose(), sip_registry::authuser, sip_pvt::branch, build_callid_registry(), build_contact(), build_reply_digest(), build_via(), sip_registry::call, sip_registry::callback, sip_pvt::callid, sip_registry::callid, sip_registry::callid_valid, create_addr(), DEFAULT_MAX_FORWARDS, dialog_ref(), dialog_unlink_all(), dialog_unref(), sip_registry::dnsmgr, sip_pvt::do_history, sip_registry::domain, sip_registry::expiry, exten, FALSE, find_peer(), FINDPEERS, sip_pvt::flags, sip_pvt::fromdomain, sip_peer::fromdomain, sip_peer::fromuser, get_srv_protocol(), get_srv_service(), sip_request::headers, sip_registry::hostname, init_req(), initialize_initreq(), sip_pvt::initreq, internip, sip_request::lines, ast_tcptls_session_args::local_address, LOG_NOTICE, LOG_WARNING, make_our_tag(), MAXHOSTNAMELEN, sip_registry::md5secret, sip_registry::nonce, sip_registry::noncecount, sip_pvt::noncecount, sip_pvt::ocseq, sip_registry::ocseq, sip_registry::opaque, sip_pvt::our_contact, sip_pvt::ourip, sip_registry::peername, sip_socket::port, sip_registry::portno, sip_registry::qop, sip_registry::realm, sip_pvt::recv, REG_STATE_AUTHSENT, REG_STATE_REGSENT, sip_registry::regattempts, sip_pvt::registry, registry_addref(), registry_unref(), sip_registry::regstate, S_OR, sip_pvt::sa, sip_registry::secret, send_request(), set_socket_transport(), sip_alloc(), sip_cfg, sip_debug_test_pvt(), sip_methods, SIP_OUTGOING, sip_reg_timeout(), SIP_REGISTER, SIP_TRANSPORT_TCP, SIP_TRANSPORT_TLS, sip_pvt::socket, sip_settings::srvlookup, STANDARD_SIP_PORT, sip_pvt::tag, cfsip_methods::text, sip_pvt::theirtag, sip_registry::timeout, sip_pvt::tohost, sip_peer::tohost, sip_registry::transport, TRUE, unref_peer(), sip_registry::us, sip_peer::username, sip_registry::username, sip_pvt::via, and XMIT_CRITICAL.

Referenced by __sip_do_register(), do_register_auth(), handle_response_register(), and sip_reg_timeout().

{
   struct sip_request req;
   char from[256];
   char to[256];
   char tmp[80];
   char addr[80];
   struct sip_pvt *p;
   struct sip_peer *peer = NULL;
   int res;
   char *fromdomain;
   char *domainport = NULL;

   /* exit if we are already in process with this registrar ?*/
   if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
      if (r) {
         ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
      }
      return 0;
   }

   if (r->dnsmgr == NULL) {
      char transport[MAXHOSTNAMELEN];
      peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
      snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static get_transport function */
      ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
      if (peer) {
         peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
      }
   }

   if (r->call) { /* We have a registration */
      if (!auth) {
         ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
         return 0;
      } else {
         p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
         make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
         ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
      }
   } else {
      /* Build callid for registration if we haven't registered before */
      if (!r->callid_valid) {
         build_callid_registry(r, internip.sin_addr, default_fromdomain);
         r->callid_valid = TRUE;
      }
      /* Allocate SIP dialog for registration */
      if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
         ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
         return 0;
      }
      
      if (p->do_history)
         append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);

      /* Use port number specified if no SRV record was found */
      if (!r->us.sin_port && r->portno)
         r->us.sin_port = htons(r->portno);

      /* Find address to hostname */
      if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
         /* we have what we hope is a temporary network error,
          * probably DNS.  We need to reschedule a registration try */
         dialog_unlink_all(p, TRUE, TRUE);
         p = dialog_unref(p, "unref dialog after unlink_all");
         if (r->timeout > -1) {
            AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
                              registry_unref(_data, "del for REPLACE of registry ptr"), 
                              registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
                              registry_addref(r,"add for REPLACE registry ptr"));
            ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
         } else {
            r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
            ast_log(LOG_WARNING, "Probably a DNS error for registration to %s@%s, trying REGISTER again (after %d seconds)\n", r->username, r->hostname, global_reg_timeout);
         }
         r->regattempts++;
         return 0;
      }

      /* Copy back Call-ID in case create_addr changed it */
      ast_string_field_set(r, callid, p->callid);
      if (!r->dnsmgr && r->portno) {
         p->sa.sin_port = htons(r->portno);
         p->recv.sin_port = htons(r->portno);
      } else { /* Set registry port to the port set from the peer definition/srv or default */
         r->portno = ntohs(p->sa.sin_port);
      }
      ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
      r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
      p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
      if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
         ast_string_field_set(p, peersecret, r->secret);
      }
      if (!ast_strlen_zero(r->md5secret))
         ast_string_field_set(p, peermd5secret, r->md5secret);
      /* User name in this realm  
      - if authuser is set, use that, otherwise use username */
      if (!ast_strlen_zero(r->authuser)) {   
         ast_string_field_set(p, peername, r->authuser);
         ast_string_field_set(p, authname, r->authuser);
      } else if (!ast_strlen_zero(r->username)) {
         ast_string_field_set(p, peername, r->username);
         ast_string_field_set(p, authname, r->username);
         ast_string_field_set(p, fromuser, r->username);
      }
      if (!ast_strlen_zero(r->username))
         ast_string_field_set(p, username, r->username);
      /* Save extension in packet */
      if (!ast_strlen_zero(r->callback))
         ast_string_field_set(p, exten, r->callback);

      /* Set transport and port so the correct contact is built */
      set_socket_transport(&p->socket, r->transport);
      if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
         p->socket.port = sip_tcp_desc.local_address.sin_port;
      }

      /*
        check which address we should use in our contact header 
        based on whether the remote host is on the external or
        internal network so we can register through nat
       */
      ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
      build_contact(p);
   }

   /* set up a timeout */
   if (auth == NULL)  {
      if (r->timeout > -1)
         ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
      AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
                        registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
                        registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
                        registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
      ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
   }

   if ((fromdomain = strchr(r->username, '@'))) {
      /* the domain name is just behind '@' */
      fromdomain++ ;
      /* We have a domain in the username for registration */
      snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
      if (!ast_strlen_zero(p->theirtag))
         snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
      else
         snprintf(to, sizeof(to), "<sip:%s>", r->username);

      /* If the registration username contains '@', then the domain should be used as
         the equivalent of "fromdomain" for the registration */
      if (ast_strlen_zero(p->fromdomain)) {
         ast_string_field_set(p, fromdomain, fromdomain);
      }
   } else {
      snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
      if (!ast_strlen_zero(p->theirtag))
         snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
      else
         snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
   }
   
   /* Fromdomain is what we are registering to, regardless of actual
      host name from SRV */
   if (!ast_strlen_zero(p->fromdomain)) {
      domainport = strrchr(p->fromdomain, ':');
      if (domainport) {
         *domainport++ = '\0'; /* trim off domainport from p->fromdomain */
         if (ast_strlen_zero(domainport))
            domainport = NULL;
      }     
      if (domainport) {       
         if (atoi(domainport) != STANDARD_SIP_PORT)
            snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
         else
            snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
      } else {
         if (r->portno && r->portno != STANDARD_SIP_PORT)
            snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
         else
            snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
      }
   } else {
      if (r->portno && r->portno != STANDARD_SIP_PORT)
         snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
      else
         snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
   }
   ast_string_field_set(p, uri, addr);

   p->branch ^= ast_random();

   init_req(&req, sipmethod, addr);

   /* Add to CSEQ */
   snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
   p->ocseq = r->ocseq;

   build_via(p);
   add_header(&req, "Via", p->via);
   add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
   add_header(&req, "From", from);
   add_header(&req, "To", to);
   add_header(&req, "Call-ID", p->callid);
   add_header(&req, "CSeq", tmp);
   if (!ast_strlen_zero(global_useragent))
      add_header(&req, "User-Agent", global_useragent);

   
   if (auth)   /* Add auth header */
      add_header(&req, authheader, auth);
   else if (!ast_strlen_zero(r->nonce)) {
      char digest[1024];

      /* We have auth data to reuse, build a digest header.
       * Note, this is not always useful because some parties do not
       * like nonces to be reused (for good reasons!) so they will
       * challenge us anyways.
       */
      if (sipdebug)
         ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
      ast_string_field_set(p, realm, r->realm);
      ast_string_field_set(p, nonce, r->nonce);
      ast_string_field_set(p, domain, r->domain);
      ast_string_field_set(p, opaque, r->opaque);
      ast_string_field_set(p, qop, r->qop);
      p->noncecount = ++r->noncecount;

      memset(digest, 0, sizeof(digest));
      if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
         add_header(&req, "Authorization", digest);
      else
         ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
   
   }

   snprintf(tmp, sizeof(tmp), "%d", r->expiry);
   add_header(&req, "Expires", tmp);
   add_header(&req, "Contact", p->our_contact);

   initialize_initreq(p, &req);
   if (sip_debug_test_pvt(p)) {
      ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
   }
   r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
   r->regattempts++; /* Another attempt */
   ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
   res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
   dialog_unref(p, "p is finished here at the end of transmit_register");
   return res;
}
static int transmit_reinvite_with_sdp ( struct sip_pvt p,
int  t38version,
int  oldsdp 
) [static]

Transmit reinvite with SDP.

Note:
A re-invite is basically a new INVITE with the same CALL-ID and TAG as the INVITE that opened the SIP dialogue We reinvite so that the audio stream (RTP) go directly between the SIP UAs. SIP Signalling stays with * in the path.

If t38version is TRUE, we send T38 SDP for re-invite from audio/video to T38 UDPTL transmission on the channel

If oldsdp is TRUE then the SDP version number is not incremented. This is needed for Session-Timers so we can send a re-invite to refresh the SIP session without modifying the media session.

Definition at line 10997 of file chan_sip.c.

References add_header(), add_sdp(), add_supported_header(), ALLOWED_METHODS, append_history, ast_set_flag, ast_test_flag, sip_pvt::do_history, FALSE, sip_pvt::flags, initialize_initreq(), sip_pvt::lastinvite, sip_pvt::ocseq, sip_pvt::offered_media, reqprep(), send_request(), SIP_INVITE, SIP_OUTGOING, SIP_REINVITE_UPDATE, SIP_UPDATE, TRUE, and XMIT_CRITICAL.

Referenced by check_pendings(), handle_response_invite(), interpret_t38_parameters(), proc_session_timer(), sip_sendhtml(), sip_set_rtp_peer(), and sip_set_udptl_peer().

{
   struct sip_request req;
   
   reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);

   add_header(&req, "Allow", ALLOWED_METHODS);
   add_supported_header(p, &req);
   if (sipdebug) {
      if (oldsdp == TRUE)
         add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
      else
         add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
   }

   if (p->do_history)
      append_history(p, "ReInv", "Re-invite sent");
   memset(p->offered_media, 0, sizeof(p->offered_media));

   if (t38version)
      add_sdp(&req, p, oldsdp, FALSE, TRUE);
   else
      add_sdp(&req, p, oldsdp, TRUE, FALSE);

   /* Use this as the basis */
   initialize_initreq(p, &req);
   p->lastinvite = p->ocseq;
   ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */

   return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
}
static int transmit_request ( struct sip_pvt p,
int  sipmethod,
int  inc,
enum xmittype  reliable,
int  newbranch 
) [static]

Transmit generic SIP request returns XMIT_ERROR if transmit failed with a critical error (don't retry)

Definition at line 12424 of file chan_sip.c.

References add_header(), sip_pvt::answered_elsewhere, INV_CONFIRMED, sip_pvt::invitestate, sip_pvt::ocseq, reqprep(), send_request(), SIP_ACK, and SIP_CANCEL.

Referenced by check_pendings(), handle_response(), handle_response_invite(), and sip_hangup().

{
   struct sip_request resp;
   
   if (sipmethod == SIP_ACK)
      p->invitestate = INV_CONFIRMED;

   reqprep(&resp, p, sipmethod, seqno, newbranch);
   if (sipmethod == SIP_CANCEL && p->answered_elsewhere) 
      add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");

   return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
}
static int transmit_request_with_auth ( struct sip_pvt p,
int  sipmethod,
int  seqno,
enum xmittype  reliable,
int  newbranch 
) [static]

Transmit SIP request, auth added.

Definition at line 12454 of file chan_sip.c.

References add_header(), ast_cause2str(), ast_log(), ast_strlen_zero(), auth_headers(), sip_invite_param::auth_type, buf, build_reply_digest(), sip_pvt::callid, dummy(), sip_pvt::hangupcause, LOG_WARNING, sip_pvt::ocseq, sip_pvt::options, PROXY_AUTH, sip_pvt::realm, reqprep(), send_request(), and SIP_BYE.

Referenced by __sip_autodestruct(), check_pendings(), and sip_hangup().

{
   struct sip_request resp;
   
   reqprep(&resp, p, sipmethod, seqno, newbranch);
   if (!ast_strlen_zero(p->realm)) {
      char digest[1024];

      memset(digest, 0, sizeof(digest));
      if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
         char *dummy, *response;
         enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
         auth_headers(code, &dummy, &response);
         add_header(&resp, response, digest);
      } else
         ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
   }
   /* If we are hanging up and know a cause for that, send it in clear text to make
      debugging easier. */
   if (sipmethod == SIP_BYE)  {
      char buf[10];

      add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
      snprintf(buf, sizeof(buf), "%d", p->hangupcause);
      add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
   }

   return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
}
static int transmit_response_reliable ( struct sip_pvt p,
const char *  msg,
const struct sip_request req 
) [static]

Transmit response, Make sure you get an ACK This is only used for responses to INVITEs, where we need to make sure we get an ACK.

Definition at line 10193 of file chan_sip.c.

References __transmit_response(), sip_request::ignore, XMIT_CRITICAL, and XMIT_UNRELIABLE.

Referenced by handle_incoming(), handle_invite_replaces(), handle_request_bye(), handle_request_cancel(), handle_request_invite(), handle_request_subscribe(), interpret_t38_parameters(), sip_hangup(), sip_indicate(), sip_sipredirect(), and sip_t38_abort().

static int transmit_response_using_temp ( ast_string_field  callid,
struct sockaddr_in *  sin,
int  useglobal_nat,
const int  intended_method,
const struct sip_request req,
const char *  msg 
) [static]

Transmit response, no retransmits, using a temporary pvt structure.

Definition at line 10108 of file chan_sip.c.

References __transmit_response(), ast_copy_flags, ast_log(), ast_random(), ast_sip_ouraddrfor(), ast_string_field_init, ast_string_field_set, ast_test_flag, ast_threadstorage_get(), sip_pvt::branch, build_via(), copy_socket_data(), do_setnat(), sip_pvt::flags, sip_pvt::fromdomain, INITIAL_CSEQ, internip, LOG_ERROR, make_our_tag(), sip_pvt::method, sip_pvt::ocseq, sip_pvt::ourip, sip_pvt::recv, sip_pvt::sa, SIP_NAT, SIP_NAT_ROUTE, sip_request::socket, sip_pvt::socket, sip_pvt::tag, and XMIT_UNRELIABLE.

Referenced by find_call().

{
   struct sip_pvt *p = NULL;

   if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
      ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
      return -1;
   }

   /* XXX the structure may be dirty from previous usage.
    * Here we should state clearly how we should reinitialize it
    * before using it.
    * E.g. certainly the threadstorage should be left alone,
    * but other thihngs such as flags etc. maybe need cleanup ?
    */
    
   /* Initialize the bare minimum */
   p->method = intended_method;

   if (!sin)
      p->ourip = internip;
   else {
      p->sa = *sin;
      ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
   }

   p->branch = ast_random();
   make_our_tag(p->tag, sizeof(p->tag));
   p->ocseq = INITIAL_CSEQ;

   if (useglobal_nat && sin) {
      ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
      p->recv = *sin;
      do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
   }

   ast_string_field_set(p, fromdomain, default_fromdomain);
   build_via(p);
   ast_string_field_set(p, callid, callid);

   copy_socket_data(&p->socket, &req->socket);

   /* Use this temporary pvt structure to send the message */
   __transmit_response(p, msg, req, XMIT_UNRELIABLE);

   /* Free the string fields, but not the pool space */
   ast_string_field_init(p, 0);

   return 0;
}
static int transmit_response_with_allow ( struct sip_pvt p,
const char *  msg,
const struct sip_request req,
enum xmittype  reliable 
) [static]

Append Accept header, content length before transmitting response.

Definition at line 10220 of file chan_sip.c.

References add_header(), respprep(), and send_response().

Referenced by handle_incoming(), and handle_request_options().

{
   struct sip_request resp;
   respprep(&resp, p, msg, req);
   add_header(&resp, "Accept", "application/sdp");
   return send_response(p, &resp, reliable, 0);
}
static int transmit_response_with_auth ( struct sip_pvt p,
const char *  msg,
const struct sip_request req,
const char *  rand,
enum xmittype  reliable,
const char *  header,
int  stale 
) [static]

Respond with authorization request.

Definition at line 10229 of file chan_sip.c.

References add_header(), append_history, ast_log(), get_header(), LOG_WARNING, sip_pvt::noncecount, sip_settings::realm, respprep(), send_response(), sip_cfg, and sip_pvt::username.

Referenced by check_auth(), and transmit_fake_auth_response().

{
   struct sip_request resp;
   char tmp[512];
   int seqno = 0;

   if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
      ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
      return -1;
   }
   /* Stale means that they sent us correct authentication, but 
      based it on an old challenge (nonce) */
   snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
   respprep(&resp, p, msg, req);
   add_header(&resp, header, tmp);
   append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
   return send_response(p, &resp, reliable, seqno);
}
static int transmit_response_with_date ( struct sip_pvt p,
const char *  msg,
const struct sip_request req 
) [static]

Append date and content length before transmitting response.

Definition at line 10211 of file chan_sip.c.

References append_date(), respprep(), send_response(), and XMIT_UNRELIABLE.

Referenced by handle_response_subscribe(), and register_verify().

{
   struct sip_request resp;
   respprep(&resp, p, msg, req);
   append_date(&resp);
   return send_response(p, &resp, XMIT_UNRELIABLE, 0);
}
static int transmit_response_with_minse ( struct sip_pvt p,
const char *  msg,
const struct sip_request req,
int  minse_int 
) [static]

Transmit 422 response with Min-SE header (Session-Timers)

Definition at line 10176 of file chan_sip.c.

References add_header(), append_date(), respprep(), send_response(), and XMIT_UNRELIABLE.

Referenced by handle_request_invite().

{
   struct sip_request resp;
   char minse_str[20];

   respprep(&resp, p, msg, req);
   append_date(&resp);

   snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
   add_header(&resp, "Min-SE", minse_str);
   return send_response(p, &resp, XMIT_UNRELIABLE, 0);
}
static int transmit_response_with_sdp ( struct sip_pvt p,
const char *  msg,
const struct sip_request req,
enum xmittype  reliable,
int  oldsdp 
) [static]

Used for 200 OK and 183 early media.

Returns:
Will return XMIT_ERROR for network errors.

Definition at line 10914 of file chan_sip.c.

References add_sdp(), ast_debug, ast_log(), ast_rtp_codec_setpref(), ast_test_flag, sip_pvt::autoframing, sip_pvt::callid, FALSE, sip_pvt::flags, get_header(), LOG_ERROR, LOG_WARNING, sip_pvt::pendinginvite, sip_pvt::prefs, respprep(), sip_pvt::rtp, send_response(), SIP_OUTGOING, t38properties::state, sip_pvt::t38, T38_ENABLED, TRUE, and try_suggested_sip_codec().

Referenced by handle_invite_replaces(), handle_request_invite(), send_provisional_keepalive_full(), sip_answer(), and transmit_provisional_response().

{
   struct sip_request resp;
   int seqno;
   if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
      ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
      return -1;
   }
   respprep(&resp, p, msg, req);
   if (p->rtp) {
      if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
         ast_debug(1, "Setting framing from config on incoming call\n");
         ast_rtp_codec_setpref(p->rtp, &p->prefs);
      }
      try_suggested_sip_codec(p);
      if (p->t38.state == T38_ENABLED) {
         add_sdp(&resp, p, oldsdp, TRUE, TRUE);
      } else {
         add_sdp(&resp, p, oldsdp, TRUE, FALSE);
      }
   } else 
      ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
   if (reliable && !p->pendinginvite)
      p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
   return send_response(p, &resp, reliable, seqno);
}
static int transmit_response_with_t38_sdp ( struct sip_pvt p,
char *  msg,
struct sip_request req,
int  retrans 
) [static]

Used for 200 OK and 183 early media.

Definition at line 10864 of file chan_sip.c.

References add_sdp(), ast_log(), sip_pvt::callid, get_header(), LOG_ERROR, LOG_WARNING, sip_pvt::pendinginvite, respprep(), send_response(), and sip_pvt::udptl.

Referenced by handle_request_invite(), and interpret_t38_parameters().

{
   struct sip_request resp;
   int seqno;
   
   if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
      ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
      return -1;
   }
   respprep(&resp, p, msg, req);
   if (p->udptl) {
      add_sdp(&resp, p, 0, 0, 1);
   } else 
      ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
   if (retrans && !p->pendinginvite)
      p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
   return send_response(p, &resp, retrans, seqno);
}
static int transmit_response_with_unsupported ( struct sip_pvt p,
const char *  msg,
const struct sip_request req,
const char *  unsupported 
) [static]

Transmit response, no retransmits.

Definition at line 10166 of file chan_sip.c.

References add_header(), append_date(), respprep(), send_response(), and XMIT_UNRELIABLE.

Referenced by handle_request_invite().

{
   struct sip_request resp;
   respprep(&resp, p, msg, req);
   append_date(&resp);
   add_header(&resp, "Unsupported", unsupported);
   return send_response(p, &resp, XMIT_UNRELIABLE, 0);
}
static int transmit_state_notify ( struct sip_pvt p,
int  state,
int  full,
int  timeout 
) [static]

Used in the SUBSCRIBE notification subsystem (RFC3265)

Definition at line 11543 of file chan_sip.c.

References add_content(), add_header(), ast_channel_search_locked(), ast_channel_unlock, ast_copy_string(), AST_DEVICE_UNAVAILABLE, AST_EXTENSION_BUSY, AST_EXTENSION_DEACTIVATED, AST_EXTENSION_INUSE, AST_EXTENSION_NOT_INUSE, AST_EXTENSION_ONHOLD, AST_EXTENSION_REMOVED, AST_EXTENSION_RINGING, AST_EXTENSION_UNAVAILABLE, ast_get_hint(), ast_log(), AST_MAX_EXTENSION, ast_str_alloca, ast_str_append(), ast_strdupa, ast_strlen_zero(), sip_pvt::callid, ast_channel::cid, ast_callerid::cid_name, ast_callerid::cid_num, sip_pvt::context, CPIM_PIDF_XML, DIALOG_INFO_XML, sip_pvt::dialogver, cfsubscription_types::event, sip_pvt::expiry, sip_pvt::exten, find_calling_channel(), find_subscription_type(), sip_pvt::fromdomain, get_header(), get_in_brackets(), sip_pvt::initreq, LOG_WARNING, cfsubscription_types::mediatype, NONE, sip_settings::notifycid, sip_settings::notifyringing, sip_pvt::ocseq, sip_settings::pedanticsipchecking, sip_pvt::pendinginvite, PIDF_XML, remove_uri_parameters(), reqprep(), send_request(), sip_cfg, SIP_NOTIFY, strsep(), sip_pvt::subscribed, sip_pvt::tag, sip_pvt::theirtag, XMIT_RELIABLE, and XPIDF_XML.

Referenced by __sip_autodestruct(), cb_extensionstate(), and handle_request_subscribe().

{
   struct ast_str *tmp = ast_str_alloca(4000);
   char from[256], to[256];
   char *c, *mfrom, *mto;
   struct sip_request req;
   char hint[AST_MAX_EXTENSION];
   char *statestring = "terminated";
   const struct cfsubscription_types *subscriptiontype;
   enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
   char *pidfstate = "--";
   char *pidfnote= "Ready";
   
   memset(from, 0, sizeof(from));
   memset(to, 0, sizeof(to));

   switch (state) {
   case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
      statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
      local_state = NOTIFY_INUSE;
      pidfstate = "busy";
      pidfnote = "Ringing";
      break;
   case AST_EXTENSION_RINGING:
      statestring = "early";
      local_state = NOTIFY_INUSE;
      pidfstate = "busy";
      pidfnote = "Ringing";
      break;
   case AST_EXTENSION_INUSE:
      statestring = "confirmed";
      local_state = NOTIFY_INUSE;
      pidfstate = "busy";
      pidfnote = "On the phone";
      break;
   case AST_EXTENSION_BUSY:
      statestring = "confirmed";
      local_state = NOTIFY_CLOSED;
      pidfstate = "busy";
      pidfnote = "On the phone";
      break;
   case AST_EXTENSION_UNAVAILABLE:
      statestring = "terminated";
      local_state = NOTIFY_CLOSED;
      pidfstate = "away";
      pidfnote = "Unavailable";
      break;
   case AST_EXTENSION_ONHOLD:
      statestring = "confirmed";
      local_state = NOTIFY_CLOSED;
      pidfstate = "busy";
      pidfnote = "On hold";
      break;
   case AST_EXTENSION_NOT_INUSE:
   default:
      /* Default setting */
      break;
   }

   subscriptiontype = find_subscription_type(p->subscribed);
   
   /* Check which device/devices we are watching  and if they are registered */
   if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
      char *hint2 = hint, *individual_hint = NULL;
      int hint_count = 0, unavailable_count = 0;

      while ((individual_hint = strsep(&hint2, "&"))) {
         hint_count++;

         if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
            unavailable_count++;
      }

      /* If none of the hinted devices are registered, we will
       * override notification and show no availability.
       */
      if (hint_count > 0 && hint_count == unavailable_count) {
         local_state = NOTIFY_CLOSED;
         pidfstate = "away";
         pidfnote = "Not online";
      }
   }

   ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
   c = get_in_brackets(from);
   if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
      ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
      return -1;
   }
   
   mfrom = remove_uri_parameters(c);

   ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
   c = get_in_brackets(to);
   if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
      ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
      return -1;
   }
   mto = remove_uri_parameters(c);

   reqprep(&req, p, SIP_NOTIFY, 0, 1);

   
   add_header(&req, "Event", subscriptiontype->event);
   add_header(&req, "Content-Type", subscriptiontype->mediatype);
   switch(state) {
   case AST_EXTENSION_DEACTIVATED:
      if (timeout)
         add_header(&req, "Subscription-State", "terminated;reason=timeout");
      else {
         add_header(&req, "Subscription-State", "terminated;reason=probation");
         add_header(&req, "Retry-After", "60");
      }
      break;
   case AST_EXTENSION_REMOVED:
      add_header(&req, "Subscription-State", "terminated;reason=noresource");
      break;
   default:
      if (p->expiry)
         add_header(&req, "Subscription-State", "active");
      else  /* Expired */
         add_header(&req, "Subscription-State", "terminated;reason=timeout");
   }
   switch (p->subscribed) {
   case XPIDF_XML:
   case CPIM_PIDF_XML:
      ast_str_append(&tmp, 0,
         "<?xml version=\"1.0\"?>\n"
         "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
         "<presence>\n");
      ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
      ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
      ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
      ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
      ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
      ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
      break;
   case PIDF_XML: /* Eyebeam supports this format */
      ast_str_append(&tmp, 0,
         "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
         "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" \nxmlns:pp=\"urn:ietf:params:xml:ns:pidf:person\"\nxmlns:es=\"urn:ietf:params:xml:ns:pidf:rpid:status:rpid-status\"\nxmlns:ep=\"urn:ietf:params:xml:ns:pidf:rpid:rpid-person\"\nentity=\"%s\">\n", mfrom);
      ast_str_append(&tmp, 0, "<pp:person><status>\n");
      if (pidfstate[0] != '-')
         ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
      ast_str_append(&tmp, 0, "</status></pp:person>\n");
      ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
      ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
      ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
      if (pidfstate[0] == 'b') /* Busy? Still open ... */
         ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
      else
         ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
      ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
      break;
   case DIALOG_INFO_XML: /* SNOM subscribes in this format */
      ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
      ast_str_append(&tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full" : "partial", mto);
      if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
         const char *local_display = p->exten;
         char *local_target = mto;

         /* There are some limitations to how this works.  The primary one is that the
            callee must be dialing the same extension that is being monitored.  Simply dialing
            the hint'd device is not sufficient. */
         if (sip_cfg.notifycid) {
            struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);

            if (caller) {
               int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
               local_target = alloca(need);
               snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
               if (!(ast_strlen_zero(caller->cid.cid_name))) {
                  local_display = ast_strdupa(caller->cid.cid_name);
               }
               ast_channel_unlock(caller);
               caller = NULL;
            }
            /* We create a fake call-id which the phone will send back in an INVITE
             * Replaces header which we can grab and do some magic with. */
            if (sip_cfg.pedanticsipchecking) {
               ast_str_append(&tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
                  p->exten, p->callid, p->theirtag, p->tag);
            } else {
               ast_str_append(&tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
                  p->exten, p->callid);
            }
            ast_str_append(&tmp, 0, 
                  "<remote>\n"
                  /* See the limitations of this above.  Luckily the phone seems to still be
                     happy when these values are not correct. */
                  "<identity display=\"%s\">%s</identity>\n"
                  "<target uri=\"%s\"/>\n"
                  "</remote>\n"
                  "<local>\n"
                  "<identity>%s</identity>\n"
                  "<target uri=\"%s\"/>\n"
                  "</local>\n",
                  local_display, local_target, local_target, mto, mto);
         } else {
            ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
         }
      } else {
         ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
      }
      ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
      if (state == AST_EXTENSION_ONHOLD) {
         ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
                                         "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
                                         "</target>\n</local>\n", mto);
      }
      ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
      break;
   case NONE:
   default:
      break;
   }

   add_content(&req, tmp->str);

   p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */

   return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}
static void try_suggested_sip_codec ( struct sip_pvt p) [static]

Try setting codec suggested by the SIP_CODEC channel variable.

Definition at line 6378 of file chan_sip.c.

References ast_getformatbyname(), ast_log(), sip_pvt::capability, sip_pvt::jointcapability, LOG_NOTICE, sip_pvt::owner, and pbx_builtin_getvar_helper().

Referenced by sip_answer(), and transmit_response_with_sdp().

{
   int fmt;
   const char *codec;

   codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
   if (!codec) 
      return;

   fmt = ast_getformatbyname(codec);
   if (fmt) {
      ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
      if (p->jointcapability & fmt) {
         p->jointcapability &= fmt;
         p->capability &= fmt;
      } else
         ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
   } else
      ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
   return;  
}
static void unlink_marked_peers_from_tables ( void  ) [static]

Definition at line 3253 of file chan_sip.c.

References ao2_t_callback, OBJ_MULTIPLE, OBJ_NODATA, OBJ_UNLINK, and peer_is_marked().

Referenced by sip_do_reload(), and sip_prune_realtime().

{
   ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
                  "initiating callback to remove marked peers");
   ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
                  "initiating callback to remove marked peers");
}
static void unlink_peer_from_tables ( struct sip_peer peer) [static]

Definition at line 3262 of file chan_sip.c.

References sip_peer::addr, and ao2_t_unlink.

Referenced by expire_register().

{
   ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
   if (peer->addr.sin_addr.s_addr) {
      ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
   }
}
static int unload_module ( void  ) [static]

PBX unload module API.

Definition at line 26555 of file chan_sip.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_t_iterator_next, ao2_t_ref, ARRAY_LEN, ast_channel_unregister(), ast_cli_unregister_multiple(), ast_context_destroy(), ast_context_find(), ast_custom_function_unregister(), ast_free, ast_free_ha(), ast_manager_unregister(), ast_mutex_lock(), ast_mutex_unlock(), AST_PTHREADT_NULL, AST_PTHREADT_STOP, ast_rtp_proto_unregister(), ast_sched_dump(), ast_softhangup(), AST_SOFTHANGUP_APPUNLOAD, ast_tcptls_server_stop(), ast_udptl_proto_unregister(), ast_unload_realtime(), ast_unregister_application(), ASTOBJ_CONTAINER_DESTROY, ASTOBJ_CONTAINER_DESTROYALL, ast_tls_config::cafile, ast_tls_config::capath, ast_tls_config::certfile, ast_tls_config::cipher, clear_realm_authentication(), clear_sip_domains(), default_tls_cfg, dialog_unlink_all(), ast_tcptls_session_args::master, monlock, sip_pvt::owner, regl, sched_context_destroy(), sip_registry_destroy(), sip_subscribe_mwi_destroy(), sip_threadinfo::stop, submwil, thread, sip_threadinfo::threadid, and TRUE.

{
   struct sip_pvt *p;
   struct sip_threadinfo *th;
   struct ast_context *con;
   struct ao2_iterator i;

   ast_sched_dump(sched);
   
   /* First, take us out of the channel type list */
   ast_channel_unregister(&sip_tech);

   /* Unregister dial plan functions */
   ast_custom_function_unregister(&sipchaninfo_function);
   ast_custom_function_unregister(&sippeer_function);
   ast_custom_function_unregister(&sip_header_function);
   ast_custom_function_unregister(&checksipdomain_function);

   /* Unregister dial plan applications */
   ast_unregister_application(app_dtmfmode);
   ast_unregister_application(app_sipaddheader);
   ast_unregister_application(app_sipremoveheader);

   /* Unregister CLI commands */
   ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));

   /* Disconnect from the RTP subsystem */
   ast_rtp_proto_unregister(&sip_rtp);

   /* Disconnect from UDPTL */
   ast_udptl_proto_unregister(&sip_udptl);

   /* Unregister AMI actions */
   ast_manager_unregister("SIPpeers");
   ast_manager_unregister("SIPshowpeer");
   ast_manager_unregister("SIPqualifypeer");
   ast_manager_unregister("SIPshowregistry");
   ast_manager_unregister("SIPnotify");
   
   /* Kill TCP/TLS server threads */
   if (sip_tcp_desc.master)
      ast_tcptls_server_stop(&sip_tcp_desc);
   if (sip_tls_desc.master)
      ast_tcptls_server_stop(&sip_tls_desc);

   /* Kill all existing TCP/TLS threads */
   i = ao2_iterator_init(threadt, 0);
   while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
      pthread_t thread = th->threadid;
      th->stop = 1;
      pthread_kill(thread, SIGURG);
      pthread_join(thread, NULL);
      ao2_t_ref(th, -1, "decrement ref from iterator");
   }
   ao2_iterator_destroy(&i);

   /* Hangup all dialogs if they have an owner */
   i = ao2_iterator_init(dialogs, 0);
   while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
      if (p->owner)
         ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
      ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
   }
   ao2_iterator_destroy(&i);

   ast_mutex_lock(&monlock);
   if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
      pthread_cancel(monitor_thread);
      pthread_kill(monitor_thread, SIGURG);
      pthread_join(monitor_thread, NULL);
   }
   monitor_thread = AST_PTHREADT_STOP;
   ast_mutex_unlock(&monlock);

   /* Destroy all the dialogs and free their memory */
   i = ao2_iterator_init(dialogs, 0);
   while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
      dialog_unlink_all(p, TRUE, TRUE);
      ao2_t_ref(p, -1, "throw away iterator result"); 
   }
   ao2_iterator_destroy(&i);

   /* Free memory for local network address mask */
   ast_free_ha(localaddr);

   clear_realm_authentication(authl);


   if (default_tls_cfg.certfile)
      ast_free(default_tls_cfg.certfile);
   if (default_tls_cfg.cipher)
      ast_free(default_tls_cfg.cipher);
   if (default_tls_cfg.cafile)
      ast_free(default_tls_cfg.cafile);
   if (default_tls_cfg.capath)
      ast_free(default_tls_cfg.capath);

   ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
   ASTOBJ_CONTAINER_DESTROY(&regl);
   ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
   ASTOBJ_CONTAINER_DESTROY(&submwil);

   ao2_t_ref(peers, -1, "unref the peers table");
   ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
   ao2_t_ref(dialogs, -1, "unref the dialogs table");
   ao2_t_ref(threadt, -1, "unref the thread table");

   clear_sip_domains();
   ast_free_ha(global_contact_ha);
   close(sipsock);
   sched_context_destroy(sched);
   con = ast_context_find(used_context);
   if (con)
      ast_context_destroy(con, "SIP");
   ast_unload_realtime("sipregs");
   ast_unload_realtime("sippeers");

   return 0;
}
static int update_call_counter ( struct sip_pvt fup,
int  event 
) [static]

update_call_counter: Handle call_limit for SIP devices Setting a call-limit will cause calls above the limit not to be accepted.

Remember that for a type=friend, there's one limit for the user and another for the peer, not a combined call limit. This will cause unexpected behaviour in subscriptions, since a "friend" is *two* devices in Asterisk, not one.

Thought: For realtime, we should probably update storage with inuse counter...

Returns:
0 if call is ok (no call limit, below threshold) -1 on rejection of call

Definition at line 5849 of file chan_sip.c.

References ao2_lock(), ao2_unlock(), ast_clear_flag, ast_copy_string(), ast_debug, AST_DEVICE_UNKNOWN, ast_devstate_changed(), ast_log(), ast_set_flag, ast_strlen_zero(), ast_test_flag, sip_peer::call_limit, DEC_CALL_LIMIT, DEC_CALL_RINGING, FALSE, find_peer(), FINDALLDEVICES, sip_pvt::flags, INC_CALL_LIMIT, INC_CALL_RINGING, sip_peer::inRinging, sip_peer::inUse, inuse, LOG_ERROR, LOG_NOTICE, sip_peer::name, name, sip_settings::notifyhold, sip_pvt::outgoing_call, sip_pvt::peername, SIP_CALL_LIMIT, sip_cfg, SIP_INC_COUNT, SIP_INC_RINGING, SIP_PAGE2_CALL_ONHOLD, sip_peer_hold(), sip_pvt_lock, sip_pvt_unlock, TRUE, unref_peer(), and sip_pvt::username.

Referenced by __sip_destroy(), handle_request_cancel(), handle_request_invite(), handle_response_invite(), sip_call(), and sip_hangup().

{
   char name[256];
   int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
   int outgoing = fup->outgoing_call;
   struct sip_peer *p = NULL;

   ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");


   /* Test if we need to check call limits, in order to avoid 
      realtime lookups if we do not need it */
   if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
      return 0;

   ast_copy_string(name, fup->username, sizeof(name));

   /* Check the list of devices */
   if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) { 
      inuse = &p->inUse;
      call_limit = &p->call_limit;
      inringing = &p->inRinging;
      ast_copy_string(name, fup->peername, sizeof(name));
   }
   if (!p) {
      ast_debug(2, "%s is not a local device, no call limit\n", name);
      return 0;
   }

   switch(event) {
   /* incoming and outgoing affects the inUse counter */
   case DEC_CALL_LIMIT:
      /* Decrement inuse count if applicable */
      if (inuse) {
         sip_pvt_lock(fup);
         ao2_lock(p);
         if (*inuse > 0) {
            if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
               (*inuse)--;
               ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
            }
         } else {
            *inuse = 0;
         }
         ao2_unlock(p);
         sip_pvt_unlock(fup);
      }

      /* Decrement ringing count if applicable */
      if (inringing) {
         sip_pvt_lock(fup);
         ao2_lock(p);
         if (*inringing > 0) {
            if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
               (*inringing)--;
               ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
            }
         } else {
            *inringing = 0;
         }
         ao2_unlock(p);
         sip_pvt_unlock(fup);
      }

      /* Decrement onhold count if applicable */
      sip_pvt_lock(fup);
      ao2_lock(p);
      if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
         ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
         ao2_unlock(p);
         sip_pvt_unlock(fup);
         sip_peer_hold(fup, FALSE);
      } else {
         ao2_unlock(p);
         sip_pvt_unlock(fup);
      }
      if (sipdebug)
         ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
      break;

   case INC_CALL_RINGING:
   case INC_CALL_LIMIT:
      /* If call limit is active and we have reached the limit, reject the call */
      if (*call_limit > 0 ) {
         if (*inuse >= *call_limit) {
            ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
            unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
            return -1; 
         }
      }
      if (inringing && (event == INC_CALL_RINGING)) {
         sip_pvt_lock(fup);
         ao2_lock(p);
         if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
            (*inringing)++;
            ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
         }
         ao2_unlock(p);
         sip_pvt_unlock(fup);
      }
      if (inuse) {
         sip_pvt_lock(fup);
         ao2_lock(p);
         if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
            (*inuse)++;
            ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
         }
         ao2_unlock(p);
         sip_pvt_unlock(fup);
      }
      if (sipdebug) {
         ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
      }
      break;

   case DEC_CALL_RINGING:
      if (inringing) {
         sip_pvt_lock(fup);
         ao2_lock(p);
         if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
            if (*inringing > 0) {
               (*inringing)--;
            }
            ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
         }
         ao2_unlock(p);
         sip_pvt_unlock(fup);
      }
      break;

   default:
      ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
   }

   if (p) {
      ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
      unref_peer(p, "update_call_counter: unref_peer from call counter");
   } 
   return 0;
}
static void update_peer ( struct sip_peer p,
int  expire 
) [static]
static void update_provisional_keepalive ( struct sip_pvt pvt,
int  with_sdp 
) [static]

Definition at line 4389 of file chan_sip.c.

References ast_sched_add(), AST_SCHED_DEL_UNREF, dialog_ref(), dialog_unref(), PROVIS_KEEPALIVE_TIMEOUT, sip_pvt::provisional_keepalive_sched_id, send_provisional_keepalive(), and send_provisional_keepalive_with_sdp().

Referenced by transmit_provisional_response().

{
   AST_SCHED_DEL_UNREF(sched, pvt->provisional_keepalive_sched_id, dialog_unref(pvt, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));

   pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
      with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
}

Variable Documentation

struct ast_module_info __MODULE_INFO_SECTION __mod_info = { __MODULE_INFO_GLOBALS .name = AST_MODULE, .flags = AST_MODFLAG_DEFAULT , .description = "Session Initiation Protocol (SIP)" , .key = ASTERISK_GPL_KEY , .buildopt_sum = AST_BUILDOPT_SUM, .load = load_module, .unload = unload_module, .reload = reload, } [static]

Definition at line 26679 of file chan_sip.c.

int apeerobjs = 0 [static]

Autocreated peer objects

Definition at line 1136 of file chan_sip.c.

char* app_dtmfmode = "SIPDtmfMode" [static]

Definition at line 26097 of file chan_sip.c.

char* app_sipaddheader = "SIPAddHeader" [static]

Definition at line 26098 of file chan_sip.c.

char* app_sipremoveheader = "SIPRemoveHeader" [static]

Definition at line 26099 of file chan_sip.c.

Definition at line 26679 of file chan_sip.c.

struct sip_auth* authl = NULL [static]

Authentication list for realm authentication.

Todo:
Move the sip_auth list to AST_LIST

Definition at line 2168 of file chan_sip.c.

int authlimit = DEFAULT_AUTHLIMIT [static]

Definition at line 558 of file chan_sip.c.

Definition at line 559 of file chan_sip.c.

struct sockaddr_in bindaddr [static]
unsigned int chan_idx [static]

Definition at line 857 of file chan_sip.c.

Initial value:
 {
   .name = "CHECKSIPDOMAIN",
   .read = func_check_sipdomain,
}

Definition at line 17840 of file chan_sip.c.

struct ast_cli_entry cli_sip[] [static]

SIP Cli commands definition.

Definition at line 26430 of file chan_sip.c.

const char config[] = "sip.conf" [static]

Main configuration file

Definition at line 572 of file chan_sip.c.

struct sockaddr_in debugaddr [static]

Definition at line 2234 of file chan_sip.c.

Referenced by sip_debug_test_addr(), sip_do_debug(), sip_do_debug_ip(), and sip_do_debug_peer().

char default_callerid[AST_MAX_EXTENSION] [static]

Definition at line 1023 of file chan_sip.c.

Referenced by build_rpid(), and initreqprep().

int default_expiry = DEFAULT_DEFAULT_EXPIRY [static]

Definition at line 521 of file chan_sip.c.

Referenced by handle_response_register(), parse_register_contact(), and sip_register().

char default_fromdomain[AST_MAX_EXTENSION] [static]

Definition at line 1024 of file chan_sip.c.

struct ast_jb_conf default_jbconf [static]

Global jitterbuffer configuration - by default, jb is disabled.

Definition at line 562 of file chan_sip.c.

char default_language[MAX_LANGUAGE] [static]

Definition at line 1022 of file chan_sip.c.

int default_maxcallbitrate [static]

Maximum bitrate for call

Definition at line 1032 of file chan_sip.c.

Referenced by build_peer(), set_peer_defaults(), and sip_alloc().

char default_mohinterpret[MAX_MUSICCLASS] [static]

Global setting for moh class to use when put on hold

Definition at line 1028 of file chan_sip.c.

char default_mohsuggest[MAX_MUSICCLASS] [static]

Global setting for moh class to suggest when putting a bridged channel on hold

Definition at line 1029 of file chan_sip.c.

char default_notifymime[AST_MAX_EXTENSION] [static]

Definition at line 1025 of file chan_sip.c.

char default_parkinglot[AST_MAX_CONTEXT] [static]

Parkinglot

Definition at line 1031 of file chan_sip.c.

struct ast_codec_pref default_prefs [static]

Default codec prefs

Definition at line 1033 of file chan_sip.c.

Referenced by reload_config(), set_peer_defaults(), sip_alloc(), sip_show_settings(), and temp_peer().

unsigned int default_primary_transport [static]

Default primary Transport (enum sip_transport) for outbound connections to devices

Definition at line 1035 of file chan_sip.c.

Referenced by build_peer(), and set_peer_defaults().

int default_qualify [static]

Default Qualify= setting

Definition at line 1026 of file chan_sip.c.

Referenced by set_peer_defaults().

Default TLS connection configuration.

Definition at line 2712 of file chan_sip.c.

Referenced by reload_config(), sip_prepare_socket(), sip_show_settings(), and unload_module().

unsigned int default_transports [static]

Default Transports (enum sip_transport) that are acceptable

Definition at line 1034 of file chan_sip.c.

Referenced by build_peer(), reload_config(), and set_peer_defaults().

char default_vmexten[AST_MAX_EXTENSION] [static]

Definition at line 1027 of file chan_sip.c.

Here we implement the container for dialogs (sip_pvt), defining generic wrapper functions to ease the transition from the current implementation (a single linked list) to a different container. In addition to a reference to the container, we need functions to lock/unlock the container and individual items, and functions to add/remove references to the individual items.

Definition at line 1745 of file chan_sip.c.

struct domain_list domain_list [static]

The SIP domain list

struct _map_x_s dtmfstr[] [static]

mapping between dtmf flags and strings

Definition at line 15478 of file chan_sip.c.

Referenced by conf_run(), handle_link_data(), handle_remote_data(), and send_dtmf().

int dumphistory [static]

Dump history to verbose before destroying SIP dialog

Definition at line 1102 of file chan_sip.c.

time_t externexpire [static]

Expiration counter for re-resolving external host name in dynamic DNS

Definition at line 2220 of file chan_sip.c.

Referenced by ast_sip_ouraddrfor().

char externhost[MAXHOSTNAMELEN] [static]

External host name

Definition at line 2219 of file chan_sip.c.

struct sockaddr_in externip [static]

our external IP address/port for SIP sessions. externip.sin_addr is only set when we know we might be behind a NAT, and this is done using a variety of (mutually exclusive) ways from the config file:

+ with "externip = host[:port]" we specify the address/port explicitly. The address is looked up only once when (re)loading the config file;

+ with "externhost = host[:port]" we do a similar thing, but the hostname is stored in externhost, and the hostname->IP mapping is refreshed every 'externrefresh' seconds;

+ with "stunaddr = host[:port]" we run queries every externrefresh seconds to the specified server, and store the result in externip.

Other variables (externhost, externexpire, externrefresh) are used to support the above functions. External IP address if we are behind NAT

Definition at line 2217 of file chan_sip.c.

Referenced by ast_sip_ouraddrfor(), reload_config(), and sip_show_settings().

int externrefresh = 10 [static]

Definition at line 2221 of file chan_sip.c.

Referenced by ast_sip_ouraddrfor().

struct _map_x_s faxecmodes[] [static]

Definition at line 15910 of file chan_sip.c.

Whether we send authentication failure manager events or not. Default no.

Definition at line 1107 of file chan_sip.c.

int global_autoframing [static]

Turn autoframing on or off.

Definition at line 1111 of file chan_sip.c.

Referenced by set_peer_defaults(), and sip_alloc().

int global_callcounter [static]

Enable call counters for all devices. This is currently enabled by setting the peer call-limit to INT_MAX. When we remove the call-limit from the code, we can make it with just a boolean flag in the device structure

Definition at line 1090 of file chan_sip.c.

int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263 [static]

Codecs that we support by default:

Definition at line 1118 of file chan_sip.c.

Referenced by set_peer_defaults(), sip_alloc(), and sip_new().

struct ast_ha* global_contact_ha = NULL [static]

Global list of addresses dynamic peers are not allowed to use.

Definition at line 1129 of file chan_sip.c.

unsigned int global_cos_audio [static]

802.1p class of service for audio RTP packets

Definition at line 1098 of file chan_sip.c.

unsigned int global_cos_sip [static]

802.1p class of service for SIP packets

Definition at line 1097 of file chan_sip.c.

unsigned int global_cos_text [static]

802.1p class of service for text RTP packets

Definition at line 1100 of file chan_sip.c.

unsigned int global_cos_video [static]

802.1p class of service for video RTP packets

Definition at line 1099 of file chan_sip.c.

Exclude static peers from contact registrations

Definition at line 1125 of file chan_sip.c.

struct ast_flags global_flags[2] = {{0}} [static]

global SIP_ flags

Definition at line 1140 of file chan_sip.c.

struct ast_jb_conf global_jbconf [static]

Global jitterbuffer configuration

Definition at line 570 of file chan_sip.c.

Referenced by reload_config(), sip_get_rtp_peer(), sip_new(), and sip_show_settings().

Match auth username if available instead of From: Default off.

Definition at line 1079 of file chan_sip.c.

int global_max_se [static]

Highest threshold for session refresh interval

Definition at line 1123 of file chan_sip.c.

Referenced by build_peer(), handle_request_invite(), set_peer_defaults(), and st_get_se().

int global_min_se [static]

Lowest threshold for session refresh interval

Definition at line 1122 of file chan_sip.c.

Referenced by build_peer(), set_peer_defaults(), and st_get_se().

Enable/disable premature frames in a call (causing 183 early media)

Definition at line 1082 of file chan_sip.c.

int global_qualify_gap [static]

Time between our group of peer pokes

Definition at line 1113 of file chan_sip.c.

Referenced by sip_poke_all_peers().

int global_qualify_peers [static]

Number of peers to poke at a given time

Definition at line 1114 of file chan_sip.c.

int global_qualifyfreq [static]

Qualify frequency

Definition at line 1112 of file chan_sip.c.

Referenced by build_peer(), and set_peer_defaults().

int global_reg_timeout [static]

Definition at line 1087 of file chan_sip.c.

int global_regattempts_max [static]

Registration attempts before giving up

Definition at line 1088 of file chan_sip.c.

char global_regcontext[AST_MAX_CONTEXT] [static]

Context for auto-extensions

Definition at line 1103 of file chan_sip.c.

Referenced by register_peer_exten().

static int global_relaxdtmf [static]

Relax DTMF

Definition at line 1081 of file chan_sip.c.

int global_rtpholdtimeout [static]

Time out call if no RTP during hold

Definition at line 1085 of file chan_sip.c.

Referenced by build_peer(), and set_peer_defaults().

int global_rtpkeepalive [static]

Send RTP keepalives

Definition at line 1086 of file chan_sip.c.

Referenced by build_peer(), and set_peer_defaults().

int global_rtptimeout [static]

Time out call if no RTP

Definition at line 1084 of file chan_sip.c.

Referenced by build_peer(), and set_peer_defaults().

char global_sdpowner[AST_MAX_EXTENSION] [static]

SDP owner name for the SIP channel

Definition at line 1106 of file chan_sip.c.

char global_sdpsession[AST_MAX_EXTENSION] [static]

SDP session name for the SIP channel

Definition at line 1105 of file chan_sip.c.

int global_shrinkcallerid [static]

enable or disable shrinking of caller id

Definition at line 1089 of file chan_sip.c.

enum st_mode global_st_mode [static]

Mode of operation for Session-Timers

Definition at line 1120 of file chan_sip.c.

Referenced by build_peer(), set_peer_defaults(), and st_get_mode().

Session-Timer refresher

Definition at line 1121 of file chan_sip.c.

Referenced by build_peer(), set_peer_defaults(), and st_get_refresher().

int global_t1 [static]

T1 time

Definition at line 1108 of file chan_sip.c.

Referenced by build_peer(), create_addr(), set_peer_defaults(), sip_alloc(), and sip_scheddestroy().

int global_t1min [static]

T1 roundtrip time minimum

Definition at line 1109 of file chan_sip.c.

int global_t38_maxdatagram [static]

global T.38 FaxMaxDatagram override

Definition at line 1141 of file chan_sip.c.

Referenced by handle_request_invite(), handle_t38_options(), set_peer_defaults(), and sip_alloc().

int global_timer_b [static]

Timer B - RFC 3261 Section 17.1.1.2

Definition at line 1110 of file chan_sip.c.

Referenced by build_peer(), create_addr(), set_peer_defaults(), sip_alloc(), and sip_scheddestroy().

unsigned int global_tos_audio [static]

IP type of service for audio RTP packets

Definition at line 1094 of file chan_sip.c.

unsigned int global_tos_sip [static]

IP type of service for SIP packets

Definition at line 1093 of file chan_sip.c.

unsigned int global_tos_text [static]

IP type of service for text RTP packets

Definition at line 1096 of file chan_sip.c.

unsigned int global_tos_video [static]

IP type of service for video RTP packets

Definition at line 1095 of file chan_sip.c.

char global_useragent[AST_MAX_EXTENSION] [static]

Useragent for the SIP channel

Definition at line 1104 of file chan_sip.c.

const int HASH_DIALOG_SIZE = 563 [static]

Definition at line 2023 of file chan_sip.c.

const int HASH_PEER_SIZE = 563 [static]

Size of peer hash table, prime number preferred!

Definition at line 2022 of file chan_sip.c.

struct _map_x_s insecurestr[] [static]

Definition at line 15499 of file chan_sip.c.

struct sockaddr_in internip [static]

our (internal) default address/port to put in SIP/SDP messages internip is initialized picking a suitable address from one of the interfaces, and the same port number we bind to. It is used as the default address/port in SIP messages, and as the default address (but not port) in SDP messages.

Definition at line 2197 of file chan_sip.c.

Referenced by ast_sip_ouraddrfor(), reload_config(), sip_alloc(), transmit_register(), and transmit_response_using_temp().

struct io_context* io [static]

The IO context

Definition at line 1162 of file chan_sip.c.

struct ast_ha* localaddr [static]

List of local networks We store "localnet" addresses from the config file into an access list, marked as 'DENY', so the call to ast_apply_ha() will return AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local' (i.e. presumably public) addresses.

List of local networks, on the same side of NAT as this Asterisk

Definition at line 2230 of file chan_sip.c.

char mandescr_show_peer[] = " ActionID: <id> Optional action ID for this AMI transaction.\n" [static]

Definition at line 15793 of file chan_sip.c.

char mandescr_show_peers[] = " ActionID: <id> Action ID for this transaction. Will be returned.\n" [static]

Definition at line 15188 of file chan_sip.c.

char mandescr_show_registry[] = " ActionID: <id> Action ID for this transaction. Will be returned.\n" [static]

Manager Action SIPShowRegistry description.

Definition at line 15142 of file chan_sip.c.

char mandescr_sipnotify[] = " ActionID: <id> Action ID for this transaction. Will be returned.\n" [static]

Definition at line 11925 of file chan_sip.c.

int max_expiry = DEFAULT_MAX_EXPIRY [static]

Maximum accepted registration time

Definition at line 520 of file chan_sip.c.

Referenced by handle_request_subscribe(), and parse_register_contact().

int min_expiry = DEFAULT_MIN_EXPIRY [static]

Minimum accepted registration time

Definition at line 519 of file chan_sip.c.

Referenced by handle_request_subscribe(), and parse_register_contact().

pthread_t monitor_thread = AST_PTHREADT_NULL [static]

This is the thread for the monitor which checks for input on the channels which are not currently in use.

Definition at line 1156 of file chan_sip.c.

ast_mutex_t monlock = AST_MUTEX_INIT_VALUE [static]

Protect the monitoring thread, so only one process can kill or start it, and not when it's doing something critical.

Definition at line 1150 of file chan_sip.c.

Referenced by do_monitor(), restart_monitor(), and unload_module().

int mwi_expiry = DEFAULT_MWI_EXPIRY [static]

Definition at line 522 of file chan_sip.c.

struct _map_x_s natmodes[] [static]

Definition at line 14923 of file chan_sip.c.

ast_mutex_t netlock = AST_MUTEX_INIT_VALUE [static]

Definition at line 1146 of file chan_sip.c.

Referenced by handle_request_do(), and reload_config().

const char notify_config[] = "sip_notify.conf" [static]

Configuration file for sending Notify with CLI commands to reconfigure or reboot phones

Definition at line 573 of file chan_sip.c.

struct ast_config* notify_types = NULL [static]

The list of manual NOTIFY types we know how to send

Definition at line 2236 of file chan_sip.c.

int ourport_tcp [static]

The port used for TCP connections

Definition at line 2232 of file chan_sip.c.

int ourport_tls [static]

The port used for TCP/TLS connections

Definition at line 2233 of file chan_sip.c.

The peer list: Users, Peers and Friends.

Definition at line 2028 of file chan_sip.c.

Referenced by chanavail_exec().

Definition at line 2029 of file chan_sip.c.

int recordhistory [static]

Record SIP history. Off by default

Definition at line 1101 of file chan_sip.c.

Referenced by sip_alloc().

struct _map_x_s referstatusstrings[] [static]

Definition at line 1488 of file chan_sip.c.

int regobjs = 0 [static]

Registry objects

Definition at line 1137 of file chan_sip.c.

Referenced by sip_send_all_registers().

struct _map_x_s regstatestrings[] [static]

Definition at line 11934 of file chan_sip.c.

int rpeerobjs = 0 [static]

Realtime peers

Definition at line 1135 of file chan_sip.c.

struct sched_context* sched [static]

The scheduling context

Definition at line 1161 of file chan_sip.c.

Initial value:
 {
   .name = "SIP_HEADER",
   .read = func_header_read,
}

Definition at line 17821 of file chan_sip.c.

ast_mutex_t sip_reload_lock = AST_MUTEX_INIT_VALUE [static]

Definition at line 1152 of file chan_sip.c.

Referenced by do_monitor(), and sip_reload().

int sip_reloading = FALSE [static]

Flag for avoiding multiple reloads at the same time

Definition at line 1158 of file chan_sip.c.

Referenced by do_monitor().

Reason for last reload/load of configuration

Definition at line 1159 of file chan_sip.c.

struct ast_rtp_protocol sip_rtp [static]

Interface structure with callbacks used to connect to RTP module.

Definition at line 2767 of file chan_sip.c.

The TCP server definition.

Definition at line 2715 of file chan_sip.c.

struct ast_channel_tech sip_tech [static]

Definition of this channel for PBX channel registration.

Definition at line 2671 of file chan_sip.c.

This version of the sip channel tech has no send_digit_begin callback so that the core knows that the channel does not want DTMF BEGIN frames. The struct is initialized just before registering the channel driver, and is for use with channels using SIP INFO DTMF.

Definition at line 2705 of file chan_sip.c.

Referenced by load_module(), and sip_new().

struct ast_tls_config sip_tls_cfg [static]

Working TLS connection configuration.

Definition at line 2709 of file chan_sip.c.

The TCP/TLS server definition.

Definition at line 2726 of file chan_sip.c.

struct ast_udptl_protocol sip_udptl [static]
Initial value:
 {
   type: "SIP",
   get_udptl_info: sip_get_udptl_peer,
   set_udptl_peer: sip_set_udptl_peer,
}

Interface structure with callbacks used to connect to UDPTL module.

Definition at line 3400 of file chan_sip.c.

Initial value:
 {
   .name = "SIPCHANINFO",
   .read = function_sipchaninfo_read,
}

Structure to declare a dialplan function: SIPCHANINFO.

Definition at line 18001 of file chan_sip.c.

enum sip_debug_e sipdebug [static]

Definition at line 1442 of file chan_sip.c.

int sipdebug_text [static]

extra debugging for 'text' related events. At the moment this is set together with sip_debug_console.

Note:
It should either go away or be implemented properly.

Definition at line 1448 of file chan_sip.c.

Initial value:
 {
   .name = "SIPPEER",
   .read = function_sippeer,
}

Structure to declare a dialplan function: SIPPEER.

Definition at line 17935 of file chan_sip.c.

int sipsock = -1 [static]

Main socket for UDP SIP communication.

sipsock is shared between the SIP manager thread (which handles reload requests), the udp io handler (sipsock_read()) and the user routines that issue udp writes (using __sip_xmit()). The socket is -1 only when opening fails (this is a permanent condition), or when we are handling a reload() that changes its address (this is a transient situation during which we might have a harmless race, see below). Because the conditions for the race to be possible are extremely rare, we don't want to pay the cost of locking on every I/O. Rather, we remember that when the race may occur, communication is bound to fail anyways, so we just live with this event and let the protocol handle this above us.

Definition at line 2187 of file chan_sip.c.

Referenced by sip_prepare_socket(), and sipsock_read().

int* sipsock_read_id [static]

ID of IO entry for sipsock FD

Definition at line 1163 of file chan_sip.c.

int speerobjs = 0 [static]

Static peers

Definition at line 1134 of file chan_sip.c.

struct _map_x_s stmodes[] [static]

Report Peer status in character string.

Returns:
0 if peer is unreachable, 1 if peer is online, -1 if unmonitored

Definition at line 14963 of file chan_sip.c.

struct _map_x_s strefreshers[] [static]

Definition at line 14981 of file chan_sip.c.

struct sockaddr_in stunaddr [static]

stun server address

Definition at line 2222 of file chan_sip.c.

Referenced by ast_sip_ouraddrfor(), reload_config(), and sip_show_settings().

struct ao2_container* threadt [static]

Definition at line 2025 of file chan_sip.c.

int unauth_sessions = 0 [static]

Definition at line 557 of file chan_sip.c.

char used_context[AST_MAX_CONTEXT] [static]

name of automatically created context for unloading

Definition at line 1143 of file chan_sip.c.