File:  [ELWIX - Embedded LightWeight unIX -] / libaitrpc / src / cli.c
Revision 1.29: download - view: text, annotated - select for diffs - revision graph
Wed Mar 20 17:32:31 2024 UTC (7 months, 2 weeks ago) by misho
Branches: MAIN
CVS tags: rpc9_6, RPC9_5, HEAD
Version 9.5

/*************************************************************************
* (C) 2010 AITNET ltd - Sofia/Bulgaria - <misho@aitbg.com>
*  by Michael Pounov <misho@openbsd-bg.org>
*
* $Author: misho $
* $Id: cli.c,v 1.29 2024/03/20 17:32:31 misho Exp $
*
**************************************************************************
The ELWIX and AITNET software is distributed under the following
terms:

All of the documentation and software included in the ELWIX and AITNET
Releases is copyrighted by ELWIX - Sofia/Bulgaria <info@elwix.org>

Copyright 2004 - 2024
	by Michael Pounov <misho@elwix.org>.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:
This product includes software developed by Michael Pounov <misho@elwix.org>
ELWIX - Embedded LightWeight unIX and its contributors.
4. Neither the name of AITNET nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY AITNET AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
#include "global.h"


/*
 * rpc_cli_openBLOBClient() - Connect to BLOB Server
 *
 * @rpccli = RPC Client session
 * @Port = Port for bind server, if Port == 0 default port is selected
 * return: NULL == error or !=NULL connection to BLOB server established
 */
rpc_cli_t *
rpc_cli_openBLOBClient(rpc_cli_t * __restrict rpccli, u_short Port)
{
	rpc_cli_t *cli = NULL;
	int n;

	if (!rpccli) {
		rpc_SetErr(EINVAL, "Invalid parameters can`t connect to BLOB server");
		return NULL;
	}

	cli = e_malloc(sizeof(rpc_cli_t));
	if (!cli) {
		LOGERR;
		return NULL;
	} else
		memcpy(cli, rpccli, sizeof(rpc_cli_t));

	memcpy(&cli->cli_sa, &rpccli->cli_sa, sizeof cli->cli_sa);
	switch (cli->cli_sa.sa.sa_family) {
		case AF_INET:
			cli->cli_sa.sin.sin_port = 
				htons(Port ? Port : ntohs(cli->cli_sa.sin.sin_port) + 1);
			break;
		case AF_INET6:
			cli->cli_sa.sin6.sin6_port = 
				htons(Port ? Port : ntohs(cli->cli_sa.sin6.sin6_port) + 1);
			break;
		case AF_LOCAL:
			strlcat(cli->cli_sa.sun.sun_path, ".blob", sizeof cli->cli_sa.sun.sun_path);
			break;
		default:
			rpc_SetErr(EINVAL, "Invalid socket type %d", cli->cli_sa.sa.sa_family);
			return NULL;
	}

	AIT_COPY_VAL(&cli->cli_buf, &rpccli->cli_buf);
	n = AIT_LEN(&cli->cli_buf);

	/* connect to BLOB server */
	cli->cli_sock = socket(cli->cli_sa.sa.sa_family, SOCK_STREAM, 0);
	if (cli->cli_sock == -1) {
		LOGERR;
		e_free(cli);
		return NULL;
	}
	if (setsockopt(cli->cli_sock, SOL_SOCKET, SO_SNDBUF, &n, sizeof n) == -1) {
		LOGERR;
		close(cli->cli_sock);
		e_free(cli);
		return NULL;
	}
	if (setsockopt(cli->cli_sock, SOL_SOCKET, SO_RCVBUF, &n, sizeof n) == -1) {
		LOGERR;
		close(cli->cli_sock);
		e_free(cli);
		return NULL;
	}
	if (connect(cli->cli_sock, &cli->cli_sa.sa, e_addrlen(&cli->cli_sa)) == -1) {
		LOGERR;
		close(cli->cli_sock);
		e_free(cli);
		return NULL;
	} else
		fcntl(cli->cli_sock, F_SETFL, fcntl(cli->cli_sock, F_GETFL) | O_NONBLOCK);

	return cli;
}

/*
 * rpc_cli_closeBLOBClient() - Close connection to BLOB server and free resources
 *
 * @cli = BLOB Client session
 * return: none
 */
void
rpc_cli_closeBLOBClient(rpc_cli_t ** __restrict cli)
{
	if (!cli || !*cli)
		return;

	shutdown((*cli)->cli_sock, SHUT_RDWR);
	close((*cli)->cli_sock);

	AIT_FREE_VAL(&(*cli)->cli_buf);

	e_free(*cli);
	*cli = NULL;
}

/* -------------------------------------------------------------- */

/*
 * rpc_cli_openClient() - Connect to RPC Server
 *
 * @InstID = InstID for RPC session request
 * @netBuf = Network buffer length (min:512 bytes), if =0 == BUFSIZ (also meaning max RPC packet)
 * @csHost = Host name or IP address for bind server
 * @Port = Port for bind server, if Port == 0 default port is selected
 * @proto = Protocol, if == 0 choose SOCK_STREAM
 * return: NULL == error or !=NULL connection to RPC server established
 */
rpc_cli_t *
rpc_cli_openClient(u_char InstID, int netBuf, const char *csHost, u_short Port, int proto)
{
	int n = 1;
	rpc_cli_t *cli = NULL;
	sockaddr_t sa = E_SOCKADDR_INIT;
	socklen_t salen;

	if (proto < 0 || proto > SOCK_RAW) {
		rpc_SetErr(EINVAL, "Invalid parameters can`t open RPC client");
		return NULL;
	}

	srandom(time(NULL) ^ getpid());

	if (!Port && proto < SOCK_RAW)
		Port = RPC_DEFPORT;
	if (!(salen = e_gethostbyname(csHost, Port, &sa)))
		return NULL;
	if (!proto)
		proto = SOCK_STREAM;
	if (netBuf < RPC_MIN_BUFSIZ)
		netBuf = BUFSIZ;
	else
		netBuf = E_ALIGN(netBuf, 2);	/* align netBuf length */

	cli = e_malloc(sizeof(rpc_cli_t));
	if (!cli) {
		LOGERR;
		return NULL;
	} else
		memset(cli, 0, sizeof(rpc_cli_t));

	/* build session */
	cli->cli_parent = e_malloc(sizeof(rpc_sess_t));
	if (!cli->cli_parent) {
		LOGERR;
		e_free(cli);
		return NULL;
	} else {
		((rpc_sess_t*) cli->cli_parent)->sess_version = RPC_VERSION;
		((rpc_sess_t*) cli->cli_parent)->sess_instance = InstID;
	}

	cli->cli_id = proto;
	memcpy(&cli->cli_sa, &sa, sizeof cli->cli_sa);
	AIT_SET_BUFSIZ(&cli->cli_buf, 0, netBuf);

	/* connect to RPC server */
	cli->cli_sock = socket(cli->cli_sa.sa.sa_family, cli->cli_id, 
			cli->cli_id == SOCK_RAW ? IPPROTO_ERPC : 0);
	if (cli->cli_sock == -1) {
		LOGERR;
		goto err;
	}
	if (setsockopt(cli->cli_sock, SOL_SOCKET, SO_SNDBUF, 
				&netBuf, sizeof netBuf) == -1) {
		LOGERR;
		goto err;
	}
	if (setsockopt(cli->cli_sock, SOL_SOCKET, SO_RCVBUF, 
				&netBuf, sizeof netBuf) == -1) {
		LOGERR;
		goto err;
	}
	if (cli->cli_id == SOCK_STREAM) {
		setsockopt(cli->cli_sock, IPPROTO_TCP, TCP_NODELAY, &n, sizeof n);
		if (connect(cli->cli_sock, &cli->cli_sa.sa, salen) == -1) {
			LOGERR;
			goto err;
		}
	}
	if (cli->cli_id == SOCK_DGRAM) {
		sockaddr_t sa2;

		if (!(salen = e_gethostbyname(csHost, 0, &sa2)))
			goto err;
		if (bind(cli->cli_sock, &sa2.sa, salen) == -1) {
			LOGERR;
			goto err;
		}
	}

	fcntl(cli->cli_sock, F_SETFL, fcntl(cli->cli_sock, F_GETFL) | O_NONBLOCK);
	return cli;
err:
	AIT_FREE_VAL(&cli->cli_buf);
	if (cli->cli_sock > 2)
		close(cli->cli_sock);
	e_free(cli->cli_parent);
	e_free(cli);
	return NULL;
}

/*
 * rpc_cli_reconnectClient() - Reconnecting client to RPC server
 *
 * @cli = RPC Client session
 * return: -1 error or 0 ok
 */
int
rpc_cli_reconnectClient(rpc_cli_t * __restrict cli)
{
	int netBuf;

	if (!cli)
		return -1;
	else
		netBuf = AIT_LEN(&cli->cli_buf);

	if (cli->cli_id == SOCK_STREAM)
		shutdown(cli->cli_sock, SHUT_RDWR);
	if (cli->cli_id == SOCK_DGRAM && cli->cli_sa.sa.sa_family == AF_LOCAL) {
		sockaddr_t sa2 = E_SOCKADDR_INIT;
		socklen_t salen = sizeof sa2;

#ifndef __linux__
		sa2.sa.sa_len = salen;
#endif
		if (!getsockname(cli->cli_sock, &sa2.sa, &salen))
			unlink(sa2.sun.sun_path);
	}
	close(cli->cli_sock);

	srandom(time(NULL) ^ getpid());

	cli->cli_sock = socket(cli->cli_sa.sa.sa_family, cli->cli_id, 0);
	if (cli->cli_sock == -1) {
		LOGERR;
		return -1;
	}
	if (setsockopt(cli->cli_sock, SOL_SOCKET, SO_SNDBUF, 
				&netBuf, sizeof netBuf) == -1) {
		LOGERR;
		close(cli->cli_sock);
		return -1;
	}
	if (setsockopt(cli->cli_sock, SOL_SOCKET, SO_RCVBUF, 
				&netBuf, sizeof netBuf) == -1) {
		LOGERR;
		close(cli->cli_sock);
		return -1;
	}
	if (cli->cli_id == SOCK_STREAM)
		if (connect(cli->cli_sock, &cli->cli_sa.sa, e_addrlen(&cli->cli_sa)) == -1) {
			LOGERR;
			close(cli->cli_sock);
			return -1;
		}

	fcntl(cli->cli_sock, F_SETFL, fcntl(cli->cli_sock, F_GETFL) | O_NONBLOCK);
	return 0;
}

/*
 * rpc_cli_closeClient() - Close connection to RPC server and free resources
 *
 * @cli = RPC Client session
 * return: none
 */
void
rpc_cli_closeClient(rpc_cli_t ** __restrict cli)
{
	if (!cli || !*cli || (*cli)->cli_id == SOCK_BPF)
		return;

	if ((*cli)->cli_id == SOCK_STREAM)
		shutdown((*cli)->cli_sock, SHUT_RDWR);
	if ((*cli)->cli_id == SOCK_DGRAM && (*cli)->cli_sa.sa.sa_family == AF_LOCAL) {
		sockaddr_t sa2 = E_SOCKADDR_INIT;
		socklen_t salen = sizeof sa2;

#ifndef __linux__
		sa2.sa.sa_len = salen;
#endif
		if (!getsockname((*cli)->cli_sock, &sa2.sa, &salen))
			unlink(sa2.sun.sun_path);
	}
	close((*cli)->cli_sock);

	AIT_FREE_VAL(&(*cli)->cli_buf);

	if ((*cli)->cli_parent)
		e_free((*cli)->cli_parent);

	e_free(*cli);
	*cli = NULL;
}

/*
 * rpc_pkt_Send() - Send RPC packet
 *
 * @sock = Socket
 * @type = Type of socket
 * @sa = Server address
 * @pkt = RPC packet
 * @len = Length of packet
 * return: -1 error, 0  EOF or >0 sended bytes
 */
int
rpc_pkt_Send(int sock, int type, sockaddr_t * __restrict sa, ait_val_t * __restrict pkt, int len)
{
	if (!pkt) {
		rpc_SetErr(EINVAL, "Invalid argument(s)!");
		return -1;
	}

	return rpc_Write(sock, type, MSG_NOSIGNAL, sa, pkt, len);
}

/*
 * rpc_pkt_Receive() - Receive RPC packet
 *
 * @sock = Socket
 * @type = Type of socket
 * @sa = Server address
 * @pkt = RPC packet
 * @seq = Signed packet with seq.no
 * return: -1 error, 0 EOF or >0 received bytes
 */
int
rpc_pkt_Receive(int sock, int type, sockaddr_t * __restrict sa, ait_val_t * __restrict pkt, int seq)
{
	int ret;
	struct tagRPCCall *rpc;

	if (!pkt) {
		rpc_SetErr(EINVAL, "Invalid argument(s)!");
		return -1;
	}

	/* reply from RPC server */
	do {
		if (type == SOCK_STREAM || type == SOCK_EXT)
			ret = rpc_Read(sock, type, 0, NULL, pkt);
		else
			ret = rpc_Read(sock, type, 0, sa, pkt);

		if (ret > 0) {
			rpc = (struct tagRPCCall*) AIT_GET_BUF(pkt);
			if (ret < ntohl(rpc->call_len))
				continue;

			/* check for loop request */
			if (!(rpc->call_io & RPC_ACK))
				continue;
			/* check for signed request */
			if (seq != ntohl(rpc->call_seq))
				continue;
		}
	} while (ret < 0);

	return ret;
}

/*
 * rpc_pkt_Request() - Build RPC Request packet
 *
 * @pkt = Packet buffer
 * @sess = RPC session info
 * @tag = Function tag for execution
 * @vars = Function argument array of values, may be NULL
 * @noreply = >0 We not want RPC reply, -1 IPC request with reply
 * @nocrc = Without CRC calculation
 * @seq = Sign packet with seq.no
 * return: -1 error or != -1 prepared bytes into packet
 */
int
rpc_pkt_Request(ait_val_t * __restrict pkt, rpc_sess_t * __restrict sess, u_short tag, 
		array_t * __restrict vars, int noreply, int nocrc, int seq)
{
	struct tagRPCCall *rpc;
	int ret = 0, estlen, len = sizeof(struct tagRPCCall);
	u_char *buf;

	if (!pkt || !sess) {
		rpc_SetErr(EINVAL, "Invalid argument(s)!");
		return -1;
	}

	/* calc estimated length */
	estlen = ait_resideVars(vars) + len;
	if (estlen > AIT_LEN(pkt)) {
		rpc_SetErr(EMSGSIZE, "Message too long");
		return -1;
	}
	buf = AIT_GET_BUF(pkt);

	/* prepare RPC call */
	rpc = (struct tagRPCCall*) buf;
	rpc_addPktSession(&rpc->call_session, sess);
	rpc->call_tag = htons(tag);
	if (!vars)
		rpc->call_argc = 0;
	else
		rpc->call_argc = (u_char) array_Size(vars);

	/* set reply */
	rpc->call_req.flags = (uint64_t) htonl((noreply > 0) ? RPC_NOREPLY : RPC_REPLY);

	if (array_Size(vars)) {
		/* marshaling variables */
		ret = ait_vars2buffer(buf + len, AIT_LEN(pkt) - len, vars);
		if (ret == -1) {
			rpc_SetErr(EBADRPC, "Failed to prepare RPC packet values");
			return -1;
		} else
			len += ret;
	}

	/* total packet length */
	rpc->call_len = htonl(len);
	rpc->call_io = (noreply == -1) ? RPC_IPC : RPC_REQ;

	/* sign packet */
	rpc->call_seq = htonl(seq);

	if (!nocrc) {
		/* calculate CRC */
		rpc->call_crc ^= rpc->call_crc;
		rpc->call_crc = htons(crcFletcher16((u_short*) buf, len / 2));
	}

	return len;
}

/*
 * rpc_pkt_Replay() - Decode RPC Replay packet
 *
 * @pkt = Packet buffer
 * @sess = RPC session info, if =NULL don't check session
 * @tag = Function tag, if =CALL_TAG_MAX don't check tag
 * @vars = Function argument array of values, may be NULL
 * @nocrc = Without CRC calculation
 * return: -1 error or != -1 return value from function
 */
int
rpc_pkt_Replay(ait_val_t * __restrict pkt, rpc_sess_t * __restrict sess, u_short tag, 
		array_t ** __restrict vars, int nocrc)
{
	struct tagRPCCall *rpc;
	int len;
	u_char *buf;
	uint16_t crc;

	if (!pkt) {
		rpc_SetErr(EINVAL, "Invalid argument(s)!");
		return -1;
	} else
		buf = AIT_GET_BUF(pkt);

	rpc = (struct tagRPCCall*) buf;
	if (!nocrc) {
		/* calculate CRC */
		crc = ntohs(rpc->call_crc);
		rpc->call_crc ^= rpc->call_crc;
		if (crc != crcFletcher16((u_short*) buf, ntohl(rpc->call_len) / 2)) {
			rpc_SetErr(ERPCMISMATCH, "Bad CRC RPC packet");
			return -1;
		}
	}

	/* check RPC packet session info */
	if (sess && rpc_chkPktSession(&rpc->call_session, sess)) {
		rpc_SetErr(ERPCMISMATCH, "Get invalid RPC session");
		return -1;
	}
	if (tag != CALL_TAG_MAX && ntohs(rpc->call_tag) != tag) {
		rpc_SetErr(ERPCMISMATCH, "Get wrong RPC reply");
		return -1;
	}
	if (ntohl(rpc->call_rep.eno) && ntohl(rpc->call_rep.ret) == -1) {
		rpc_SetErr(ntohl(rpc->call_rep.eno), "Server side: retcode=%d #%d %s", 
				ntohl(rpc->call_rep.ret), ntohl(rpc->call_rep.eno), 
				strerror(ntohl(rpc->call_rep.eno)));
		return -1;
	}
	len = rpc->call_argc * sizeof(ait_val_t);
	if (len > AIT_LEN(pkt) - sizeof(struct tagRPCCall)) {
		rpc_SetErr(EMSGSIZE, "Reply RPC packet not enough buffer space ...");
		return -1;
	}
	if (len > ntohl(rpc->call_len) - sizeof(struct tagRPCCall)) {
		rpc_SetErr(EMSGSIZE, "Reply RPC packet is too short ...");
		return -1;
	}

	/* RPC is OK! Go de-marshaling variables ... */
	if (vars && rpc->call_argc) {
#ifdef CLI_RES_ZCOPY
		*vars = ait_buffer2vars(buf + sizeof(struct tagRPCCall), len, 
				rpc->call_argc, 42);
#else
		*vars = ait_buffer2vars(buf + sizeof(struct tagRPCCall), len, 
				rpc->call_argc, 0);
#endif
		if (!*vars) {
			rpc_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
			return -1;
		}
	}

	return ntohl(rpc->call_rep.ret);
}

/*
 * rpc_cli_execCall() - Execute RPC call
 *
 * @cli = RPC Client session
 * @noreply = >0 We not want RPC reply, -1 IPC request with reply
 * @tag = Function tag for execution
 * @in_vars = IN function argument array of values, may be NULL
 * @out_vars = OUT returned array of rpc values, if !=NULL must be free after use with ait_freeVars()
 * return: -1 error, 0 ok result or 1 closed rpc connection
 */
int
rpc_cli_execCall(rpc_cli_t *cli, int noreply, u_short tag, 
		array_t * __restrict in_vars, array_t ** __restrict out_vars)
{
	int type = 0, wlen;
	u_int seq = 0;

	if (!cli) {
		rpc_SetErr(EINVAL, "Can`t execute call because parameter is null or invalid!");
		return -1;
	} else {
		if (cli->cli_id == SOCK_STREAM || cli->cli_id == SOCK_EXT)
			type = cli->cli_id;
		else
			seq = random();	/* sign package */
	}
	if (out_vars)
		*out_vars = NULL;

	if ((wlen = rpc_pkt_Request(&cli->cli_buf, cli->cli_parent, tag, 
					in_vars, noreply, type, seq)) == -1)
		return -1;

	if ((wlen = rpc_pkt_Send(cli->cli_sock, cli->cli_id, &cli->cli_sa, 
					&cli->cli_buf, wlen)) == -1)
		return -1;
	if (!wlen)		/* closed rpc connection */
		return 1;

	if (noreply > 0)	/* we not want reply */
		return 0;

	if ((wlen = rpc_pkt_Receive(cli->cli_sock, cli->cli_id, &cli->cli_sa, 
					&cli->cli_buf, seq)) == -1)
		return -1;
	if (!wlen) {	/* closed rpc connection */
		rpc_SetErr(ECONNRESET, "Closed connection");
		return -1;
	}

	if ((wlen = rpc_pkt_Replay(&cli->cli_buf, cli->cli_parent, tag, 
					out_vars, type)) == -1)
		return -1;

	return wlen;
}

/*
 * rpc_cli_freeCall() - Free resouce allocated by RPC call
 *
 * @out_vars = Returned array with variables from RPC call
 * return: none
 */
void
rpc_cli_freeCall(array_t ** __restrict out_vars)
{
#ifdef CLI_RES_ZCOPY
	array_Destroy(out_vars);
#else
	ait_freeVars(out_vars);
#endif
}

/*
 * rpc_cli_ping() - Ping RPC server
 *
 * @cli = connected client
 * return: -1 error or !=-1 ping seq id
 */
int
rpc_cli_ping(rpc_cli_t *cli)
{
	int ret = 0;
	array_t *arr = NULL;

	if (!cli)
		return -1;

	if (rpc_cli_execCall(cli, RPC_REPLY, CALL_SRVPING, NULL, &arr))
		return -1;
	else
		ret = AIT_GET_U16(array(arr, 0, ait_val_t*));
	rpc_cli_freeCall(&arr);

	return ret;
}


/*
 * rpc_cli_openClient2() - Connect to layer2 RPC Server
 *
 * @InstID = InstID for RPC session request
 * @netBuf = Network buffer length (min:512 bytes), if =0 == BUFSIZ (also meaning max RPC packet)
 * @csIface = Interface name for bind client, if NULL first interface on host
 * @csHost = Host ethernet address
 * return: NULL == error or !=NULL connection to RPC server established
 */
rpc_cli_t *
rpc_cli_openClient2(u_char InstID, int netBuf, const char *csIface, const char *csHost)
{
#ifndef __linux__
	rpc_cli_t *cli = NULL;
	sockaddr_t sa = E_SOCKADDR_INIT, sal = E_SOCKADDR_INIT;
	char szIface[64], szStr[STRSIZ];
	register int i;
	struct ifreq ifr;
	int n = 1;
	struct bpf_insn insns[] = {
		BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 12),
		BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, RPC_DEFPORT, 0, 1),
		BPF_STMT(BPF_RET + BPF_K, -1),
		BPF_STMT(BPF_RET + BPF_K, 0),
	};
	struct bpf_program fcode = { 
		.bf_len = sizeof(insns) / sizeof(struct bpf_insn), 
       		.bf_insns = insns
	};

	if (!csHost || !e_getlinkbyname(csHost, &sa))
		return NULL;
	if (!csIface) {
		if (e_get1stiface(szIface, sizeof szIface))
			return NULL;
	} else
		strlcpy(szIface, csIface, sizeof szIface);
	if (!e_getifacebyname(szIface, &sal))
		return NULL;

	cli = e_malloc(sizeof(rpc_cli_t));
	if (!cli) {
		LOGERR;
		return NULL;
	} else
		memset(cli, 0, sizeof(rpc_cli_t));

	/* build session */
	cli->cli_parent = e_malloc(sizeof(rpc_sess_t));
	if (!cli->cli_parent) {
		LOGERR;
		e_free(cli);
		return NULL;
	} else {
		((rpc_sess_t*) cli->cli_parent)->sess_version = RPC_VERSION;
		((rpc_sess_t*) cli->cli_parent)->sess_instance = InstID;
	}

	cli->cli_id = SOCK_BPF;
	memcpy(&cli->cli_sa, &sa, sizeof cli->cli_sa);

	/* connect to RPC server */
	for (i = 0; i < 10; i++) {
		memset(szStr, 0, sizeof szStr);
		snprintf(szStr, sizeof szStr, "/dev/bpf%d", i);
		cli->cli_sock = open(szStr, O_RDWR);
		if (cli->cli_sock > STDERR_FILENO)
			break;
	}
	if (cli->cli_sock < 3) {
		LOGERR;
		e_free(cli->cli_parent);
		e_free(cli);
		return NULL;
	}

	if (ioctl(cli->cli_sock, BIOCIMMEDIATE, &n) == -1) {
		LOGERR;
		goto err;
	}
	if (ioctl(cli->cli_sock, BIOCSETF, &fcode) == -1) {
		LOGERR;
		goto err;
	}
	n = (netBuf < RPC_MIN_BUFSIZ) ? getpagesize() : E_ALIGN(netBuf, 2);
	if (ioctl(cli->cli_sock, BIOCSBLEN, &n) == -1) {
		LOGERR;
		goto err;
	} else
		AIT_SET_BUFSIZ(&cli->cli_buf, 0, n);

	memset(&ifr, 0, sizeof ifr);
	strlcpy(ifr.ifr_name, szIface, sizeof ifr.ifr_name);
	if (ioctl(cli->cli_sock, BIOCSETIF, &ifr) == -1) {
		LOGERR;
		goto err;
	} else
		fcntl(cli->cli_sock, F_SETFL, 
				fcntl(cli->cli_sock, F_GETFL) | O_NONBLOCK);

	return cli;
err:
	AIT_FREE_VAL(&cli->cli_buf);
	if (cli->cli_sock > 2)
		close(cli->cli_sock);
	e_free(cli->cli_parent);
	e_free(cli);
#else
	rpc_SetErr(ENOTSUP, "Feature isn't supported on Linux!");
#endif
	return NULL;
}

/*
 * rpc_cli_closeClient2() - Close layer2 connection to RPC server and free resources
 *
 * @cli = RPC Client session
 * return: none
 */
void
rpc_cli_closeClient2(rpc_cli_t ** __restrict cli)
{
	if (!cli || !*cli || (*cli)->cli_id != SOCK_BPF)
		return;

	close((*cli)->cli_sock);

	AIT_FREE_VAL(&(*cli)->cli_buf);

	if ((*cli)->cli_parent)
		e_free((*cli)->cli_parent);

	e_free(*cli);
	*cli = NULL;
}

/*
 * rpc_cli_openClientExt() - Connect to pipe RPC Server
 *
 * @InstID = InstID for RPC session request
 * @netBuf = Network buffer length (min:512 bytes), if =0 == BUFSIZ (also meaning max RPC packet)
 * @fd = File descriptor
 * return: NULL == error or !=NULL connection to RPC server established
 */
rpc_cli_t *
rpc_cli_openClientExt(u_char InstID, int netBuf, int fd)
{
	rpc_cli_t *cli = NULL;
	int n;

	cli = e_malloc(sizeof(rpc_cli_t));
	if (!cli) {
		LOGERR;
		return NULL;
	} else
		memset(cli, 0, sizeof(rpc_cli_t));

	/* build session */
	cli->cli_parent = e_malloc(sizeof(rpc_sess_t));
	if (!cli->cli_parent) {
		LOGERR;
		e_free(cli);
		return NULL;
	} else {
		((rpc_sess_t*) cli->cli_parent)->sess_version = RPC_VERSION;
		((rpc_sess_t*) cli->cli_parent)->sess_instance = InstID;
	}

	cli->cli_id = SOCK_EXT;
	cli->cli_sock = fd;

	n = (netBuf < RPC_MIN_BUFSIZ) ? getpagesize() : E_ALIGN(netBuf, 2);
	AIT_SET_BUFSIZ(&cli->cli_buf, 0, n);

	fcntl(cli->cli_sock, F_SETFL, 
			fcntl(cli->cli_sock, F_GETFL) | O_NONBLOCK);

	return cli;
}

/*
 * rpc_cli_closeClientExt() - Close pipe connection to RPC server and free resources
 *
 * @cli = RPC Client session
 * return: none
 */
void
rpc_cli_closeClientExt(rpc_cli_t ** __restrict cli)
{
	if (!cli || !*cli || (*cli)->cli_id != SOCK_EXT)
		return;

	AIT_FREE_VAL(&(*cli)->cli_buf);

	if ((*cli)->cli_parent)
		e_free((*cli)->cli_parent);

	e_free(*cli);
	*cli = NULL;
}

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>