/*
   cipelib - library routines common to CIPE (user-mode part) and PKCIPE

   Copyright 2000 Olaf Titz <olaf@bigred.inka.de>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version
   2 of the License, or (at your option) any later version.
*/
/* $Id: socks5_cmd.c,v 1.2 2000/11/22 20:23:38 olaf Exp $ */

#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include "cipelib.h"
#include "socks5_internal.h"

int socks5_cmd(int fd, int cmd, struct sockaddr_in *so)
{
    struct socksrq r;
    r.ver=5;
    r.cmd=cmd;
    r.rsv=0;
    r.atyp=1;
    r.dstaddr=so->sin_addr.s_addr;
    r.dstport=so->sin_port;
    if (writen(fd, (char *)&r, sizeof(r), "socks5_cmd: wcmd")<0)
	goto error;
    if (readn(fd, (char *)&r, sizeof(r), "socks5_cmd: rreply")<0)
	goto error;
    if (r.cmd==0) {
	if (r.atyp!=1) {
	    cipe_syslog(LOG_ERR,
                        "socks5_cmd: unknown address type %d", r.atyp);
	    goto error;
	}
	so->sin_addr.s_addr=r.dstaddr;
	so->sin_port=r.dstport;
	return fd;
    }
    cipe_syslog(LOG_ERR, "socks5_cmd: server: %s",
                (r.cmd>SOCKS5_MAXERR) ?
                "Unknown error" : socks_errlist[(int)r.cmd]);
 error:
    close(fd);
    return -1;
}
