001/*
002 *
003 * Copyright the original author or authors
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.bytestreams.socks5;
018
019import java.io.DataInputStream;
020import java.io.IOException;
021
022import org.jivesoftware.smack.util.SHA1;
023
024import org.jxmpp.jid.Jid;
025
026/**
027 * A collection of utility methods for SOcKS5 messages.
028 *
029 * @author Henning Staib
030 */
031public class Socks5Utils {
032
033    /**
034     * Returns a SHA-1 digest of the given parameters as specified in <a
035     * href="http://xmpp.org/extensions/xep-0065.html#impl-socks5">XEP-0065</a>.
036     *
037     * @param sessionID for the SOCKS5 Bytestream
038     * @param initiatorJID JID of the initiator of a SOCKS5 Bytestream
039     * @param targetJID JID of the target of a SOCKS5 Bytestream
040     * @return SHA-1 digest of the given parameters
041     */
042    public static String createDigest(String sessionID, Jid initiatorJID, Jid targetJID) {
043        StringBuilder b = new StringBuilder();
044        b.append(sessionID).append(initiatorJID).append(targetJID);
045        return SHA1.hex(b.toString());
046    }
047
048    /**
049     * Reads a SOCKS5 message from the given InputStream. The message can either be a SOCKS5 request
050     * message or a SOCKS5 response message.
051     * <p>
052     * (see <a href="http://tools.ietf.org/html/rfc1928">RFC1928</a>)
053     *
054     * @param in the DataInputStream to read the message from
055     * @return the SOCKS5 message
056     * @throws IOException if a network error occurred
057     */
058    public static byte[] receiveSocks5Message(DataInputStream in) throws IOException {
059        byte[] header = new byte[5];
060        in.readFully(header, 0, 5);
061
062        if (header[3] != (byte) 0x03) {
063            throw new IOException("Unsupported SOCKS5 address type: " + header[3] + " (expected: 0x03)");
064        }
065
066        int addressLength = header[4];
067
068        byte[] response = new byte[7 + addressLength];
069        System.arraycopy(header, 0, response, 0, header.length);
070
071        in.readFully(response, header.length, addressLength + 2);
072
073        return response;
074    }
075
076}