Parsing XMPP protocol analysis and application

Source: Internet
Author: User
Tags starttls


Parsing XMPP protocol analysis and application XMPP is an XML-based protocol that inherits the flexible development in the XML environment. Therefore, XMPP-based applications are highly scalable. After the extension, XMPP can send extended information to meet user requirements, and create application processes such as the content publishing system and address-based services at the top of XMPP. In addition, XMPP includes a software protocol for the server to enable communication with the other, making it easier for developers to build customer applications or add functions to a system. XMPP (Scalable Message Processing site protocol) is based on the Extensible Markup Language (XML) protocol, which is used for instant messaging (IM) and online on-site detection. It facilitates quasi-real-time operations between servers. This protocol may eventually allow Internet users to send instant messages to anyone else on the Internet, even if the operating system is different from the browser. The predecessor of XMPP is Jabber, an open-source network instant communication protocol. XMPP has been standardized by IETF International Standards Organization.
1 XMPP address and data structure 1.1 entity address www.2cto.com XMPP overall framework 1 is shown. In the figure, the addresses of various entities (such as XMPP customers, servers, and gateways) in the XMPP framework are called Jabber Identifier and JID ). JID uniquely identifies an independent object or entity for instant message and online status information communication, and can be compatible with Entity IDs and online status information of other instant messaging systems (such as MSN. The syntax is as follows: [node "@"] domain name ["/" resource]. The length of each domain cannot exceed bytes, and the total length cannot exceed bytes.

XMPP defines three roles: client, server, and gateway. Communication can take place between any two of the three. The server also undertakes the client information record, connection management and information routing functions. Gateways are interconnected with heterogeneous instant messaging systems. heterogeneous systems can include SMS, MSN, and ICQ. The basic network mode is that a single client connects to a single server through TCP/IP, and then transmits XML on it. Commands related to instant messaging are transmitted. In the past, these commands were either sent in a binary format (for example, QQ), or sent in a text-only command with a space and a parameter with a line break (for example, MSN ). The logic of the instant messaging commands transmitted by XMPP is similar to that in the past, but the Protocol format is changed to plain text in XML format. This not only makes parsing easier, but also makes reading easier, facilitating development and troubleshooting. The core part of XMPP is a stream protocol that sends XML data in parts on the network. This stream protocol is the basis for transmitting XMPP instant messaging commands, and is also a very important basic network protocol that can be further used. Therefore, XMPP uses TCP to transmit XML streams.
The domain name specifies the XMPP server that the object is connected. Each available XMPP server has a complete domain name, which can be found in the Domain Name System (DNS). A node can represent a user, a type of application, or a service, all nodes correspond to a precise domain name. Resources are used to identify special objects (such as devices or locations) belonging to users, allowing a user to connect multiple resources to the same XMPP server at the same time. 1.2 XMPP data structure because XMPP is an XML-based protocol, users can define tags based on their own needs to express almost any structured data, you can also easily create custom applications or add features.
1.2.1 The three top-level XML elements www.2cto.com defined by XMPP are <message/>, <presence/>, and <iq/> (info/query ), each element can contain a large amount of data through attributes and namespace. Its Attributes and namespace are all part of XMPP. The <message/> element is used to contain the message content sent between two XMPP entities. The <presence/> element indicates the entity availability information, availability information is available and unavailable. <iq/> elements are used to construct sessions between two entities, it also allows objects to send requests and responses in XML format back and forth to obtain or set public user information, such as names. In the instant mail, the name conflict problem is solved using the namespace feature of XML. The XML namespace defines a method to associate the elements and attributes used in the XML with the reference of the Uniform Resource Locator (Uniform Resource Locator, URL) to define the elements and attributes. A uniform resource locator (URL) is a way to fully describe the addresses of web pages and other resources on the Internet. Each web page on the Internet has a unique name, usually called a URL address, which can be a local disk or a computer on the LAN, more websites are on the Internet. Simply put, a URL is a Web address, commonly known as a "Web site ".
1.2.2 XMPP data structure in terms of structure, XMPP has three types of data: XML Stream, stream authentication, and XML section. An XML STream is a container for entity exchange of XML elements. It starts with <stream> and ends with </STream>. It is a standard method for both parties to transmit data asynchronously, the XMPP communication process is in the outermost layer. XML is a structured unit of information transmitted by an object through an XML Stream. In an XML stream, it starts with a submark with a depth of 1, end with a submark with a depth of 1, which are <message/>, <presence/>, and <iq/>. XMPP acts as a common "Transport Layer" for XML streams. XML streams contain transmitted authentication information and on-site messages. XMPP can efficiently route data to the most appropriate request source and simplify the implementation on the client to the maximum extent, this makes it possible to exchange information across applications in real time.
2. Work Process (1) nodes (such as yb and pt) connect to the local server. ① XMPP users apply for a Socket connection on the server by opening an XML stream from the client to the server. SEND: <stream: stream to = 'sdpt.com 'xmlns = 'jabber: client' xmlns: stream = 'http://etherx.jabber.org/streams'> ② the server replies by opening an XML stream from the server to the client. RECV: <stream: stream from = 'sdpt.com 'id = '000000' xmlns = 'jabber: client' xmlns: stream = 'http://etherx.jabber.org/streams'> (2) the node applies to the local server for logon. ① The user asks about the information required to log on to the server. SEND: <iq id = '2' type = 'get'> <query xmlns = 'jabber: iq: auth '> <username> yb </username> </query> </iq> ② the server responds to the user and notifies the user of the information required for logon. ③ The user provides the required information. ④ The server returns an empty iq element of the "result" type, indicating that the logon is successful. RECV: <iq id = '3' type = 'result'/> ⑤ The yb user sends the current status to the server, indicating that the user is online. SEND: <presence> <status> ONline </status> </presence> (3) a user obtains a roster and adds a contact to a friend (for example, yb learns that a friend sd is ONline ). (4) send messages between users (for example, yb sends messages to sd ). The user sends a message: www.2cto.com SEND: <message to 'sd@jabber.org'> <body> Where are you? </Body> </message> the Server adds a source address based on the XMPP user's session information, so that when the recipient receives the message, the message contains the source address. (5) the XMPP server searches for, connects to, and authenticates the target server based on the domain name in the target JID (for example, sdpt.com searches for jabber.org using DNS, connects to the jabber.org server, and performs authentication ). (6) XMPP server jabber.org confirms that sd is connected to this server, and yb is authorized to communicate with sd. (7) data flows between yb and sd. (8) The user exits and only needs to disable <stream> when exiting.
3 Security Mechanism 3.1 Simple Authentication and Security full-Layer negotiation mechanism Simple Authentication and Security Layer (SASL) can be used to add Authentication mechanisms to connection-based protocols, provides multiple authentication methods such as KERBEROS_V4, PLAIN and DIGEST-MD5. Each authentication mechanism contains information such as the authentication mechanism name, authentication process initialization command, authentication control command, specific 8-bit code, and interpreter. During the authentication process, the authentication server completes authentication, authorization identity transfer, simple authentication, and full-layer negotiation. In XMPP, the SASL processing steps are as follows (C: client, S: SASL authentication server): (1) establish a connection between C and S. (2) S provides a list of authentication mechanisms to C. (3) C. Select an authentication mechanism from the authentication mechanism list. (4) S asks C for authorization information. (5) C. Submit the authorization information to S. (6) S returns the authentication success or failure information to C.
3.2 In the communication process, two XMPP servers often need to communicate with each other. To prevent information forgery by using server spoofing, XMPP adopts the callback authentication mechanism. Callback authentication relies on DNS technology. Using the callback authentication mechanism, a server can check whether the server that establishes a connection with itself has been legally authorized. The callback authentication process is as follows: (1) the source server establishes a connection with the receiving server and requests authentication from the receiving server. Receives the server response and assigns the authentication session ID. (2) The source server sends an authentication key to the receiving server. (3) establish a connection between the receiving server and the authentication server. The authentication server also assigns a verification session ID for this authentication session. (4) the receiving server sends the key and verification session ID submitted by the source server to the authentication server for verification. (5) The authentication server verifies the key and returns the authentication result to the receiving server. (6) the receiving server returns the authentication result to the source server.
3.3 encryption although SASL provides an advanced authentication mechanism, both parties must pass the specific authorization authentication before normal communication can be conducted, but the login information is generally important information such as passwords and usernames, most of them are transmitted in plain text, so they are easily eavesdropped. To solve this problem, XMPP uses the "STARTTLS" extension based on the Transport Layer Security Protocol to provide both parties with confidentiality and data integrity services. The TLS Protocol includes two protocol groups-TLS record protocol and TLS handshake protocol-each group has a lot of information in different formats. TLS record protocol is a hierarchical protocol. The information in each layer may contain fields such as length, description, and content. The record protocol supports information transmission, data segmentation to processing blocks, data compression, MAC, encryption, and transmission results. Decrypt, verify, decompress, and reorganize the received data, and then send them to the high-level client. The TLS connection status refers to the operation environment of the TLS record protocol. It specifies the compression algorithm, encryption algorithm, and MAC algorithm. The TLS record layer receives continuous data of any size without blank blocks from the top layer. Key computing: The record protocol uses algorithms to Generate Keys, IV, and MAC keys from the security parameters provided by the handshake protocol. The TLS handshake protocol consists of three sub-protocol groups, which allow peer-to-peer parties to reach an agreement on the security parameters of the record layer, perform self-authentication, negotiate security parameters through examples, and report error conditions to each other. Www.2cto.com
The TLS Protocol framework consists of two layers: TLS handshake protocol and TLS record protocol. The TLS handshake protocol is used to enable servers and customers to exchange TLS Protocol version information, negotiate encryption algorithms, perform (mutual) identity authentication, and exchange keys before transmitting application layer data. The TLS record protocol is used to group, compress, and encrypt information provided by the application layer. The data integrity check is performed by comparing whether the MAC values of the data calculated by using security hash functions (such as SHA and MD5) before and after transmission are consistent. Data encryption uses symmetric cryptographic algorithms (such as R4 and DES ). Data Integrity check and encryption keys are negotiated by the TLS handshake protocol.
The STARTTLS extension process adopted in XMPP is as follows (C: client, S: TLS server): (1) Establish an XML stream session connection between C and S. (2) S sends a list of STARTTLS extension service requirements and other authentication mechanisms to C. The code example is as follows: <stream: features> <starttls xmlns = 'urn: ietf: params: xml: ns: xmpp-tls '> <required/> </starttls> <mechanic ISMs xmlns =' urn: ietf: params: xml: ns: xmppsasl '> <mechanical> DIGEST-MD5 </mechanical> <mechanical> PLAIN </mechanical> </mechanical ISMs> </stream: features>
(3) C. Send the STARTTLS command to S. (4) TLS handshake protocols in C and S start to negotiate encryption algorithms and keys. (5) If the TLS handshake protocol is successfully negotiated, the current XML stream session is closed. C initiates a New XML stream session, and all transmitted information is encrypted by the TLS record protocol. If the TLS handshake protocol negotiation fails, a warning is sent. (6) S replies the New XML stream session to C.
4. Key issues in client programming because a large number of XMPP servers already exist in the network, in general application development, you only need to design custom client programs, you can also use the Smack library to accelerate development. (1) Create an XMPP connection. Because XMPP uses the TCP protocol, you must first create a network connection. XMPPConnection is the class used by the Smack library to create a connection to the XMPP server. The code for creating an XMPP connection is as follows: XMPPConnection connection = new XMPPConnection ("jab-ber.org"); www.2cto.com to create an encrypted connection, you can use SSLXMPPConnection class: XMPPConnection connection = new SSLXMPPConnection ("jabber.org"); (2) log on. After a TCP connection is created, you need to use the user name and password to log on to the XMPP server. The logon program can use the XMPPConnection. login (String username, String password) method. After logging on, you can chat with others.
Connection. login ("yb", "password"); // connection is the created XMPP connection, the same as connection. createChat ("yb@sdpt.com ″). SendMessage ("Hello! "); (3) operate the roster. Each user includes an XMPP address (such as mailto: % E2 % 80% 9Cyb@sdpt.com), name, or nickname (such as "yb ″), and its list (such as friends and colleagues ). The Roster can track whether a friend or user group is online and its status information. After logon, you can use the Roster class to obtain the status of a friend or user group. The Code is as follows: roster Roster = con. getRoster (); for (Iterator I = roster. getEntries (); I. hasNext ();) {System. out. println (I. next ();} the roster information is usually changed at any time and may need to be added or deleted. You can use RosterListener to listen for changes to the List and its online status.
(4) send and receive messages. You can use the Chat and GroupChat classes to send and receive messages. The following describes how to use Chat to send text messages. GroupChat is used in a similar way. Chat newChat = connection. createChat ("yb@sdpt.com"); // create a new Chat newChat. sendMessage ("Hello! "); // Send the message" Hello! Using the Chat. sendMessage () method, you can easily create a message object. Its parameter is the message content, and the message will be sent after execution. Chat newChat = connection. createChat (yb@sdpt.com "); newMessage. setBody ("Hi, I'm waiting for you. "); while (true) {www.2cto.com Message message = newChat. nextMessage (); // wait for the recipient to send the message newChat. sendMessage (message. getBody (); // send the message sent from the peer} // back to (5) modify the status. You can use presence. Type. UNAV-ILABLE as the parameter to create a presence, and the status changes to offline. Presence presence = new Presence (Presence. type. UNAVAILABLE); presence. setStatus ("Gone skating"); 5 conclusion currently, 0.2 million instant messaging platforms around the world support XMPP, with 1 million users in use. Simple interfaces, open protocols, interconnected architectures, authoritative standards, and a solid user base are the advantages of XMPP. From weiku electronic market

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.