Editing XEP-0065: SOCKS5 Bytestreams

From JaWiki (Jabber/XMPP wiki)
Jump to: navigation, search

Warning: The database has been locked for maintenance, so you will not be able to save your edits right now. You may wish to copy and paste your text into a text file and save it for later.

The administrator who locked it offered this explanation: MediaWiki upgrading

The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then save the changes below to finish undoing the edit.
Latest revision Your text
Line 1: Line 1:
[[Category:XEP]]
+
This document defines an XMPP protocol extension for establishing an out-of-band bytestream between any two Jabber entities.
[[Category:Translation]]
+
[[Category:XEP translation]]
+
  
{{warning|Этот текст не является официальным переводом документа [http://www.xmpp.org/extensions/xep-0065.html XEP-0065: SOCKS5 Bytestreams] и может не соответствовать оригиналу. Для разработки программ используйте официальный текст.}}
+
: '''NOTICE:''' The protocol defined herein is a Draft Standard of the XMPP Standards Foundation. Implementations are encouraged and the protocol is appropriate for deployment in production systems, but some changes to the protocol are possible before it becomes a Final Standard.
 +
Document Information
  
Этот документ определяет [[XEP|расширение протокола XMPP]] для установление [[out-of-band|внеканального]] байтового потока между двумя произвольными [[entity|сущностями]] Jabber.
+
Series: XEP
 +
Number: 0065
 +
Publisher: XMPP Standards Foundation
 +
Status: Draft
 +
Type: Standards Track
 +
Version: 1.7
 +
Last Updated: 2007-05-21
 +
Approving Body: XMPP Council
 +
Dependencies: XMPP Core, RFC 1928, RFC 3174, XEP-0030
 +
Supersedes: None
 +
Superseded By: None
 +
Short Name: bytestreams
 +
Schema: <http://www.xmpp.org/schemas/bytestreams.xsd>
 +
Wiki Page: <http://wiki.jabber.org/index.php/SOCKS5 Bytestreams (XEP-0065)>
 +
Author Information
 +
Dave Smith
  
: '''ПРИМЕЧАНИЕ:''' Настоящий протокол имеет статус "Черновик". Его реализации поощряются, и протокол подходит для развёртывания в производственных системах<!-- Implementations are encouraged and the protocol is appropriate for deployment in production systems -->, но прежде, чем он станет Окончательным Стандартом, в протоколе могут произойти некоторые изменения.
+
Email: dizzyd@jabber.org
 +
JabberID: dizzyd@jabber.org
 +
Matthew Miller
  
= Входные данные =
+
Email: linuxwolf@outer-planes.net
 +
JabberID: linuxwolf@outer-planes.net
 +
Peter Saint-Andre
  
== Информация о документе ==
+
Email: stpeter@jabber.org
 +
JabberID: stpeter@jabber.org
 +
Legal Notice
  
* Категория: [[XEP]]
+
This XMPP Extension Protocol is copyright 1999 - 2007 by the XMPP Standards Foundation (XSF) and is in full conformance with the XSF's Intellectual Property Rights Policy <http://www.xmpp.org/extensions/ipr-policy.shtml>. This material may be distributed only subject to the terms and conditions set forth in the Creative Commons Attribution License (<http://creativecommons.org/licenses/by/2.5/>).
* Номер: 0065
+
Discussion Venue
* Издатель: [[XMPP Standards Foundation|Организации Стандартизации XMPP]]
+
* Статус: Черновик
+
* Тип: {{fixme|Standards Track}}
+
* Версия: 1.7
+
* Последнее обновление: 2007-05-21
+
* Утвердивший орган: [[XMPP Council|Совет XMPP]]
+
* Опирается на:
+
** [[XMPP Core|Основы XMPP]],
+
** RFC 1928: SOCKS Protocol Version 5,
+
** RFC 3174: US Secure Hash Algorithm 1 (SHA1),
+
** {{xep|0030|Service Discovery}}
+
* Заменяет: нет
+
* Заменяется: нет
+
* Короткое название: bytestreams (потоки байтов)
+
* Схема: http://www.xmpp.org/schemas/bytestreams.xsd
+
* Страница Вики: http://wiki.jabber.org/index.php/SOCKS5_Bytestreams_(XEP-0065)
+
  
== Информация об авторах ==
+
The preferred venue for discussion of this document is the Standards discussion list: <http://mail.jabber.org/mailman/listinfo/standards>.
  
* [[Dave Smith|Дэйв Смит (Dave Smith)]]
+
Given that this XMPP Extension Protocol normatively references IETF technologies, discussion on the XSF-IETF list may also be appropriate (see <http://mail.jabber.org/mailman/listinfo/jsf-ietf> for details).
*: Электропочта: dizzyd@jabber.org
+
Relation to XMPP
*: JabberID: dizzyd@jabber.org
+
* [[Matthew Miller|Мэтью Миллер (Matthew Miller)]]
+
*: Электропочта: linuxwolf@outer-planes.net
+
*: JabberID: linuxwolf@outer-planes.net
+
* [[Peter Saint-Andre|Питер Сен-Андре (Peter Saint-Andre)]]
+
*: Электропочта: stpeter@jabber.org
+
*: JabberID: stpeter@jabber.org
+
  
== Надлежащее уведомление ==
+
The Extensible Messaging and Presence Protocol (XMPP) is defined in the XMPP Core (RFC 3920) and XMPP IM (RFC 3921) specifications contributed by the XMPP Standards Foundation to the Internet Standards Process, which is managed by the Internet Engineering Task Force in accordance with RFC 2026. Any protocol defined in this document has been developed outside the Internet Standards Process and is to be understood as an extension to XMPP rather than as an evolution, development, or modification of XMPP itself.
 +
Conformance Terms
  
На это [[XEP|расширение протокола XMPP]] распространяется авторское право 1999–2007 [[XMPP Standards Foundation|Организации Стандартизации XMPP]]. Документ полностью соответствует Стратегии XSF в Области Интеллектуальной Собственности (XSF's Intellectual Property Rights Policy, http://www.xmpp.org/extensions/ipr-policy.shtml). Этот материал может распространься только в соответствии с установленной далее Лицензией Творческих Общин «Указание Авторства» (Creative Commons Attribution License, http://creativecommons.org/licenses/by/2.5/)
+
The following keywords as used in this document are to be interpreted as described in RFC 2119: "MUST", "SHALL", "REQUIRED"; "MUST NOT", "SHALL NOT"; "SHOULD", "RECOMMENDED"; "SHOULD NOT", "NOT RECOMMENDED"; "MAY", "OPTIONAL".
 +
Table of Contents
  
{{todo|Почитать все эти документы и восстановить справедливость}}
 
  
== Место обсуждения ==
+
1. Introduction
 +
2. Terminology
 +
3. Narrative
 +
    3.1. Direct Connection
 +
    3.2. Mediated Connection
 +
4. Protocol
 +
    4.1. Initiator Queries Target Regarding Bytestreams Support
 +
    4.2. Initiator Queries Server For Proxies
 +
    4.3. Initiator Queries Proxy to Find Out if it is a Proxy
 +
    4.4. Initiator Discovers Network Address of StreamHost
 +
    4.5. Initiator Informs Target of StreamHosts
 +
    4.6. Target Establishes SOCKS5 Connection with StreamHost
 +
    4.7. Target Acknowledges SOCKS5 Connection
 +
    4.8. Initiator Establishes SOCKS5 Connection with StreamHost
 +
    4.9. Activation of Bytestream
 +
5. Formal Use Case
 +
    5.1. Primary Flow
 +
    5.2. Alternate Flows
 +
6. Formal Description
 +
    6.1. <query/> Element
 +
    6.2. <streamhost/> Element
 +
    6.3. <streamhost-used/> Element
 +
    6.4. <activate/> Element
 +
7. Optional UDP Support
 +
    7.1. Discovering UDP Support
 +
    7.2. Requesting UDP Mode
 +
    7.3. UDP Process
 +
      7.3.1. Establishing the UDP Association
 +
      7.3.2. Initializing the UDP Channel
 +
    7.4. Exchanging UDP Packets
 +
8. Implementation Notes
 +
    8.1. StreamHost Requirements
 +
    8.2. SOCKS5 Parameter Mapping
 +
9. Security Considerations
 +
10. IANA Considerations
 +
11. XMPP Registrar Considerations
 +
    11.1. Protocol Namespaces
 +
    11.2. Service Discovery Features
 +
    11.3. Service Discovery Category/Type
 +
12. Schema
 +
Notes
 +
Revision History
 +
1. Introduction
  
Рекомендуется вести обсуждение данного документа в почтовом списке обсуждения Стандартов (http://mail.jabber.org/mailman/listinfo/standards)
+
XMPP is designed for sending relatively small fragments of XML between network entities (see XMPP Core [1]) and is not designed for sending binary data. However, sometimes it is desirable to send binary data to another entity that one has discovered on the XMPP network (e.g., to send a file). Therefore it is widely recognized within the Jabber community that it would be valuable to have a generic protocol for streaming binary data between any two entities on the network. The main application for such a bytestreaming technology would be file transfer, for which there are currently a number of incompatible protocols (resulting in a lack of interoperability). However, other applications are possible, which is why it is important to develop a generic protocol rather than one that is specialized for a particular application such as file transfer. This document defines a protocol that meets the following conditions:
 +
Bytestreams are established over standard TCP connections (RFC 793 [2]) or UDP associations (RFC 768 [3]), where TCP support is REQUIRED and UDP support is OPTIONAL
 +
Sockets may be direct (peer-to-peer) or mediated (established through a bytestreaming service)
 +
Where possible, standard wire protocols are used
  
Поскольку [[XEP|расширение протокола XMPP]] нормативно ссылается на технологии [[IETF]], обсуждение в почтовом списке XSF-IETF также может затрагивать данный документ (см. http://mail.jabber.org/mailman/listinfo/jsf-ietf).
+
Specifically, this document proposes that the Jabber community make use of the SOCKS 5 protocol, which is an IETF-approved, IPv6-ready technology for bytestreams. (Note: Because this proposal uses a subset of the SOCKS5 protocol that is specially adapted for Jabber bytestreams, existing SOCKS5 proxies cannot be used to implement this proposal without modifications.)
 +
2. Terminology
  
== Отношение к XMPP ==
+
The following terms are used throughout this document.
  
[[XMPP|Расширяемый протокол передачи сообщений и информации о присутствии (XMPP)]] определён в документах [[XMPP Core|«Основы XMPP»]] (RFC 3920) и [[XMPP IM|«Обмен сообщениями в XMPP»]] (RFC 3921), внесённых [[XMPP Standards Foundation|Организацией Стандартизации XMPP]] в Процесс Стандартизации Интернета (Internet Standards Process), который управляется [[w:IETF|IETF]] в соответствии с RFC 2026. Каждый протокол, определённый в этом документе, разработан вне Процесса Стандартизации Интернета и должен рассматриваться как дополнение к XMPP, а не как развитие, продолжение самого XMPP.
+
Table 1: Glossary of EntitiesTerm Description
 +
Initiator A Jabber Entity that wishes to establish a bytestream with another Entity
 +
Target The Entity with which the Initiator is attempting to establish a bytestream
 +
Proxy A Jabber entity which is not NAT/Firewalled and is willing to be a middleman for the bytestream between the Initiator and the Target
 +
StreamHost The system that the Target connects to and that is "hosting" the bytestream -- may be either the Initiator or a Proxy
 +
StreamID A relatively unique Stream ID for this connection; this is generated by the Initiator for tracking purposes and MUST be less than 128 characters in length
  
== Слова соответствия ==
+
3. Narrative
  
Следующие ключевые слова, используемые в настоящем документе, долны интерпретироваться в соответствии с RFC 2119:
+
There are two scenarios addressed by this protocol:
: «ДОЛЖЕН»/«ДОЛЖНА»/«ДОЛЖНО»/«ДОЛЖНЫ», «ОБЯЗАТЕЛЕН»/«ОБЯЗАТЕЛЬНА»/«ОБЯЗАТЕЛЬНО»/«ОБЯЗАТЕЛЬНЫ»<!-- , "SHALL" -->;
+
direct connection (i.e., the StreamHost is the Initiator)
: «НЕ ДОЛЖЕН»/«НЕ ДОЛЖНА»/«НЕ ДОЛЖНО»/«НЕ ДОЛЖНЫ»<!-- , "SHALL NOT" -->;
+
mediated connection (i.e., the StreamHost is a Proxy)
: «СЛЕДУЕТ», «РЕКОМЕНДУЕТСЯ»;
+
: «СЛЕДУЕТ НЕ», «РЕКОМЕНДУЕТСЯ НЕ»;
+
: «МОЖЕТ»/«МОГУТ», «НЕОБЯЗАТЕЛЬНЫЙ»/«НЕОБЯЗАТЕЛЬНАЯ»/«НЕОБЯЗАТЕЛЬНОЕ»/«НЕОБЯЗАТЕЛЬНЫЕ».
+
  
= Описание протокола =
+
The "happy paths" for these scenarios are described separately below for ease of understanding. A full description of these scenarios is captured in the Formal Use Case. This narrative describes TCP connections only; UDP associations are described in the Optional UDP Support section of this document.
 +
3.1 Direct Connection
  
== Введение ==
+
Direct connection is the simpler case. In this situation, the StreamHost is the Initiator (StreamHost/Initiator), which means that the Initiator knows the network address of the StreamHost and knows when to activate the bytestream. The process for establishing bytestreams in this case is as follows:
  
[[XMPP]] разработан для пересылки сравнительно малых кусков [[XML]] между [[entity|сетевыми сущностями]] (см. «[[XMPP Core|Основы XMPP]]») и не предназначен для пересылки двоичных данных. Тем не менее, иногда требуется передать двоичные данные другой сущности, найденной в сети XMPP (например, передать файл). Поэтому в сообществе Jabber многие признают, что было бы полезно иметь общий протокол для пересылки двоичных данных между двумя произвольными сущностями в сети. Основным приложением такой технологии передачи была бы [[file transfer|передача файлов]], для которой в настоящее время есть несколько несовместимых протоколов (что выливается в отсутствие совместимости). Тем не менее, возможны и другие приложения, из-за которых важно разработать общий протокол, а не ограниченный частным применением, таким, передача файлов. Этот документ определяет протокол, удовлетворяющий следующим условиям:
+
Initiator sends IQ-set to Target specifying the full JID and network address of StreamHost/Initiator as well as the StreamID (SID) of the proposed bytestream.
* Байтовые потоки устанавливаются поверх стандартных соединений [[w:TCP|TCP]] (RFC 793) или [[w:UDP|UDP]] (RFC 768), причём поддержка TCP ОБЯЗАТЕЛЬНА, а поддержка UDP НЕОБЯЗАТЕЛЬНА.
+
* [[w:Сокет|Сокеты]] могут быть прямыми (peer-to-peer) или опосредованными (устанавливаемыми через передающий сервис).
+
* Где возможно, используются стандартные протоколы передачи.
+
  
Конкретно, данный документ предполагает, что сообщество Jabber пользуется протоколом [[w:en:SOCKS|SOCKS 5]] — технологией передачи данных, принятой [[w:IETF|IETF]] и совместимой с [[w:IPv6|IPv6]]. (Примечание: Предлагаемая технология использует подмножество протокола SOCKS 5, специально адаптированное для передачи данных в Jabber, поэтому существующие SOCKS 5 [[w:Прокси-сервер|прокси-серверы]] не могут использоваться для её реализации без соответствующей доработки.)
+
Target opens a TCP socket to the specified network address.
  
== Терминология ==
+
Target requests connection via SOCKS5, with the DST.ADDR and DST.PORT parameters set to the values defined below.
  
В документе используются следующие термины.
+
StreamHost/Initiator sends acknowledgement of successful connection to Target via SOCKS5.
  
<div id="table_1">[[#table_1|Таблица 1: Словарь Сущностей]]</div>
+
Target sends IQ-result to Initiator, preserving the 'id' of the initial IQ-set.
  
{| class="standard"
+
StreamHost/Initiator activates the bytestream.
! Термин !! Описание
+
|-
+
| Инициатор || [[Entity|Сущность]] Jabber, которая желает установить сеанс передачи данных с другой Сущностью.
+
|-
+
| Цель || Сущность, с которой Инициатор пытается установить сеанс передачи.
+
|-
+
| Посредник || Сущность Jabber, не находящаяся за [[w:NAT|NAT-маршрутизатором]] или [[w:Межсетевой экран|межсетевым экраном]] и желающая выступать промежуточным звеном при передаче файлов между Инициатором и Целью.
+
|-
+
| ВедущийУзел || Система, к которой подключается Цель и которая управляет передачей. ВедущимУзлом может быть либо Инициатор, либо Посредник.
+
|-
+
| ИдПередачи || Относительно уникальный идентификатор передачи для этого соединения. Он генерируется Инициатором и используется для контроля передачи. Его длина ДОЛЖНА быть меньше 128 символов.
+
|}
+
  
== Narrative ==
+
Initiator and Target may begin using the bytestream.
{{todo|Как перевести название?}}
+
3.2 Mediated Connection
  
Возможны два сценария, для которых предназначен этот протокол:
+
Mediated connection is slightly more complicated. In this situation, the StreamHost is not the Initiator but a Proxy, which means that the Initiator must discover the network address of the StreamHost before sending the initial IQ-set, must negotiate a connection with the StreamHost in the same way that the Target does, and must request that the StreamHost activate the bytestream before it can be used. The process for establishing bytestreams in this case is as follows:
# прямое соединение (т.е. ВедущийУзел — Инициатор);
+
# опосредованное соединение (т.е. ВедущийУзел — Посредник).
+
  
Нормальный ход этих сценариев описан ниже для простоты понимания. Полное описание этих сценариев зафиксировано в разделе {{fixme|[[#Formal Use Case|Formal Use Case]]}}. Здесь описывается только TCP-соединение, UDP-связь описывается в разделе {{fixme|[[#Optional UDP Support|Optional UDP Support]]}} настоящего документа.
+
Optionally, Initiator discovers the network address of StreamHost in-band.
  
=== Прямое соединение ===
+
Initiator sends IQ-set to Target specifying the full JID and network address of StreamHost as well as the StreamID (SID) of the proposed bytestream.
  
Простейший случай — это прямое соединение. В этой ситуации ВедущимУзлом выступает Инициатор (ВедущийУзел/Инициатор). Это означает, что Инициатор знает сетевой адрес ВедущегоУзла и способ активации передачи. Процесс установки соединения и передачи в этом случае следующий:
+
Target opens a TCP socket to the selected StreamHost.
  
# Инициатор посылает Цели [[iq|IQ-запрос (set)]], указывая [[JID|полный JID]] ВедущегоУзла/Инициатора, а также ИдПередачи предлагаемого канала передачи.
+
Target establishes connection via SOCKS5, with the DST.ADDR and DST.PORT parameters set to the values defined below.
# Цель открывает TCP-соединение по указанному сетевому адресу.
+
# Цель запрашивает соединение через SOCKS5 со значениями адреса приёмника (DST.ADDR) и порта приёмника (DST.PORT), указанными ниже.
+
# ВедущийУзел/Инициатор посылает подтверждение успешного соединения с Целью по SOCKS5.
+
# Цель отправляет [[iq|IQ-ответ (result)]] Инициатору, используя в нём идентификатор начальной IQ-последовательности.
+
# ВедущийУзел/Инициатор активирует передачу.
+
# Инициатор и Цель могут начать пересылку данных.
+
  
=== Опосредованное соединение ===
+
StreamHost sends acknowledgement of successful connection to Target via SOCKS5.
  
Опосредованное соединение немного сложнее. В этом случае ВедущимУзлом является не Инициатор, а Посредник; это означает, что Инициатор должен узнать сетевой адрес ВедущегоУзла перед посылкой начального [[iq|запроса IQ-set]], должен согласовать соединение с ВедущимУзлом таким же образом, как и Цель, и должен запросить, чтобы ВедущийУзел активировал канал передачи прежде, чем он может быть использован. Процесс установки каналов передачи таков:
+
Target sends IQ-result to Initiator, preserving the 'id' of the initial IQ-set.
  
# (Необязательный пункт) Инициатор узнаёт сетевой адрес ВедущегоУзла [[in-band|внутри канала XMPP]].
+
Initiator opens a TCP socket at the StreamHost.
# Инициатор посылает Цели запрос IQ-set с указанием [[JID|полного JID]] и сетевого адреса ВедущегоУзла, а также <span id="SID_definition">ИдПередачи (StreamID, SID)</span> предлагаемого канала передачи.
+
# Цель открывает соединение [[w:TCP|TCP]] с выбранным ВедущимУзлом.
+
# Цель устанавливает соединение по SOCKS5 со значениями адреса приёмника (DST.ADDR) и порта приёмника (DST.PORT), определёнными ниже.
+
# ВедущийУзел посылает подтверждение успешного соединения с Целью по SOCKS5.
+
# Цель посылает Инициатору [[iq|результат IQ-result]], используя идентификатор (параметр 'id') исходного запроса IQ-set.
+
# Инициатор открывает соединение TCP с ВедущимУзлом.
+
# Инициатор устанавливает соединение по SOCKS5 со значениями адреса приёмника (DST.ADDR) и порта приёмника (DST.PORT), определёнными ниже.
+
# ВедущийУзел посылает подтверждение успешного соединения с Инициатором по SOCKS5.
+
# Инициатор посылает IQ-set ВедущемуУзлу с запросом активации ВедущимуУзлом канала передачи, связанного с ИдПередачи.
+
# ВедущийУзел активирует канал передачи. (Данные теперь перенаправляются посредником [прокси] из одного соединения SOCKS5 в другое.)
+
# ВедущийУзел посылает результат IQ-result Инициатору, подтверждающий, что канал передачи активирован (или сообщающий об ошибке).
+
# Инициатор и Цель могут начинать использовать канал передачи.
+
  
== Протокол ==
+
Initiator establishes connection via SOCKS5, with the DST.ADDR and DST.PORT parameters set to the values defined below.
  
=== Инициатор запрашивает Цель о поддержке передачи данных ===
+
StreamHost sends acknowledgement of successful connection to Initiator via SOCKS5.
  
Перед попыткой создания канала передачи данных Инициатор может захотеть знать, поддерживает ли Цель протокол передачи. Он может сделать это, используя [[Service Discovery|обнаружение сервисов]] следующим образом:
+
Initiator sends IQ-set to StreamHost requesting that StreamHost activate the bytestream associated with the StreamID.
  
<b id="Example_1">Пример 1. Инициатор посылает Цели запрос обнаружения сервисов.</b>
+
StreamHost activates the bytestream. (Data is now relayed between the two SOCKS5 connections by the proxy.)
<iq    type='get'
+
        from='initiator@host1/foo'
+
        to='target@host2/bar'
+
        id='hello'>
+
    <query xmlns='http''':'''//jabber.org/protocol/disco#info'/>
+
</iq>
+
  
Если Цель поддерживает передачу данных, она ДОЛЖНА указать это в ответе на запрос обнаружения сервисов.
+
StreamHost sends IQ-result to Initiator acknowledging that the bytestream has been activated (or specifying an error).
  
<b id="Example_2">Пример 2. Цель отвечает за запрос обнаружения сервисов.</b>
+
Initiator and Target may begin using the bytestream.
<iq    type='result'
+
4. Protocol
        from='target@host2/bar'
+
4.1 Initiator Queries Target Regarding Bytestreams Support
        to='initiator@host1/foo'
+
        id='hello'>
+
    <query xmlns='http''':'''//jabber.org/protocol/disco#info'>
+
        <identity
+
                category='proxy'
+
                type='bytestreams'
+
                name='SOCKS5 Bytestreams Service'/>
+
        ...
+
        <feature var='http''':'''//jabber.org/protocol/bytestreams'/>
+
        ...
+
    </query>
+
</iq>
+
  
=== Инициатор запрашивает Посредников у сервера ===
+
Before attempting to initiate a bytestream, the Initiator may want to know if the Target supports the bytestream protocol. It may do so using Service Discovery [4] as follows:
  
Перед попыткой создания канала передачи данных Инициатору надо найти посредника (прокси). Он может сделать это, используя [[Service Discovery|обнаружение сервисов]] следующим образом:
+
Example 1. Initiator Sends Service Discovery Request to Target
 +
<iq type='get'
 +
    from='initiator@host1/foo'
 +
    to='target@host2/bar'
 +
    id='hello'>
 +
  <query xmlns='http://jabber.org/protocol/disco#info'/>
 +
</iq>
 +
   
  
<b id="Example_3">Пример 3. Инициатор посылает серверу запрос [[Service Discovery|обнаружения сервисов (Service Discovery).]]</b>
+
If the Target supports bytestreams, it MUST answer to that effect in the service discovery result.
<iq    type='get'
+
        from='initiator@host1/foo'
+
        to='host1'
+
        id='server_items'>
+
    <query xmlns='http''':'''//jabber.org/protocol/disco#items'/>
+
</iq>
+
  
Сервер вернёт все известные [[JID|JIDы]] в своём списке сервисов.
+
Example 2. Target Replies to Service Discovery Request
 +
<iq type='result'
 +
    from='target@host2/bar'
 +
    to='initiator@host1/foo'
 +
    id='hello'>
 +
  <query xmlns='http://jabber.org/protocol/disco#info'>
 +
    <identity
 +
        category='proxy'
 +
        type='bytestreams'
 +
        name='SOCKS5 Bytestreams Service'/>
 +
    ...
 +
    <feature var='http://jabber.org/protocol/bytestreams'/>
 +
    ...
 +
  </query>
 +
</iq>
 +
   
 +
4.2 Initiator Queries Server For Proxies
  
<b id="Example_4">Пример 4. Сервер отвечает на запрос обнаружения сервисов.</b>
+
Before attempting to initiate a bytestream, the Initiator needs to find a proxy. It may do so using Service Discovery as follows:
<iq    type='result'
+
        from='host1'
+
        to='initiator@host1/foo'
+
        id='server_items'>
+
    <query xmlns='http''':'''//jabber.org/protocol/disco#items'>
+
        ...
+
        <item jid='proxy.host3' name='Bytestreams Proxy'/>
+
        ...
+
    </query>
+
</iq>
+
  
=== Инициатор спрашивает посредника, является ли он посредником ===
+
Example 3. Initiator Sends Service Discovery Request to Server
 +
<iq type='get'
 +
    from='initiator@host1/foo'
 +
    to='host1'
 +
    id='server_items'>
 +
  <query xmlns='http://jabber.org/protocol/disco#items'/>
 +
</iq>
 +
   
  
Инициатор должен спросить у каждой сущности в списке, является ли она посредником для передачи данных. Он может сделать это, используя [[Service Discovery|обнаружение сервисов (Service Discovery)]] следующим образом:
+
The server will return all of the known JIDs in its disco list.
  
<b id="Example_5">Пример 5. Инициатор посылает посреднику запрос обнаружения сервисов.</b>
+
Example 4. Server Replies to Service Discovery Request
<iq     type='get'  
+
<iq type='result'  
        from='initiator@host1/foo'
+
    from='host1'  
        to='proxy.host3'  
+
    to='initiator@host1/foo'  
        id='proxy_info'>
+
    id='server_items'>
    <query xmlns='http''':'''//jabber.org/protocol/disco#info'/>
+
  <query xmlns='http://jabber.org/protocol/disco#items'>
</iq>
+
    ...
 +
    <item jid='proxy.host3' name='Bytestreams Proxy'/>
 +
    ...
 +
  </query>
 +
</iq>
 +
   
 +
4.3 Initiator Queries Proxy to Find Out if it is a Proxy
  
Посредник вернёт сведения о себе. Инициатору СЛЕДУЕТ исследовать каждый элемент &lt;identity/&gt; и посмотреть, содержится ли в этих сведениях &lt;identity/&gt; категории "proxy" (свойство 'category') и типа "bytestreams" (свойство 'type').
+
For each item in the disco#items result, the Initiator must query to determine if it is a bytestreams proxy. It may do so using Service Discovery as follows:
  
<b id="Example_6">Пример 6. Сервер отвечает на запрос обнаружения сервисов.</b>
+
Example 5. Initiator Sends Service Discovery Request to Proxy
<iq     type='result'  
+
<iq type='get'  
        from='proxy.host3'
+
    from='initiator@host1/foo'
        to='initiator@host1/foo'  
+
    to='proxy.host3'
        id='proxy_info'>
+
    id='proxy_info'>
    <query xmlns='http''':'''//jabber.org/protocol/disco#info'>
+
  <query xmlns='http://jabber.org/protocol/disco#info'/>
        ...
+
</iq>
        <identity
+
   
                category='proxy'
+
                type='bytestreams'
+
                name='SOCKS5 Bytestreams Service'/>
+
        ...
+
        <feature var='http''':'''//jabber.org/protocol/bytestreams'/>
+
        ...
+
    </query>
+
</iq>
+
  
=== Инициатор узнаёт сетевой адрес ВедущегоУзла ===
+
The proxy will return its information. The Initiator SHOULD inspect each identity to see if it contains an identity of category "proxy" and type "bytestreams".
  
Если ВедущимУзлом выступает Посредник, Инициатор сначала должен запросить полный сетевой адрес, используемый для передачи данных (очевидно, этого не требуется в случае, сли ВедущимУзлом является Инициатор). Это делается посылкой посреднику запроса [[iq|IQ-get]] в пространстве имён bytestreams как в следующем примере:
+
Example 6. Server Replies to Service Discovery Request
 +
<iq type='result'
 +
    from='proxy.host3'
 +
    to='initiator@host1/foo'
 +
    id='proxy_info'>
 +
  <query xmlns='http://jabber.org/protocol/disco#info'>
 +
    ...
 +
    <identity category='proxy'
 +
              type='bytestreams'
 +
              name='SOCKS5 Bytestreams Service'/>
 +
    ...
 +
    <feature var='http://jabber.org/protocol/bytestreams'/>
 +
    ...
 +
  </query>
 +
</iq>
 +
   
 +
4.4 Initiator Discovers Network Address of StreamHost
  
<b id="Example_7">Пример 7. Инициатор запрашивает у Посредника сетевой адрес.</b>
+
If the StreamHost is a Proxy, the Initiator must first request the full network address used for bytestreaming (obviously this is not required if the StreamHost is the Initiator). This is done by sending an IQ-get to the proxy in the bytestreams namespace, as follows:
<iq    type='get'
+
        from='initiator@host1/foo'
+
        to='proxy.host3'
+
        id='discover'>
+
    <query xmlns='http''':'''//jabber.org/protocol/bytestreams'/>
+
</iq>
+
  
Элемент <streamhost/>, указывающий сетевой адрес, ДОЛЖЕН иметь следующие атрибуты:
+
Example 7. Initiator Requests Network Address from Proxy
* '''jid''' = [[JID]] ВедущегоУзла для соединения через [[Jabber]]
+
<iq type='get'
Дополнительно, элемент <streamhost/> ДОЛЖЕН включать:
+
    from='initiator@host1/foo'  
 +
    to='proxy.host3'  
 +
    id='discover'>
 +
  <query xmlns='http://jabber.org/protocol/bytestreams'/>
 +
</iq>
 +
   
  
ЛИБО
+
The <streamhost/> element specifying a network address MUST possess the following attributes:
* '''host''' = [[w:en:Hostname|сетевое имя]] или [[w:IP-адрес|IP-адрес]] ВедущегоУзла для SOCKS5-соединения через TCP
+
jid = the JID of the StreamHost for communications over Jabber
* '''port''' = порт, связанный с сетевым именем или IP-адресом, для SOCKS5-соединения через TCP
+
ЛИБО
+
* '''zeroconf''' = идентификатор [[w:Zeroconf|zeroconf]], к которому может подключиться сущность, для которой идентификатору службы и названию протокола СЛЕДУЕТ быть <tt>"_jabber.bytestreams"</tt>.
+
  
<b id="Example_8">Пример 8. Посредник сообщает Инициатору сетевой адрес.</b>
+
In addition, the <streamhost/> element MUST include:
<iq    type='result'
+
        from='proxy.host3'
+
        to='initiator@host1/foo'
+
        id='discover'>
+
    <query xmlns='http''':'''//jabber.org/protocol/bytestreams'>
+
        <streamhost
+
                jid='proxy.host3'
+
                host='24.24.24.1'
+
                zeroconf='_jabber.bytestreams'/>
+
    </query>
+
</iq>
+
  
Если у Инициатора нет права инициировать передачу данных на Посреднике по любой причине (например, реализация посредника может позволять администраторам запрещать JIDам или доменам использование Посредника), Посредник ДОЛЖЕН вернуть ошибку <tt><forbidden/></tt> («запрещено») Инициатору (за информацией о синтаксисе ошибок обращайтесь к {{xep|0086|Error Condition Mappings}}):
+
EITHER
 +
host = the hostname or IP address of the StreamHost for SOCKS5 communications over TCP
 +
port = a port associated with the hostname or IP address for SOCKS5 communications over TCP
  
<b id="Example_9">Пример 9. Посредник возвращает Иициатору ошибку.</b>
+
OR
<iq    type='error'
+
zeroconf = a zeroconf [5] identifier to which an entity may connect, for which the service identifier and protocol name SHOULD be "_jabber.bytestreams".
        from='initiator@host1/foo'
+
        to='proxy.host3'
+
        id='discover'>
+
    <query xmlns='http''':'''//jabber.org/protocol/bytestreams'/>
+
        <error code='403' type='auth'>
+
        <forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
+
    </error>
+
</iq>
+
  
Если Посредник не может выступать в качестве ВедущегоУзла, ему СЛЕДУЕТ вернуть Инициатору ошибку <tt><not-allowed/></tt> («не разрешено»):
+
Example 8. Proxy Informs Initiator of Network Address
 +
<iq type='result'
 +
    from='proxy.host3'
 +
    to='initiator@host1/foo'
 +
    id='discover'>
 +
  <query xmlns='http://jabber.org/protocol/bytestreams'>
 +
    <streamhost
 +
        jid='proxy.host3'
 +
        host='24.24.24.1'
 +
        zeroconf='_jabber.bytestreams'/>
 +
  </query>
 +
</iq>
 +
   
  
<b id="Example_10">Пример 10. Посредник возвращает Инициатору ошибку.</b>
+
If the Initiator does not have permissions to initiate bytestreams on the Proxy for whatever reason (e.g., a proxy implementation may enable administrators to ban JIDs or domains from using the Proxy), the Proxy MUST return a <forbidden/> error to the Initiator (for information about error syntax, refer to Error Condition Mappings [6]):
<iq    type='error'
+
        from='initiator@host1/foo'
+
        to='proxy.host3'
+
        id='discover'>
+
    <query xmlns='http''':'''//jabber.org/protocol/bytestreams'/>
+
        <error code='405' type='cancel'>
+
        <not-allowed xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
+
    </error>
+
</iq>
+
  
=== Инициатор сообщает Цели о ВедущихУзлах ===
+
Example 9. Proxy Returns Error to Initiator
 +
<iq type='error'
 +
    from='initiator@host1/foo'
 +
    to='proxy.host3'
 +
    id='discover'>
 +
  <query xmlns='http://jabber.org/protocol/bytestreams'/>
 +
  <error code='403' type='auth'>
 +
    <forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
 +
  </error>
 +
</iq>
 +
   
  
Чтобы организовать передачу данных между Инициатором и Целью, Инициатор должен предоставить Цели сведения о сетевом адресе ВедущегоУзла (или узлов). Это совершается [[in-band|внутри канала]] с помощью одного набора [[iq|IQ-set]], который должен содержать следующие сведения:
+
If the Proxy is unable to act as a StreamHost, the Proxy SHOULD return a <not-allowed/> error to the Initiator:
  
* Сетевой адрес по меньшей мере одного ВедущегоУзла, к которому может попытаться подключиться Цель.
+
Example 10. Proxy Returns Error to Initiator
* ИдПередачи для этого соединения.
+
<iq type='error'
* Использующийся режим (mode), обычно "tcp", но при определённых условиях может быть "udp" (см. {{fixme|[[#Optional UDP Support]]}}).
+
    from='initiator@host1/foo'
 +
    to='proxy.host3'
 +
    id='discover'>
 +
  <query xmlns='http://jabber.org/protocol/bytestreams'/>
 +
  <error code='405' type='cancel'>
 +
    <not-allowed xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
 +
  </error>
 +
</iq>
 +
   
 +
4.5 Initiator Informs Target of StreamHosts
  
Формат протокола показан ниже.
+
In order to establish a bytestream between the Initiator and the Target, the Initiator must provide network address information for the StreamHost(s) to the Target. This happens in-band via a single IQ-set, which must contain the following information:
 +
The network address of at least one StreamHost to which the Target may attempt to connect
 +
The Stream ID for this connection
 +
The "mode" to use, normally "tcp" but optionally "udp" (see the Optional UDP Support section of this document)
  
<b id="Example_11">Пример 11. Начало взаимодействия.</b>
+
The protocol format is shown below.
<iq    type='set'
+
        from='initiator@host1/foo'
+
        to='target@host2/bar'
+
        id='initiate'>
+
    <query  xmlns='http''':'''//jabber.org/protocol/bytestreams'
+
            sid='mySID'
+
            mode='tcp'>
+
        <streamhost
+
                jid='initiator@host1/foo'
+
                host='192.168.4.1'
+
                port='5086'/>
+
        <streamhost
+
                jid='proxy.host3'
+
                host='24.24.24.1'
+
                zeroconf='_jabber.bytestreams'/>
+
    </query>
+
</iq>
+
  
Если Цель не желает принимать передачу, она ДОЛЖНА вернуть Инициатору ошибку <not-acceptable/> («не принято»).
+
Example 11. Initiation of Interaction
 +
<iq type='set'
 +
    from='initiator@host1/foo'
 +
    to='target@host2/bar'
 +
    id='initiate'>
 +
  <query xmlns='http://jabber.org/protocol/bytestreams'
 +
        sid='mySID'
 +
mode='tcp'>
 +
    <streamhost
 +
        jid='initiator@host1/foo'
 +
        host='192.168.4.1'
 +
        port='5086'/>
 +
    <streamhost
 +
        jid='proxy.host3'
 +
        host='24.24.24.1'
 +
        zeroconf='_jabber.bytestreams'/>
 +
  </query>
 +
</iq>
 +
   
  
<b id="Example_12">Пример 12. Цель отклоняет передачу.</b>
+
If the Target is unwilling to accept the bytestream, it MUST return a <not-acceptable/> error to the Initiator.
<iq    type='error'
+
        from='target@host2/bar'
+
        to='initiator@host1/foo'
+
        id='initiate'>
+
    <error code='406' type='auth'>
+
        <not-acceptable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
+
    </error>
+
</iq>
+
  
=== Цель устанавливает соединение SOCKS5 с ВедущимУзлом ===
+
Example 12. Target Refuses Bytestream
 +
<iq type='error'
 +
    from='target@host2/bar'
 +
    to='initiator@host1/foo'
 +
    id='initiate'>
 +
  <error code='406' type='auth'>
 +
    <not-acceptable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
 +
  </error>
 +
</iq>
 +
   
 +
4.6 Target Establishes SOCKS5 Connection with StreamHost
  
Если Цель согласна принять поток данных, она ДОЛЖНА попытаться открыть стандартный сокет TCP на сетевом интерфейсе ВедущегоУзла, соединённого с Инициатором. Если Инициатором было предложено несколько ВедущихУзлов, Цели СЛЕДУЕТ попытаться соединиться с ними в том порядке, в котором они указаны.
+
If the Target is willing to accept the bytestream, it MUST attempt to open a standard TCP socket on the network address of the StreamHost communicated by the Initiator. If the Initiator provides more than one StreamHost, the Target SHOULD try to connect to them in the order they occur.
  
Если Цель пытается, но не может соединиться ни с каким из ВедущихУзлов и не желает пытаться установить соединение со своей стороны {{todo|сомневаюсь в правильности перевода: it does not wish to attempt a connection from its side}}, она ДОЛЖНА вернуть Инициатору ошибку <tt>&lt;item-not-found/&gt;</tt> («элемент не найдён»).
+
If the Target tries but is unable to connect to any of the StreamHosts and it does not wish to attempt a connection from its side, it MUST return a <item-not-found/> error to the Initiator.
  
<b id="Example_13">Пример 13. Цель не может соединиться ни с каким из ВедущихУзлов и желает завершить транзакцию.</b>
+
Example 13. Target Is Unable to Connect to Any StreamHost and Wishes to End Transaction
<iq     type='error'  
+
<iq type='error'  
        from='target@host2/bar'  
+
    from='target@host2/bar'  
        to='initiator@host1/foo'  
+
    to='initiator@host1/foo'  
        id='initiate'>
+
    id='initiate'>
    <error code='404' type='cancel'>
+
  <error code='404' type='cancel'>
        <item-not-found xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
+
    <item-not-found xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
    </error>
+
  </error>
</iq>
+
</iq>
 +
   
  
Если Цель может открыть сокет TCP на ВедущемУзле, она ДОЛЖНА использовать протокол SOCKS5, описанный в RFC 1982 для установления соединения с ВедущимУзлом. В соответствии с RFC по SOCKS5, у Цели МОЖЕТ быть затребован пароль для доступа к прокси-серверу. Тем не менее, всё, что касается аутентификации, находится за пределами этого документа.
+
If the Target is able to open a TCP socket on a StreamHost, it MUST utilize the SOCKS5 protocol specified in RFC 1928 [7] to establish the connection with the StreamHost. In accordance with the SOCKS5 RFC, the Target MAY have to authenticate in order to use the proxy. However, any authentication required is beyond the scope of this document.
  
Когда Цель будет успешно аутентифицирована на Посреднике (даже анонимно), ей СЛЕДУЕТ послать запрос CONNECT соответствующему узлу, чтобы продолжить процесс установления соединения. При этом применяются следующие правила:
+
Once the Target has successfully authenticated with the Proxy (even anonymously), it SHOULD send a CONNECT request to the appropriate host in order to continue the negotiation. The following rules apply:
 +
The hostname MUST be SHA1(SID + Initiator JID + Target JID) where the definition of the SHA1 hashing algorithm is as specified by RFC 3174 [8] and the output is hexadecimal-encoded (not binary).
 +
The port MUST be 0 (zero).
 +
The JIDs provided MUST be the JIDs used for the IQ exchange, which MAY be full JIDs (<node@domain.tld/resource>) or bare JIDs (<node@domain.tld>).
 +
The appropriate stringprep profiles (as specified in XMPP Core [9]) MUST be applied to the JIDs before application of the SHA1 hashing algorithm.
  
# Имя узла (hostname) должно быть SHA1(ИдПередачи + JID Инициатора + JID Цели), где [[w:Хэширование|хэш-функция]] [[w:SHA-1|SHA-1]] определена согласно RFC 3174 и её выход записывается в [[w:Шестнадцатеричная система счисления|шестнадцатеричной системе счисления]] (не двоичным кодом).
+
Example 14. Target Connects to StreamHost
# Порт (port) ДОЛЖЕН быть 0 (ноль).
+
CMD = X'01'
# Указанные Jabber-идентификаторы ДОЛЖНЫ быть идентификаторами, использующимися для обмена IQ-стансами, которые могут быть полными JID (<tt>node@domain.tld/resource</tt>) или голыми JID (<tt>node@domain.tld</tt>).
+
ATYP = X'03'
# Перед применением алгоритма хэширования SHA-1 к Jabber-идентификаторам ДОЛЖНЫ быть применены соответствующие профили [[stringprep]] (как указано в «[[Основы XMPP|Основах XMPP]]»).
+
DST.ADDR = SHA1 Hash of: (SID + Initiator JID + Target JID)
 +
DST.PORT = 0
 +
   
  
<b id="Example_14">Пример 14. Цель соединяется с ВедущимУзлом</b>
+
Example 15. StreamHost Acknowledges Connection
CMD = X'01'
+
STATUS = X'00'
ATYP = X'03'
+
   
DST.ADDR = SHA1 Hash of: (SID + Initiator JID + Target JID)
+
DST.PORT = 0
+
  
<b id="Example_14">Пример 15. ВедущийУзел принимает соединение</b>
+
When replying to the client in accordance with Section 6 of RFC 1928, the StreamHost SHOULD set the BND.ADDR and BND.PORT to the values provided by the client in the connection request.
STATUS = X'00'
+
4.7 Target Acknowledges SOCKS5 Connection
  
При ответе клиенту, в соответствии с разделом 6 RFC 1928, ВедущемуУзлу СЛЕДУЕТ выставить параметры BND.ADDR и BND.PORT в значения, предоставленные клиентом в запросе соединения.
+
After the Target has authenticated with the StreamHost, it MUST send an IQ-result to the Initiator indicating which StreamHost was used.
  
=== Цель подтверждает соединение SOCKS5 ===
+
Example 16. Target Notifies Initiator of Connection
 +
<iq type='result'
 +
    from='target@host2/bar'
 +
    to='initiator@host1/foo'
 +
    id='initiate'>
 +
  <query xmlns='http://jabber.org/protocol/bytestreams'>
 +
    <streamhost-used jid='proxy.host3'/>
 +
  </query>
 +
</iq>
 +
   
  
После того как Цель будет аутентифицирована ВедущимУзлом, она ДОЛЖНА послать Инициатору IQ-результат, сообщающий о том, какой ВедущийУзел она использует.
+
At this point, the Initiator knows which StreamHost was used by the Target.
 +
4.8 Initiator Establishes SOCKS5 Connection with StreamHost
  
<b id="Example_16">Пример 16. Цель уведомляет Инициатора о соединении.</b>
+
If the StreamHost used is a Proxy, the Initiator MUST authenticate and establish a connection with the StreamHost before requesting that the StreamHost activate bytestream. The Initiator will establish a connection to the SOCKS5 proxy in the same way the Target did (passing the same value for the CONNECT request), as shown in the following examples.
<iq    type='result'
+
        from='target@host2/bar'
+
        to='initiator@host1/foo'
+
        id='initiate'>
+
    <query xmlns='http''':'''//jabber.org/protocol/bytestreams'>
+
        <streamhost-used jid='proxy.host3'/>
+
    </query>
+
</iq>
+
  
Здесь Инициатор узнаёт, какой ВедущийУзел использует Цель.
+
Example 17. Initiator Connects to StreamHost
 
+
CMD = X'01'
=== Инициатор устанавливает соединение SOCKS5 с ВедущимУзлом ===
+
ATYP = X'03'
 +
DST.ADDR = SHA1 Hash of: (SID + Initiator JID + Target JID)
 +
DST.PORT = 0
 +
   
  
Если ВедущийУзел использует Посредника, Инициатор ДОЛЖЕН аутентифицировать и установить соединение с ВедущимУзлом перед запросом активации потока передачи данных. Инициатор установит соединение с прокси-сервером SOCKS5 тем же способом, что и Цель (указывая те же значения в запросе CONNECT), как показано в следущих примерах.
+
Example 18. StreamHost Acknowledges Connection to Initiator
 
+
STATUS = X'00'
 
+
   
<b id="Example_17">Пример 17. Инициатор соединяется с ВедущимУзлом.</b>
+
4.9 Activation of Bytestream
CMD = X'01'
+
ATYP = X'03'
+
DST.ADDR = SHA1 Hash of: (SID + Initiator JID + Target JID)
+
DST.PORT = 0
+
 
+
 
+
<b id="Example_18">Пример 18. ВедущийУзел принимает соединение Инициатора.</b>
+
STATUS = X'00'
+
 
+
=== Activation of Bytestream ===
+
  
 
In order for the bytestream to be used, it MUST first be activated by the StreamHost. If the StreamHost is the Initiator, this is straightforward and does not require any in-band protocol. However, if the StreamHost is a Proxy, the Initiator MUST send an in-band request to the StreamHost. This is done by sending an IQ-set to the Proxy, including an <activate/> element whose XML character data specifies the full JID of the Target.
 
In order for the bytestream to be used, it MUST first be activated by the StreamHost. If the StreamHost is the Initiator, this is straightforward and does not require any in-band protocol. However, if the StreamHost is a Proxy, the Initiator MUST send an in-band request to the StreamHost. This is done by sending an IQ-set to the Proxy, including an <activate/> element whose XML character data specifies the full JID of the Target.
Line 427: Line 456:
 
<not-allowed/> error if only one party (either Initiator or Recipient, but not both) is connected to the Proxy
 
<not-allowed/> error if only one party (either Initiator or Recipient, but not both) is connected to the Proxy
 
<internal-server-error/> error if the proxy cannot activate the bytestream because of some internal malfunction
 
<internal-server-error/> error if the proxy cannot activate the bytestream because of some internal malfunction
 
+
5. Formal Use Case
== Formal Use Case ==
+
  
 
This is a formal representation of the narrative information provided above. The primary actor is the Initiator and the goal is to establish a bytestream between the Initiator and the Target. (Note: "UCE" stands for "Use Case Ends" (success is assumed unless otherwise specified), "P" stands for "Primary Flow", and "A" stands for "Alternate Flow".)
 
This is a formal representation of the narrative information provided above. The primary actor is the Initiator and the goal is to establish a bytestream between the Initiator and the Target. (Note: "UCE" stands for "Use Case Ends" (success is assumed unless otherwise specified), "P" stands for "Primary Flow", and "A" stands for "Alternate Flow".)
=== Primary Flow ===
+
5.1 Primary Flow
 
Initiator wishes to establish a bytestream with Target
 
Initiator wishes to establish a bytestream with Target
 
Initiator sends an IQ-set to Target specifying a StreamID and the network addresses of one or more StreamHosts [A1]
 
Initiator sends an IQ-set to Target specifying a StreamID and the network addresses of one or more StreamHosts [A1]
Line 443: Line 471:
 
Target sends IQ-result to Initiator announcing successful connection to StreamHost [A6]
 
Target sends IQ-result to Initiator announcing successful connection to StreamHost [A6]
 
Use Case Ends (bytestream is established and ready for use)
 
Use Case Ends (bytestream is established and ready for use)
=== Alternate Flows ===
+
5.2 Alternate Flows
  
 
A1. Initiator does not know the full network address of a StreamHost (i.e., Proxy)
 
A1. Initiator does not know the full network address of a StreamHost (i.e., Proxy)
Line 495: Line 523:
 
Initiator receives <internal-server-error/> error from Proxy
 
Initiator receives <internal-server-error/> error from Proxy
 
UCE unsuccessfully
 
UCE unsuccessfully
== Formal Description ==
+
6. Formal Description
=== <query/> Element ===
+
6.1 <query/> Element
  
 
The <query/> element is the container for all in-band communications. This element MUST be in the namespace "http://jabber.org/protocol/bytestreams". This element has a single attribute for the stream session identifier, and contains multiple <streamhost/> elements, a single <streamhost-used/> element, or a single <activate/> element.
 
The <query/> element is the container for all in-band communications. This element MUST be in the namespace "http://jabber.org/protocol/bytestreams". This element has a single attribute for the stream session identifier, and contains multiple <streamhost/> elements, a single <streamhost-used/> element, or a single <activate/> element.
Line 509: Line 537:
  
 
The <activate/> element is used to request activation of a unidirectional or bidirectional bytestream. It MUST be present in the IQ-set sent from the Initiator to the StreamHost after the Initiator receives an IQ-result from the Target, and there MUST be only one instance.
 
The <activate/> element is used to request activation of a unidirectional or bidirectional bytestream. It MUST be present in the IQ-set sent from the Initiator to the StreamHost after the Initiator receives an IQ-result from the Target, and there MUST be only one instance.
=== <streamhost/> Element ===
+
6.2 <streamhost/> Element
  
 
The <streamhost/> element contains the bytestream connection information. This element has attributes for the StreamHost's JID, network host/address, and network port. This element MUST NOT contain any content nodes.
 
The <streamhost/> element contains the bytestream connection information. This element has attributes for the StreamHost's JID, network host/address, and network port. This element MUST NOT contain any content nodes.
Line 522: Line 550:
  
 
When communicating the available hosts, the Initiator MUST include EITHER the host and port OR the zeroconf information.
 
When communicating the available hosts, the Initiator MUST include EITHER the host and port OR the zeroconf information.
=== <streamhost-used/> Element ===
+
6.3 <streamhost-used/> Element
  
 
The <streamhost-used/> element indicates the StreamHost connected to. This element has a single attribute for the JID of the StreamHost to which the Target connected. This element MUST NOT contain any content node.
 
The <streamhost-used/> element indicates the StreamHost connected to. This element has a single attribute for the JID of the StreamHost to which the Target connected. This element MUST NOT contain any content node.
  
 
The "jid" attribute specifies the full JID of the StreamHost. This attribute MUST be present, and MUST be a valid JID for use with an <iq/>.
 
The "jid" attribute specifies the full JID of the StreamHost. This attribute MUST be present, and MUST be a valid JID for use with an <iq/>.
=== <activate/> Element ===
+
6.4 <activate/> Element
  
 
The <activate/> element is a flag to trigger a Proxy to complete a connection.
 
The <activate/> element is a flag to trigger a Proxy to complete a connection.
== Optional UDP Support ==
+
7. Optional UDP Support
  
 
Support for UDP associations is strictly OPTIONAL. However, implementations that support UDP associations MUST adhere to the profile described in this section.
 
Support for UDP associations is strictly OPTIONAL. However, implementations that support UDP associations MUST adhere to the profile described in this section.
=== Discovering UDP Support ===
+
7.1 Discovering UDP Support
  
 
If an implementation supports UDP associations, it MUST advertise that separately by returning a feature of 'http://jabber.org/protocol/bytestreams#udp' in response to Service Discovery information requests.
 
If an implementation supports UDP associations, it MUST advertise that separately by returning a feature of 'http://jabber.org/protocol/bytestreams#udp' in response to Service Discovery information requests.
Line 565: Line 593:
 
</iq>
 
</iq>
 
      
 
      
=== Requesting UDP Mode ===
+
7.2 Requesting UDP Mode
  
 
UDP associations are requested by setting the 'mode' attribute to a value of "udp" rather than "tcp".
 
UDP associations are requested by setting the 'mode' attribute to a value of "udp" rather than "tcp".
Line 584: Line 612:
 
</iq>
 
</iq>
 
      
 
      
=== UDP Process ===
+
7.3 UDP Process
  
 
There is one main difference between UDP mode and TCP mode: rather than simply establishing a TCP connection, the Target and/or Initiator MUST (1) establish a UDP association and then (2) initialize the UDP channel. In particular:
 
There is one main difference between UDP mode and TCP mode: rather than simply establishing a TCP connection, the Target and/or Initiator MUST (1) establish a UDP association and then (2) initialize the UDP channel. In particular:
Line 591: Line 619:
  
 
The processes for establishing the UDP association and for initializing the UDP channel are described below.
 
The processes for establishing the UDP association and for initializing the UDP channel are described below.
==== Establishing the UDP Association ====
+
7.3.1 Establishing the UDP Association
  
 
Once the Target has successfully authenticated with the Proxy (as described under Target Establishes SOCKS5 Connection with StreamHost), it MUST send a UDP ASSOCIATE (rather than CONNECT) request to the host identified by the algorithm defined above.
 
Once the Target has successfully authenticated with the Proxy (as described under Target Establishes SOCKS5 Connection with StreamHost), it MUST send a UDP ASSOCIATE (rather than CONNECT) request to the host identified by the algorithm defined above.
Line 607: Line 635:
 
STATUS = X'00'
 
STATUS = X'00'
 
        
 
        
==== Initializing the UDP Channel ====
+
7.3.2 Initializing the UDP Channel
  
 
After connecting to the StreamHost, the Target (direct connection) or both Target and Initiator (mediated connection) MUST initialize the UDP channel. In order to do so, each sending entity MUST send a SOCKS5 UDP packet to the StreamHost on the same port used for the initial TCP connection (in the foregeoing example, a host of 192.168.4.1 and port of 5086), with DST.PORT set to '1' and DATA containing the sending entity's JID (i.e, the JID of either the Target or Initiator).
 
After connecting to the StreamHost, the Target (direct connection) or both Target and Initiator (mediated connection) MUST initialize the UDP channel. In order to do so, each sending entity MUST send a SOCKS5 UDP packet to the StreamHost on the same port used for the initial TCP connection (in the foregeoing example, a host of 192.168.4.1 and port of 5086), with DST.PORT set to '1' and DATA containing the sending entity's JID (i.e, the JID of either the Target or Initiator).
Line 634: Line 662:
  
 
Note: Since UDP is not reliable, the Target SHOULD resend the UDP packet if the reply notification is not received within a short time (a 5-second retry is RECOMMENDED). The StreamHost SHOULD ignore duplicate UDP initialization packets once it has replied with a notification.
 
Note: Since UDP is not reliable, the Target SHOULD resend the UDP packet if the reply notification is not received within a short time (a 5-second retry is RECOMMENDED). The StreamHost SHOULD ignore duplicate UDP initialization packets once it has replied with a notification.
=== Exchanging UDP Packets ===
+
7.4 Exchanging UDP Packets
  
 
Once the UDP association is established, UDP packets can be exchanged with the StreamHost. When a UDP packet is sent by either party, it MUST contain a 4-byte header (in addition to other possible headers, such as that of SOCKS5), which consists of the source virtual port and then the destination virtual port of the packet, both 16-bit values in network byte order. This allows the peers to multiplex many packets for different purposes over one session. The actual application data should follow this header, and thus the payload size will always be "Application Data Size + 4".
 
Once the UDP association is established, UDP packets can be exchanged with the StreamHost. When a UDP packet is sent by either party, it MUST contain a 4-byte header (in addition to other possible headers, such as that of SOCKS5), which consists of the source virtual port and then the destination virtual port of the packet, both 16-bit values in network byte order. This allows the peers to multiplex many packets for different purposes over one session. The actual application data should follow this header, and thus the payload size will always be "Application Data Size + 4".
Line 650: Line 678:
  
 
The programming interface for a SOCKS5 Bytestreams-aware UDP MUST report an available buffer space for UDP datagrams that is smaller than the actual space provided by the operating system and SOCKS5 layer if applicable. In other words, 4 more octets smaller.
 
The programming interface for a SOCKS5 Bytestreams-aware UDP MUST report an available buffer space for UDP datagrams that is smaller than the actual space provided by the operating system and SOCKS5 layer if applicable. In other words, 4 more octets smaller.
== Implementation Notes ==
+
8. Implementation Notes
=== StreamHost Requirements ===
+
8.1 StreamHost Requirements
  
 
A StreamHost MUST support TCP connections.
 
A StreamHost MUST support TCP connections.
Line 665: Line 693:
 
Support UDP associations in addition TCP connections.
 
Support UDP associations in addition TCP connections.
 
Ignore the DST.ADDR and DST.PORT parameters if desired.
 
Ignore the DST.ADDR and DST.PORT parameters if desired.
=== SOCKS5 Parameter Mapping ===
+
8.2 SOCKS5 Parameter Mapping
  
 
To facilitate the usage of SOCKS5, command parameters MUST be mapped to the appropriate values. Parameters not specified in the table below SHOULD be used as defined in RFC 1928.
 
To facilitate the usage of SOCKS5, command parameters MUST be mapped to the appropriate values. Parameters not specified in the table below SHOULD be used as defined in RFC 1928.
Line 688: Line 716:
 
DST.PORT 0 or 1, for payload or initialization packets, respectively.
 
DST.PORT 0 or 1, for payload or initialization packets, respectively.
  
== Security Considerations ==
+
9. Security Considerations
  
 
This proposal does not include a method for securing or encrypting SOCKS5 bytetreams. If such security is desired, it MUST be negotiated over the bytestream (once established) using standard protocols such as SSL or TLS. Negotiation of such security methods is outside the scope of this document.
 
This proposal does not include a method for securing or encrypting SOCKS5 bytetreams. If such security is desired, it MUST be negotiated over the bytestream (once established) using standard protocols such as SSL or TLS. Negotiation of such security methods is outside the scope of this document.
== IANA Considerations ==
+
10. IANA Considerations
  
 
This document requires no interaction with the Internet Assigned Numbers Authority (IANA) [10].
 
This document requires no interaction with the Internet Assigned Numbers Authority (IANA) [10].
== XMPP Registrar Considerations ==
+
11. XMPP Registrar Considerations
=== Protocol Namespaces ===
+
11.1 Protocol Namespaces
  
 
The XMPP Registrar [11] includes 'http://jabber.org/protocol/bytestreams' in its registry of protocol namespaces.
 
The XMPP Registrar [11] includes 'http://jabber.org/protocol/bytestreams' in its registry of protocol namespaces.
=== Service Discovery Features ===
+
11.2 Service Discovery Features
  
 
The XMPP Registrar shall includes 'http://jabber.org/protocol/bytestreams#udp' in its registry of service discovery features.
 
The XMPP Registrar shall includes 'http://jabber.org/protocol/bytestreams#udp' in its registry of service discovery features.
=== Service Discovery Category/Type ===
+
11.3 Service Discovery Category/Type
  
 
The XMPP Registrar includes the "proxy" category and associated "bytestreams" type in the Service Discovery registry. The registry submission is as follows:
 
The XMPP Registrar includes the "proxy" category and associated "bytestreams" type in the Service Discovery registry. The registry submission is as follows:
Line 715: Line 743:
 
   </category>
 
   </category>
 
      
 
      
== Schema ==
+
12. Schema
  
 
<?xml version='1.0' encoding='UTF-8'?>
 
<?xml version='1.0' encoding='UTF-8'?>
Line 791: Line 819:
  
 
</xs:schema>
 
</xs:schema>
 
+
 
= Выходные данные =
+
Notes
 
+
== Notes ==
+
  
 
1. RFC 3920: Extensible Messaging and Presence Protocol (XMPP): Core <http://tools.ietf.org/html/rfc3920>.
 
1. RFC 3920: Extensible Messaging and Presence Protocol (XMPP): Core <http://tools.ietf.org/html/rfc3920>.
Line 817: Line 843:
  
 
11. The XMPP Registrar maintains a list of reserved protocol namespaces as well as registries of parameters used in the context of XMPP extension protocols approved by the XMPP Standards Foundation. For further information, see <http://www.xmpp.org/registrar/>.
 
11. The XMPP Registrar maintains a list of reserved protocol namespaces as well as registries of parameters used in the context of XMPP extension protocols approved by the XMPP Standards Foundation. For further information, see <http://www.xmpp.org/registrar/>.
== Revision History ==
+
Revision History
 
Version 1.7 (2007-05-21)
 
Version 1.7 (2007-05-21)
  

Please note that all contributions to JaWiki (Jabber/XMPP wiki) may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see JaWiki (Jabber/XMPP wiki):Copyrights for details). Do not submit copyrighted work without permission!

Cancel | Editing help (opens in new window)