Asterisk pjsip.conf

asterisk pjsip.conf Описание параметров настройки pjsip в Asterisk. Подробное руководство на русском. Примеры и сравнения. pjsip vs sip.

Что такое PJSIP

PJSIP мультимедийная библиотека с открытым кодом, для реализации протоколов SIP, SDP, RTP, STUN, TURN и ICE. Она сочетает лучшие возможности SIP сигнализации, хорошую проходимость NAT и высокий уровень взаимодействия с приложениями. Подходит практически для любого типа систем, начиная от компьютеров и заканчивая встраиваемыми системами (embedded systems) и мобильными телефонами.

Формат файла pjsip.conf

Pjsip.conf обычный текстовый файл, как и все конфигурационные файлы Asterisk, состоит из секций. Каждая секция (раздел) определяет конфигурацию объекта res_pjsip. Секции отделены друг от друга именами, заключенными в квадратные скобки [какая неожиданность] и содержат одну или более конфигурационную опцию и её значение отделенное знаком равно.

[ SectionName ] 
ConfigOption = Value 
ConfigOption = Value

В большинстве случаев имена секций могут быть произвольными, однако в случае с типами ENDPOINT и AOR имена должны совпадать со заголовком SIP URI «To» для идентификации входящих SIP запросов. Каждая секция имеет обязательную опцию type=, которой определяется назначение секции в конфигурации объектов res_pjsip.

Ниже перечислены типы секций res_pjsip и простейшие примеры конфигурации.

Варианты и значения по умолчанию

Как узнать возможные варианты значений и параметры по умолчанию?
В этом поможет встроенная справка интерфейса командной строки (CLI):
config show help res_pjsip <configobject> <configoption>

Например: config show help res_pjsip endpoint rewrite_contact

config show  help  res_pjsip endpoint rewrite_contact
[endpoint]
rewrite_contact = [Boolean] (Default: no) (Regex: false)
 
Allow Contact header to be rewritten with the source IP address-port
 
 On inbound SIP messages from this endpoint, the Contact header or an
appropriate Record-Route header will be changed to have the source IP address
and port. This option does not affect outbound messages sent to this endpoint.

И видим. что параметр rewrite_contact имеет значение по умолчанию = no, тип значения Boolean, т.е. возможное значение = yes

Секция System

System settings

System settings

[system]

  • timer_t1=500 ; Установить значение таймера T1 в миллисекундах (default: «500»)
  • timer_b=32000 ; Установить значение таймера B в миллисекундах (default: «32000»)
  • compact_headers=no ; Использовать короткие формы имен SIP заголовков(default: «no»)
  • threadpool_initial_size=0 ; Initial number of threads in the res_pjsip threadpool (default: «0»)
  • threadpool_auto_increment=5 ; The amount by which the number of threads is incremented when necessary (default: «5»)
  • threadpool_idle_timeout=60 ; Number of seconds before an idle thread should be disposed of (default: «60»)
  • threadpool_max_size=0 ; Maximum number of threads in the res_pjsip threadpool. A value of 0 indicates no maximum (default: «0»)
  • disable_tcp_switch=yes ; Disable automatic switching from UDP to TCP transports if outgoing request is too large. See RFC 3261 section 18.1.1. Disabling this option has been known to cause interoperability issues, so disable at your own risk. (default: «yes»)
  • type= ; Must be of type system (default: «»)

Секция Global

Global settings.

Global settings.

  • max_forwards=70 ; Value used in Max Forwards header for SIP requests (default: «70»)
  • type= ; Must be of type global (default: «»)
  • user_agent=Asterisk PBX SVN-branch-12-r404375 ; Value used in User Agent header for SIP requests and Server header for SIP responses (default: «»)
  • default_outbound_endpoint=default_outbound_endpoint ; Endpoint to use when sending an outbound request to a URI without a specified endpoint (default: «d efault_outbound_endpo int»)
  • debug=no ; Enable/Disable SIP debug logging. Valid options include yes|no

; or a host address (default: «no»)

  • keep_alive_interval=20 ; The interval (in seconds) at which to send keepalive messages on all active connection-oriented transports (default: «0»)
  • contact_expiration_check_interval=30 ;The interval (in seconds) to check for expired contacts.
  • disable_multi_domain=no ; Disable Multi Domain support. If disabled it can improve realtime performace by reducing number of database requsts (default: «no»)
  • endpoint_identifier_order=ip,username,anonymous The order by which endpoint identifiers are given priority. Currently, «ip», «username», «auth_username» and «anonymous» are valid identifiers as registered by the res_pjsip_endpoint_identifier_* modules. Some modules like res_pjsip_endpoint_identifier_user register more than one identifier. Use the CLI command «pjsip show identifiers» to see the identifiers currently available. (default: ip,username,anonymous)
  • max_initial_qualify_time=4 ; The maximum amount of time (in seconds) from startup that qualifies should be attempted on all contacts. If greater than the qualify_frequency for an aor, qualify_frequency will be used instead.
  • regcontext=sipregistrations ; If regcontext is specified, Asterisk will dynamically create and destroy a NoOp priority 1 extension for a given endpoint who registers or unregisters with us. The extension added is the name of the endpoint.
  • default_voicemail_extension=asterisk ;The voicemail extension to send in the NOTIFY Message-Account header if not set on endpoint or aor. (default: «»)

The following unidentified_request options are only used when «auth_username» matching is enabled in «endpoint_identifier_order».

  • unidentified_request_count=5 ; The number of unidentified requests that can be received from a single IP address in unidentified_request_period seconds before a security event is generated. (default: 5)
  • unidentified_request_period=5 ; See above. (default: 5 seconds)
  • unidentified_request_prune_interval=30 ; The interval at which unidentified requests are check to see if they can be pruned. If they're older than twice the unidentified_request_period, they're pruned.
  • default_from_user=asterisk ; When Asterisk generates an outgoing SIP request, the From header username will be set to this value if there is no better option (such as CallerID or endpoint/from_user) to be used
  • default_realm=asterisk ; When Asterisk generates a challenge, the realm will be set to this value if there is no better option (such as auth/realm) to be used

Asterisk Task Processor Queue Size
On heavy loaded system with DB storage you may need to increasetaskprocessor queue. If the taskprocessor queue size reached high water level, the alert is triggered. If the alert is set the pjsip distibutor stops processing incoming requests until the alert is cleared. The alert is cleared when taskprocessor queue size drops to the low water clear level. The next options set taskprocessor queue levels for MWI.

  • mwi_tps_queue_high=500 ; Taskprocessor high water alert trigger level.
  • mwi_tps_queue_low=450 ; Taskprocessor low water clear alert level.

; The default is -1 for 90% of high water level.

                  ; Unsolicited MWI
                  ; If there are endpoints configured with unsolicited MWI
                  ; then res_pjsip_mwi module tries to send MWI to all endpoints on startup.
 * **mwi_disable_initial_unsolicited**=no ; Disable sending unsolicited mwi to all endpoints on startup.  If disabled then unsolicited mwi will start processing on the endpoint's next contact update.
  • ignore_uri_user_options=no ; Enable/Disable ignoring SIP URI user field options. If you have this option enabled and there are semicolons in the user field of a SIP URI then the field is truncated at the first semicolon. This effectively makes the semicolon a non-usable character for PJSIP endpoint names, extensions, and AORs. This can be useful for improving compatability with an ITSP that likes to use user options for whatever reason.
                    ; Example:
                    ; URI: "sip:1235557890;phone-context=national@x.x.x.x;user=phone"
                    ; The user field is "1235557890;phone-context=national"
                    ; Which becomes this: "1235557890"

Note: The caller-id and redirecting number strings obtained from incoming SIP URI user fields are always truncated at the first semicolon.

*CLI> pjsip show settings

Global Settings:

 ParameterName                     : ParameterValue
 =============================================================
 contact_expiration_check_interval : 30
 debug                             : no
 default_from_user                 : asterisk
 default_outbound_endpoint         : default_outbound_endpoint
 default_voicemail_extension       :
 endpoint_identifier_order         : ip,username,anonymous
 keep_alive_interval               : 0
 max_forwards                      : 70
 max_initial_qualify_time          : 0
 regcontext                        :
 user_agent                        : FPBX-12.0.76.4(13.9.0)

System Settings:

 ParameterName             : ParameterValue
 ==========================================
 compact_headers           : false
 disable_tcp_switch        : true
 threadpool_auto_increment : 5
 threadpool_idle_timeout   : 60
 threadpool_initial_size   : 0
 threadpool_max_size       : 50
 timer_b                   : 32000
 timer_t1                  : 500

ENDPOINT

Модуль ENDPOINT определяет многочисленные параметры SIP, а также связь с другими модулями - AUTH, AOR и TRANSPORT.
Секция ENDPOINT должна быть обязательно связана с одной или несколькими секциями AOR.
По сути дела, ENDPOINT является основным профилем SIP телефона или SIP транка в res_pjsip, аналогично пиру в sip.conf.
Только если там определялись почти все параметры, то здесь часть ключевых свойств вынесены в специальные секции (модули), которые и будут рассмотрены ниже.

ENPOINT все параметры

ENPOINT все параметры

  • 100rel=yes - разрешить поддержку RFC3262 ACK (по умолчанию «yes»)
  • aggregate_mwi=yes ; (default: «yes»)
  • allow= - используемые кодеки (по умолчанию: «»)
  • aors= - AoR используемая ENDPOINT (по умолчанию: «»)
  • auth= - Объект аутентификации соотнесенный с endpoint (по умолчанию: «»)
  • callerid= - CallerID используемый endpoint (default: «»)
  • callerid_privacy=allowed_not_screened - Уровень приватности (по умолчанию: «allowed_not_screened»)
  • callerid_tag= - Внутренняя метка (Internal id_tag) для endpoint (по умолчанию: «»)
  • context=default - Контекст диалплана для данной endpoint.
  • direct_media_glare_mitigation=none ; Mitigation of direct media re INVITE glare (default: «none»)
  • direct_media_method=invite ; Direct Media method type (default: «invite»)
  • connected_line_method=invite ; Connected line method type (default: «invite»)
  • direct_media=yes ; Determines whether media may flow directly between endpoints (default: «yes»)
  • disable_direct_media_on_nat=no ; Disable direct media session refreshes when NAT obstructs the media session (default: «no»)
  • disallow= ; Media Codec s to disallow (default: «»)
  • dtmf_mode=rfc4733 ; DTMF mode (default: «rfc4733»)
  • media_address= ; IP address used in SDP for media handling (default: «»)
  • bind_rtp_to_media_address= ; Bind the RTP session to the media_address. This causes all RTP packets to be sent from the specified address. (default: «no»)
  • force_rport=yes ; Force use of return port (default: «yes»)
  • ice_support=no ; Enable the ICE mechanism to help traverse NAT (default: «no»)
  • identify_by=username ; A comma-separated list of ways the Endpoint or AoR can be identified.
    • «username»: Identify by the From or To username and domain
    • «auth_username»: Identify by the Authorization username and real. In all cases, if an exact match on username and domain/realm fails, the match will be retried with just the username (default: «username»)
  • redirect_method=user ; How redirects received from an endpoint are handled (default: «user»)
  • mailboxes= ; NOTIFY the endpoint when state changes for any of the specified mailboxes. Asterisk will send unsolicited MWI NOTIFY messages to the endpoint when state changes happen for any of the specified mailboxes. (default: «»)
  • voicemail_extension= ; The voicemail extension to send in the NOTIFY Message-Account header (default: global/default_voicemail_extension)
  • mwi_subscribe_replaces_unsolicited=no ;An MWI subscribe will replace unsoliticed NOTIFYs (default: «no»)
  • moh_suggest=default ; Default Music On Hold class (default: «default»)
  • moh_passthrough=yes ; Pass Music On Hold through using SIP re-invites with sendonly when placing on hold and sendrecv when taking off hold
  • outbound_auth= ; Authentication object used for outbound requests (default: «»)
  • outbound_proxy= ; Proxy through which to send requests a full SIP URI must be provided (default: «»)
  • rewrite_contact=no ; Allow Contact header to be rewritten with the source IP address port (default: «no»)
  • rtp_ipv6=no ; Allow use of IPv6 for RTP traffic (default: «no»)
  • rtp_symmetric=no ; Enforce that RTP must be symmetric (default: «no»)
  • send_diversion=yes ; Send the Diversion header conveying the diversion information to the called user agent (default: «yes»)
  • send_pai=no ; Send the P Asserted Identity header (default: «no»)
  • send_rpid=no ; Send the Remote Party ID header (default: «no»)
  • rpid_immediate=no ; Send connected line updates on unanswered incoming calls immediately. (default: «no»)
  • timers_min_se=90 ; Minimum session timers expiration period (default: «90»)
  • timers=yes ; Session timers for SIP packets (default: «yes»)
  • timers_sess_expires=1800 ; Maximum session timer expiration period (default: «1800»)
  • transport= ; Desired transport configuration (default: «»)
  • trust_id_inbound=no ; Accept identification information received from this endpoint (default: «no»)
  • trust_id_outbound=no ; Send private identification details to the endpoint (default: «no»)
  • type= ; Must be of type endpoint (default: «»)
  • use_ptime=no ; Use Endpoint s requested packetisation interval (default: «no»)
  • use_avpf=no ; Determines whether res_pjsip will use and enforce usage of AVPF for this endpoint (default: «no»)
  • media_encryption=no ; Determines whether res_pjsip will use and enforce usage of media encryption for this endpoint (default: «no»)
  • media_encryption_optimistic=no ; Use encryption if possible but don't fail the call if not possible.
  • g726_non_standard=no ; When set to «yes» and an endpoint negotiates g.726 audio then g.726 for AAL2 packing order is used contrary to what is recommended in RFC3551. Note, 'g726aal2' also needs to be specified in the codec allow list (default: «no»)
  • inband_progress=no ; Determines whether chan_pjsip will indicate ringing using inband progress (default: «no»)
  • call_group= ; The numeric pickup groups for a channel (default: «»)
  • pickup_group= ; The numeric pickup groups that a channel can pickup (default: «»)
  • named_call_group= ; The named pickup groups for a channel (default: «»)
  • named_pickup_group= ; The named pickup groups that a channel can pickup (default: «»)
  • device_state_busy_at=0 ; The number of in use channels which will cause busy to be returned as device state (default: «0»)
  • t38_udptl=no ; Whether T 38 UDPTL support is enabled or not (default: «no»)
  • t38_udptl_ec=none ; T 38 UDPTL error correction method (default: «none»)
  • t38_udptl_maxdatagram=0 ; T 38 UDPTL maximum datagram size (default: «0»)
  • fax_detect=no ; Whether CNG tone detection is enabled (default: «no»)
  • fax_detect_timeout=30 ; How many seconds into a call before fax_detect is disabled for the call.Zero disables the timeout.(default: «0»)
  • t38_udptl_nat=no ; Whether NAT support is enabled on UDPTL sessions(default: «no»)
  • t38_udptl_ipv6=no ; Whether IPv6 is used for UDPTL Sessions (default:«no») for this endpoint (default: «»)
  • language= ; Set the default language to use for channels created for this endpoint (default: «»)
  • one_touch_recording=no ; Determines whether one touch recording is allowed for this endpoint (default: «no»)
  • record_on_feature=automixmon ; The feature to enact when one touch recording is turned on (default: «automixmon»)
  • record_off_feature=automixmon ; The feature to enact when one touch recording is turned off (default: «automixmon»)
  • rtp_engine=asterisk ; Name of the RTP engine to use for channels created for this endpoint (default: «asterisk»)
  • allow_transfer=yes ; Determines whether SIP REFER transfers are allowed for this endpoint (default: «yes»)
  • sdp_owner=- ; String placed as the username portion of an SDP origin o line(default: «-»)
  • sdp_session=Asterisk ; String used for the SDP session s line (default: «Asterisk»)
  • tos_audio=0 ; DSCP TOS bits for audio streams (default: «0»)
  • tos_video=0 ; DSCP TOS bits for video streams (default: «0»)
  • cos_audio=0 ; Priority for audio streams (default: «0»)
  • cos_video=0 ; Priority for video streams (default: «0»)
  • allow_subscribe=yes ; Determines if endpoint is allowed to initiate subscriptions with Asterisk (default: «yes»)
  • sub_min_expiry=0 ; The minimum allowed expiry time for subscriptions initiated by the endpoint (default: «0»)
  • from_user= ; Username to use in From header for requests to this endpoint (default: «»)
  • mwi_from_user= ; Username to use in From header for unsolicited MWI NOTIFYs to this endpoint (default: «»)
  • from_domain= ; Domain to user in From header for requests to this endpoint (default: «»)
  • dtls_verify=no ; Verify that the provided peer certificate is valid (default: «no»)
  • dtls_rekey=0 ; Interval at which to renegotiate the TLS session and rekey the SRTP session (default: «0»)
  • dtls_cert_file= ; Path to certificate file to present to peer (default:«»)
  • dtls_private_key= ; Path to private key for certificate file (default: «»)
  • dtls_cipher= ; Cipher to use for DTLS negotiation (default: «»)
  • dtls_ca_file= ; Path to certificate authority certificate (default: «»)
  • dtls_ca_path= ; Path to a directory containing certificate authority certificates (default: «»)
  • dtls_setup= ; Whether we are willing to accept connections connect to the other party or both (default: «»)
  • dtls_fingerprint= ; Hash to use for the fingerprint placed into SDP (default: «SHA-256»)
  • srtp_tag_32=no ; Determines whether 32 byte tags should be used instead of 80 byte tags (default: «no»)
  • set_var= ; Variable set on a channel involving the endpoint. For multiple channel variables specify multiple 'set_var'(s)
  • rtp_keepalive= ; Interval, in seconds, between comfort noise RTP packets if RTP is not flowing. This setting is useful for ensuring that holes in NATs and firewalls are kept open throughout a call.
  • rtp_timeout= ; Hang up channel if RTP is not received for the specified number of seconds when the channel is off hold (default: «0» or not enabled)
  • rtp_timeout_hold= ; Hang up channel if RTP is not received for the specified number of seconds when the channel «0» or not enabled)
  • contact_user= ; On outgoing requests, force the user portion of the Contact header to this value (default: «»)
Простой пример конфигурации секции ENDPOINT
[777]
type=endpoint
context=from-internal
disallow=all
allow=alaw
transport=udp-transport
auth=auth777
aors=777

В данном примере мы видим тип секции: type=endpoint
контекст, разрешенные кодеки и также ассоциацию с другими секциями
transport=udp-transport, auth=auth777 и aors=777.
Насколько я понимаю, опции type и aors являются обязательными для работоспособности точки.
Для назначения Caller ID этому пиру(ENDPOINT), потребуется задать следующие параметры:

trust_id_outbound=yes
callerid=V Pupkin <777>

TRANSPORT

Настройка транспортного уровня res_pjsip. Используются протоколы UDP, TCP, WebSockets и методы шифрования TLS/SSL. Можно настроить одну транспортную секцию для использования множеством точек (ENDPOINT), или создать уникальный транспортный уровень для конкретной точки. Условно, можно сравнить TRANSPORT, с секцией [general] sip.conf.

TRANSPORT все параметры

TRANSPORT все параметры

  • async_operations=1 ; Number of simultaneous Asynchronous Operations (default: «1»)
  • bind= ; IP Address and optional port to bind to for this transport (default: «»)
  • ca_list_file= ; File containing a list of certificates to read TLS ONLY (default: «»)
  • ca_list_path= ; Path to directory containing certificates to read TLS ONLY. PJProject version 2.4 or higher is required for this option to be used. (default: «»)
  • cert_file= ; Certificate file for endpoint TLS ONLY. Will read .crt or .pem file but only uses cert, a .key file must be specified via priv_key_file. Since PJProject version 2.5: If the file name ends in _rsa, for example «asterisk_rsa.pem», the files «asterisk_dsa.pem» and/or «asterisk_ecc.pem» are loaded (certificate, inter- mediates, private key), to support multiple algorithms for server authentication (RSA, DSA, ECDSA). If the chains are different, at least OpenSSL 1.0.2 is required. (default: «»)
  • cipher= ; Preferred cryptography cipher names TLS ONLY (default: «»)
  • domain= ; Domain the transport comes from (default: «»)
  • external_media_address= ; External IP address to use in RTP handling (default: «»)
  • external_signaling_address= ; External address for SIP signalling (default: «»)
  • external_signaling_port=0 ; External port for SIP signalling (default: «0»)
  • method= ; Method of SSL transport TLS ONLY (default: «»)
  • local_net= ; Network to consider local used for NAT purposes (default: «»)
  • password= ; Password required for transport (default: «»)
  • priv_key_file= ; Private key file TLS ONLY (default: «»)
  • protocol=udp ; Protocol to use for SIP traffic (default: «udp»)
  • require_client_cert= ; Require client certificate TLS ONLY (default: «»)
  • type= ; Must be of type transport (default: «»)
  • verify_client= ; Require verification of client certificate TLS ONLY (default:«»)
  • verify_server= ; Require verification of server certificate TLS ONLY (default: «»)
  • tos=0 ; Enable TOS for the signalling sent over this transport (default: «0»)
  • cos=0 ; Enable COS for the signalling sent over this transport (default: «0»)
  • websocket_write_timeout=100 ; Default write timeout to set on websocket transports. This value may need to be adjusted for connections where Asterisk must write a substantial amount of data and the receiving clients are slow to process the received information. Value is in milliseconds; default is 100 ms.
  • allow_reload=no ; Although transports can now be reloaded, that may not be desirable because of the slight possibility of dropped calls. To make sure there are no unintentional drops, if this option is set to 'no' (the default) changes to the particular transport will be ignored. If set to 'yes', changes (if any) will be applied.

По умолчанию, для применения настроек транспортного уровня недостаточно перечитать конфиги. Потребуется рестартовать Asterisk, если не задано allow_reload=true (по умолчанию - false)
простой пример конфигурации секции TRANSPORT
[udp-transport]
type=transport
protocol=udp
bind=0.0.0.0

или TLS транспорт c ключами:

[transport-tls]
type=transport
protocol=tls
bind=0.0.0.0:5066
cert_file=/etc/asterisk/keys/asterisk.crt
priv_key_file=/etc/asterisk/keys/asterisk.key
external_media_address=123.123.123.1
external_signaling_address=123.123.123.1
local_net=10.10.0.0/16
method=tlsv1
Каждый транспорт в системе должен иметь уникальный порт.
localhost*CLI> pjsip show transports
 
Transport:  <TransportId........>  <Type>  <cos>  <tos>  <BindAddress....................>
 =========================================================================================
 
Transport:  udp-transport             udp      0      0  0.0.0.0:5080
Transport:  udp-transport-infra       udp      0      0  192.168.1.110:5081
Transport:  udp-transport-megafon     udp      0      0  0.0.0.0:5060

AUTH

Секция аутентификации содержит опции и полномочия для входящих и исходящих регистраций. С этой секцией ассоциируются такие секции как ENDPOINT и REGISTRATIONS.
Разные ENDPOINT и REGISTRATIONS могут использовать одну и ту же секцию аутентификации, если требуется.

config show help res_pjsip auth

config show help res_pjsip auth

localhost*CLI> config show help res_pjsip auth
auth: [category !~ /.?/]
 
Authentication type
 
 Authentication objects hold the authentication information for use by other
objects such as 'endpoints' or 'registrations'. This also allows for multiple
objects to use a single auth object. See the 'auth_type' config option for
password style choices.
 
auth_type                 -- Authentication type
nonce_lifetime            -- Lifetime of a nonce associated with this authentication config.
md5_cred                  -- MD5 Hash used for authentication.
password                  -- PlainText password used for authentication.
realm                     -- SIP realm for endpoint
type                      -- Must be 'auth'
username                  -- Username to use for account
Простой пример секции AUTH
[auth777]
type=auth
auth_type=userpass
password=password
username=777

с использованием MD5

[auth6001]
type=auth
auth_type=md5
md5_cred=5f4dcc3b5aa765d61d8327deb882cf99
username=777

AOR

Главная функция AoR (Address of Record) указать Asterisk, как связаться с ENDPOINT. Без соответствующей AOR секции, точка ENDPOINT будет недоступна для вызова. Здесь также задаются соответствия голосовой почте, MWI, продолжительность действия регистрации -expiration и настройки qualify (периодической отправки SIP сообщений OPTONS для мониторинга состояния устройств)

Когда Asterisk получает запрос на регистрацию от устройства, он в первую очередь ищет соответствующую SIP заголовку To: «777»<sip:777@192.168.1.21;transport=UDP> запись в именах секций AOR – в нашем прмере [777]

config show help res_pjsip aor

config show help res_pjsip aor

localhost*CLI> config show help res_pjsip aor
aor: [category !~ /.?/]
 
The configuration for a location of an endpoint
 
 An AoR is what allows Asterisk to contact an endpoint via res_pjsip. If no
AoRs are specified, an endpoint will not be reachable by Asterisk. Beyond
that, an AoR has other uses within Asterisk, such as inbound registration.
 
 An 'AoR' is a way to allow dialing a group of 'Contacts' that all use the
 same 'endpoint' for calls.
 This can be used as another way of grouping a list of contacts to dial
 rather than specifing them each directly when dialing via the dialplan. This
 must be used in conjuction with the 'PJSIP_DIAL_CONTACTS'.
 Registrations: For Asterisk to match an inbound registration to an endpoint,
 the AoR object name must match the user portion of the SIP URI in the "To:"
 header of the inbound SIP registration. That will usually be equivalent to
 the "user name" set in your hard or soft phones configuration.
 
contact                   -- Permanent contacts assigned to AoR
default_expiration        -- Default expiration time in seconds for contacts that are dynamica
mailboxes                 -- Allow subscriptions for the specified mailbox(es)
maximum_expiration        -- Maximum time to keep an AoR
max_contacts              -- Maximum number of contacts that can bind to an AoR
minimum_expiration        -- Minimum keep alive time for an AoR
remove_existing           -- Determines whether new contacts replace existing ones.
type                      -- Must be of type 'aor'.
qualify_frequency         -- Interval at which to qualify an AoR
authenticate_qualify      -- Authenticates a qualify request if needed
outbound_proxy            -- Outbound proxy used when sending OPTIONS request
support_path              -- Enables Path support for REGISTER requests and Route support for
Простейший пример секции AOR
[777]
type=aor
max_contacts=1

Опция max_contact=1 значит, что только один SIP User Agent может быть одновременно зарегистрирован через эту запись AOR. Можно указать и 10, если потребуется.

[777]
type=aor
contact=sip:777@192.168.1.21:5060

Во втором примере мы не ожидаем запроса на регистрацию от SIP UA,
а указываем вручную постоянный контакт для этой записи.
Можно не беспокоится о кол-ве подключений, адрес все равно один.

[siptrunk]
type=aor
contact=sip:123.123.1.1:5060

В последнем примере пропущен username, что позволяет использовать данную запись для исходящей связи,
определяя вызываемый номер при помощи диалплана «Dial(PJSIP/${EXTEN}@siptrunk)».

REGISTRATION

Секция регистраций отвечает за исходящие регистрации. Используется для регистрации в удаленных системах, будь то другой Asterisk или транк от провайдера.

config show help res_pjsip_outbound_registration registration

config show help res_pjsip_outbound_registration registration

localhost*CLI> config show help res_pjsip_outbound_registration  registration
registration: [category !~ /.?/]
 
The configuration for outbound registration
 
 Registration is *COMPLETELY* separate from the rest of 'pjsip.conf'. A minimal
configuration consists of setting a 'server_uri'        and a 'client_uri'.
 
auth_rejection_permanent  -- Determines whether failed authentication challenges are treated a
client_uri                -- Client SIP URI used when attempting outbound registration
contact_user              -- Contact User to use in request                                                                                                             
expiration                -- Expiration time for registrations in seconds                                                                                               
max_retries               -- Maximum number of registration attempts.                                                                                                   
outbound_auth             -- Authentication object to be used for outbound registrations.
outbound_proxy            -- Outbound Proxy used to send registrations                                                                                                  
retry_interval            -- Interval in seconds between retries if outbound registration is u
forbidden_retry_interval  -- Interval used when receiving a 403 Forbidden response.
server_uri                -- SIP URI of the server to register against                                                                                                  
transport                 -- Transport used for outbound authentication                                                                                                 
type                      -- Must be of type 'registration'.                                                                                                            
support_path              -- Enables Path support for outbound REGISTER requests  
Пример секции REGISTRATION
[siptrunk]
type=registration
transport=udp-transport
outbound_auth=siptrunk
server_uri=sip:123.123.1.1:5060
client_uri=sip:username@192.168.1.1:5060
retry_interval=60

Для регистрации понадобится определить используемый транспорт и секцию аутентификации.
Помимо этого, наверняка, потребуется указать контакт для входящих вызовов.

[providertrunk]
type=registration
transport=udp-transport
outbound_auth=providertrunk
server_uri=sip:sip.example.com
client_uri=sip:1234567890@sip.example.com
retry_interval=60

Пример регистрации транка провайдера.

DOMAIN_ALIAS

Псевдоним домена. [Имя] данной секции является псевдонимом, а конфигурационная опция domain=, доменным именем, которому сопоставлен псевдоним.

config show help res_pjsip domain_alias

config show help res_pjsip domain_alias

localhost*CLI> config show help res_pjsip domain_alias
domain_alias: [category !~ /.?/]
 
Domain Alias
 
 Signifies that a domain is an alias. If the domain on a session is not found
to match an AoR then this object is used to see if we have an alias for the
AoR to which the endpoint is binding. This objects name as defined in
configuration should be the domain alias and a config option is provided to
specify the domain to be aliased.
 
type                      -- Must be of type 'domain_alias'.
domain                    -- Domain to be aliased
Пример секции DOMAIN_ALIAS
[example2.com]
type=domain_alias
domain=example.com

ACL

Модуль не привязан к какой-либо точке ENDPOINTs и управляет всеми входящими SIP коммуникациями с использованием res_pjsip. Установки ACl (Access Control Lis) могут быть назначены в самой секции, или в файле acl.conf на который будет ссылаться секция.

config show help res_pjsip_acl acl

config show help res_pjsip_acl acl

localhost*CLI> config show help res_pjsip_acl  acl
acl: [category !~ /.?/]
 
Access Control List
 
acl                       -- List of IP ACL section names in acl.conf
contact_acl               -- List of Contact ACL section names in acl.conf
contact_deny              -- List of Contact header addresses to deny
contact_permit            -- List of Contact header addresses to permit
deny                      -- List of IP addresses to deny access from
permit                    -- List of IP addresses to permit access from
type                      -- Must be of type 'acl'.
Простые примеры ACL

Asterisk res_pjsip_acl

Настройки берутся из файла acl.conf:

[acl]
type=acl
acl=example_named_acl1

Настройки непосредственно в секции:

[acl]
type=acl
deny=0.0.0.0/0.0.0.0
permit=123.12.123.0
permit=123.12.123.1

Конфиг разрешающий регистрацию на основе SIP заголовка, а не IP адреса.

[acl]
type=acl
contactdeny=0.0.0.0/0.0.0.0
contactpermit=123.12.123.0
contactpermit=123.12.123.1

IDENTIFY

Определяет конечные точки с помощью IP-адреса источника.

config show help res_pjsip_endpoint_identifier_ip identify

config show help res_pjsip_endpoint_identifier_ip identify

localhost*CLI> config show help res_pjsip_endpoint_identifier_ip identify
identify: [category !~ /.?/]

Identifies endpoints via source IP address

endpoint                  -- Name of Endpoint
match                     -- IP addresses or networks to match against
type                      -- Must be of type 'identify'.
Пример identity
[777]
type=identify
endpoint=777
match=123.0.112.1

CONTACT

Контакты являются одним из способов не указывать явно SIP URI в плане набора (диалплане).

config show help res_pjsip contact

config show help res_pjsip contact

localhost*CLI> config show help res_pjsip contact
contact: [category !~ /.?/]
 
A way of creating an aliased name to a SIP URI
 
 Contacts are a way to hide SIP URIs from the dialplan directly. They are
also used to make a group of contactable parties when in use with 'AoR' lists.
 
 
type                      -- Must be of type 'contact'.
uri                       -- SIP URI to contact peer
expiration_time           -- Time to keep alive a contact
qualify_frequency         -- Interval at which to qualify a contact
outbound_proxy            -- Outbound proxy used when sending OPTIONS request
path                      -- Stored Path vector for use in Route headers on outgoing requests.

Отношения объектов конфигурации pjsip.conf

ENDPOINT

  • Множество ENDPOINTs связываются с множеством AORs
  • Ноль или больше ENDPOINTs связаны с ноль или одной AUTHs
  • Ноль или больше ENDPOINTs связаны с как минимум одним TRANSPORT
  • Ноль или одна ENDPOINTs связана с определенной IDENTIFY

REGISTRATION

  • Ноль или больше REGISTRATIONs связаны с ноль или одной AUTHs
  • Ноль или больше REGISTRATIONs связаны с как минимум одним TRANSPORT

AOR

  • Множество ENDPOINTs связываются с множеством AORs
  • Множество AORs связаны с множеством CONTACTs

CONTACT

  • Множество CONTACTs связываются с множеством AORs

IDENTIFY

  • Ноль или больше ENDPOINTs связаны с определенным IDENTIFY объектом.

ACL, DOMAIN_ALIAS

  • Эти объекты не имеют направленных связей с другими объектами.

Примеры диалплана для вызова PJSIP пиров и екстеншенов.

   exten => _6XXX,1,Dial(PJSIP/${EXTEN})
 
   exten => _9NXXNXXXXXX,1,Dial(PJSIP/mytrunk/sip:${EXTEN:1}@203.0.113.1:5060)
 
   exten => _9NXXNXXXXXX,1,Dial(PJSIP/${EXTEN:1}@mytrunk)

Примеры

Пример ENDPOINT для одного SIP телефона с регистрацией на Asterisk.
;===============TRANSPORT
 
[udp-transport]
type=transport
protocol=udp
bind=0.0.0.0
 
;===============EXTENSION 777
 
[777]
type=endpoint
context=from-internal
disallow=all
allow=alaw
transport=udp-transport
auth=auth777
aors=777
 
[auth777]
type=auth
auth_type=userpass
password=777
username=777
 
[777]
type=aor
max_contacts=1
  • auth= используется для входящей аутентификации
  • max_contacts= установите кол-во регистраций, одну или более, разрешенных для этой учетной записи.
Пример SIP транка с исходящей регистрацией
;==============TRANSPORTS
 
[udp-transport]
type=transport
protocol=udp
bind=0.0.0.0
 
;===============TRUNK
 
[siptrunk]
type=registration
transport=udp-transport
outbound_auth=siptrunk
server_uri=sip:sip.example.com
client_uri=sip:1234567890@sip.example.com
retry_interval=60
 
[siptrunk]
type=auth
auth_type=userpass
password=1234567890
username=1234567890
 
[siptrunk]
type=aor
contact=sip:123.0.112.1:5060
 
[siptrunk]
type=endpoint
transport=udp-transport
context=from-trunk
disallow=all
allow=alaw,ulaw
outbound_auth=siptrunk
aors=siptrunk
 
[siptrunk]
type=identify
endpoint=siptrunk
match=123.0.112.1
Пример регистрации множественных ENDPOINTs с использованием шаблонов
;===============TRANSPORT
 
[udp-transport]
type=transport
protocol=udp
bind=0.0.0.0
 
;===============ENDPOINT TEMPLATES
 
[endpoint-basic](!)
type=endpoint
transport=udp-transport
context=from-internal
disallow=all
allow=alaw
 
[auth-userpass](!)
type=auth
auth_type=userpass
 
[aor-single-reg](!)
type=aor
max_contacts=1
 
;===============EXTENSION 777
 
[777](endpoint-basic)
auth=auth777
aors=777
 
[auth777](auth-userpass)
password=777
username=777
 
[777](aor-single-reg)
 
;===============EXTENSION 778
 
[778](endpoint-basic)
auth=auth778
aors=778
 
[auth778](auth-userpass)
password=778
username=778
 
[778](aor-single-reg)
 
;===============EXTENSION 779
 
[779](endpoint-basic)
auth=auth779
aors=779
 
[auth779](auth-userpass)
password=779
username=779
 
[779](aor-single-reg) 

От старого к новому - sip.conf к pjsip.conf сравнение примеров.

Сравнение конфигурации ENDPOINT

  • Два SIP телефона должны звонить и принимать вызовы через Asterisk.
  • В обоих случаях для аутентификации используются username и password.
  • 777 регистрируется с динамического IP, 778 со статического IP адреса.

1

sip.confpjsip.conf
[general]
udpbindaddr=0.0.0.0
 
[777]
type=friend
host=dynamic
disallow=all
allow=alaw
context=from-internal
secret=1234
 
[778]
type=friend
host=192.168.1.2
disallow=all
allow=alaw
context=from-internal
secret=1234
[udp-transport]
type=transport
protocol=udp
bind=0.0.0.0
 
[777]
type = endpoint
transport = udp-transport
context = from-internal
disallow = all
allow = alaw
aors = 777
auth = auth777
 
[777]
type = aor
max_contacts = 1
 
[auth777]
type=auth
auth_type=userpass
password=1234
username=777
 
[778]
type = endpoint
transport = udp-transport
context = from-internal
disallow = all
allow = alaw
aors = 778
auth = auth778
 
[778]
type = aor
contact = sip:778@192.168.1.2:5060
 
[auth778]
type=auth
auth_type=userpass
password=1234
username=778

Сравнение конфигурации trunk

sip.confpjsip.conf
[general]
udpbindaddr=0.0.0.0
 
register => myname:1234@203.0.113.1:5060
 
[mytrunk]
type=friend
secret=1234
username=myname
host=123.0.112.1
disallow=all
allow=alaw
context=from-trunk
[simpletrans]
type=transport
protocol=udp
bind=0.0.0.0 
[mytrunk]
type=registration
transport=simpletrans
outbound_auth=mytrunk
server_uri=sip:@123.0.112.1:5060
client_uri=sip:myname@123.0.112.1:5060
 
[mytrunk]
type=auth
auth_type=userpass
password=1234
username=myname
 
[mytrunk]
type=aor
contact=sip:123.0.112.1:5060
 
[mytrunk]
type=endpoint
transport=simpletrans
context=from-trunk
disallow=all
allow=alaw
outbound_auth=mytrunk
aors=mytrunk
 
[mytrunk]
type=identify
endpoint=mytrunk
match=123.0.112.1

PJSIP CLI

Connected to Asterisk 13.9.1 currently running on aster2 (pid = 17401)
asterisk*CLI> core show help pjsip
pjsip dump endpt               -- Dump the res_pjsip endpt internals
pjsip export config_wizard primitives [to] -- Export config wizard primitives
pjsip list aors                -- List PJSIP Aors
pjsip list auths               -- List PJSIP Auths
pjsip list channels            -- List PJSIP Channels
pjsip list ciphers             -- List available OpenSSL cipher names
pjsip list contacts            -- List PJSIP Contacts
pjsip list endpoints           -- List PJSIP Endpoints
pjsip list identifies          -- List PJSIP Identifies
pjsip list registrations       -- List PJSIP Registrations
pjsip list transports          -- List PJSIP Transports
pjsip qualify                  -- Send an OPTIONS request to a PJSIP endpoint
pjsip send register            -- Registers an outbound registration target
pjsip send unregister          -- Unregisters outbound registration target
pjsip set history {on|off|clear} -- Enable/Disable PJSIP History
pjsip set logger {on|off|host} -- Enable/Disable PJSIP Logger Output
pjsip show aors                -- Show PJSIP Aors
pjsip show aor                 -- Show PJSIP Aor
pjsip show auths               -- Show PJSIP Auths
pjsip show auth                -- Show PJSIP Auth
pjsip show channels            -- Show PJSIP Channels
pjsip show channel             -- Show PJSIP Channel
pjsip show channelstats        -- Show PJSIP Channel Stats
pjsip show contacts            -- Show PJSIP Contacts
pjsip show contact             -- Show PJSIP Contact
pjsip show endpoints           -- Show PJSIP Endpoints
pjsip show endpoint            -- Show PJSIP Endpoint
pjsip show history             -- Display PJSIP History
pjsip show identifiers         -- List registered endpoint identifiers
pjsip show identifies          -- Show PJSIP Identifies
pjsip show identify            -- Show PJSIP Identify
pjsip show registrations       -- Show PJSIP Registrations
pjsip show registration        -- Show PJSIP Registration
pjsip show settings            -- Show global and system configuration options
pjsip show transports          -- Show PJSIP Transports
pjsip show transport           -- Show PJSIP Transport
pjsip show version             -- Show the version of pjproject in use

Настройка Asterisk

  • asterisk/pjsip.txt
  • Последние изменения: 2019/09/25