/* 
   authentication client for podfuk-smb

   Copyright (C) Tim Potter 2000
   
   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.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <string.h>
#include <sys/time.h>
#include <sys/uio.h>

#include "podfuk-smb-auth.h"

/* Connect to podfuk-smb-auth socket */

static int open_pipe_sock(void)
{
	struct sockaddr_un sunaddr;
	struct stat st;
	pstring path;
	int sock;
	
	/* Check permissions on unix socket directory */
	
	if (lstat(PODFUK_SOCKET_DIR, &st) == -1) {
		return -1;
	}
	
	if (!S_ISDIR(st.st_mode) || (st.st_uid != 0)) {
		return -1;
	}
	
	/* Connect to socket */
	
	strncpy(path, PODFUK_SOCKET_DIR, sizeof(path) - 1);
	path[sizeof(path) - 1] = '\0';
	
	strncat(path, "/", sizeof(path) - 1);
	path[sizeof(path) - 1] = '\0';
	
	strncat(path, PODFUK_SOCKET_NAME, sizeof(path) - 1);
	path[sizeof(path) - 1] = '\0';
	
	ZERO_STRUCT(sunaddr);
	sunaddr.sun_family = AF_UNIX;
	strncpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path) - 1);
	
	/* If socket file doesn't exist, don't bother trying to connect
	   with retry.  This is an attempt to make the system usable when
	   the podfuk-smb auth daemon is not running. */

	if (lstat(path, &st) == -1) {
		return -1;
	}
	
	/* Check permissions on unix socket file */
	
	if (!S_ISSOCK(st.st_mode) || (st.st_uid != 0)) {
		return -1;
	}
	
	/* Connect to socket */
	
	if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
		return -1;
	}
	
	if (connect(sock, (struct sockaddr *)&sunaddr, 
		    sizeof(sunaddr)) == -1) {
		close(sock);
		return -1;
	}
        
	return sock;
}

/* Write data to podfuk socket */

static int write_sock(int sock, void *buffer, int count)
{
	int result, nwritten;
	
	/* Write data to socket */
	
	nwritten = 0;
	
	while(nwritten < count) {
		struct timeval tv;
		fd_set r_fds;
		int selret;
		
		/* Catch pipe close on other end by checking if a read()
		   call would not block by calling select(). */

		FD_ZERO(&r_fds);
		FD_SET(sock, &r_fds);
		ZERO_STRUCT(tv);
		
		if ((selret = select(sock + 1, &r_fds, NULL, NULL, 
				     &tv)) == -1) {
			close(sock);
			return -1;                   /* Select error */
		}
		
		/* Write should be OK if fd not available for reading */
		
		if (!FD_ISSET(sock, &r_fds)) {
			
			/* Do the write */
			
			result = write(sock, (char *)buffer + nwritten, 
				       count - nwritten);
			
			if ((result == -1) || (result == 0)) {
				
				/* Write failed */
				
				close(sock);
				return -1;
			}
			
			nwritten += result;
			
		} else {
			
			/* Pipe has closed on remote end */
			
			close(sock);
			return -1;
		}
	}
	
	return nwritten;
}

/* Read data from podfuk-smb-authd socket with timeout */

static int read_sock(int sock, void *buffer, int count)
{
	int result = 0, nread = 0;

	/* Read data from socket */
	
	while(nread < count) {
		
		result = read(sock, (char *)buffer + nread, count - nread);
		
		if ((result == -1) || (result == 0)) {
			
			/* Read failed.  I think the only useful thing we
			   can do here is just return -1 and fail since the
			   transaction has failed half way through. */
			
			close(sock);
			return -1;
		}
		
		nread += result;
	}
	
	return result;
}

/* Send our credentials down the pipe.  We can't get away with anything naughty
   as the kernel checks the values we pass. */

struct cmessage {
  struct cmsghdr cmsg;
  struct ucred cmcred;
};

static int write_creds(int sock)
{
	struct iovec iov[1];
	struct msghdr msg;
	struct cmessage cm;
	char c = 69;

	/* Must write at least one byte */

	iov[0].iov_base = &c;
	iov[0].iov_len = 1;

	cm.cmsg.cmsg_type = SCM_CREDENTIALS;
	cm.cmsg.cmsg_level = SOL_SOCKET;
	cm.cmsg.cmsg_len = sizeof(struct cmessage);

	cm.cmcred.pid = getpid();
	cm.cmcred.uid = geteuid();
	cm.cmcred.gid = getegid();

	msg.msg_iov = iov;
	msg.msg_iovlen = 1;
	msg.msg_name = NULL;
	msg.msg_namelen = 0;
	msg.msg_control = &cm;
	msg.msg_controllen = sizeof(struct cmessage);
	msg.msg_flags = 0;

	return sendmsg(sock, &msg, 0);
}

/* Process an authorisation request */

static enum auth_result auth_request(struct cli_request *request,
				     struct cli_response *response)
{
	struct cli_response lresponse;
	enum auth_result result = AUTH_CMD_FAILED;
	int sock;

	if (!response) response = &lresponse;

	ZERO_STRUCTP(response);

	request->pid = getpid();

	if ((sock = open_pipe_sock()) == -1) {
		goto done;
	}

	/* Send credentials */

	if (write_creds(sock) == -1) {
		goto done;
	}

	/* Send request */

	if (write_sock(sock, request, sizeof(*request)) == -1) {
		goto done;
	}

	/* Wait for reply */

	if (read_sock(sock, response, sizeof(*response)) == -1) {
		goto done;
	}

	/* Read any extra data */

	if (response->extra_data_len > 0) {
		response->extra_data = malloc(response->extra_data_len);

		if (!response->extra_data ||
		    read_sock(sock, response->extra_data, 
			      response->extra_data_len) == -1) {
			goto done;
		}
	}

	result = response->result;

    done:
	if (sock != -1) close(sock);

	return result;	
}

/* Call podfuk-smb-authd to add a token */

int add_token(char *sharename, char *username, char *workgroup, 
	      char *password)
{
	struct cli_request request;

	request.command = AUTH_ADD_TOKEN;

	strcpy(request.data.add_token.sharename, sharename);
	strcpy(request.data.add_token.username, username);
	strcpy(request.data.add_token.workgroup, workgroup);
	strcpy(request.data.add_token.password, password);

	return auth_request(&request, NULL) == AUTH_CMD_OK;
}

/* Call podfuk-smb-authd to remove a token */

int remove_token(char *sharename)
{
	struct cli_request request;

	request.command = AUTH_REMOVE_TOKEN;

	strcpy(request.data.clear_token.sharename, sharename);

	return auth_request(&request, NULL) == AUTH_CMD_OK;
}

/* Call podfuk-smb-authd to clear user tokens */

int clear_tokens(int clear_all)
{
	struct cli_request request;

	request.command = clear_all ? AUTH_CLEAR_ALL_TOKENS : 
		AUTH_CLEAR_TOKENS;

	return auth_request(&request, NULL) == AUTH_CMD_OK;
}

/* Call podfuk-smb-authd to list tokens */

int list_tokens(int list_all, struct auth_token **tokens, int *num_tokens)
{
	struct cli_request request;
	struct cli_response response;
	enum auth_result result;

	request.command = list_all ? AUTH_LIST_ALL_TOKENS : AUTH_LIST_TOKENS;

	result = auth_request(&request, &response);

	*tokens = NULL;
	*num_tokens = 0;

	if (result == AUTH_CMD_OK) {
		*tokens = (struct auth_token *)response.extra_data;
		*num_tokens = response.extra_data_len / 
			sizeof(struct auth_token);
	}
		
	return result == AUTH_CMD_OK;
}

/* Fetch a token given the uid, servername and sharename, or just the
   uid and sharename, or failing that just the uid (default user). */

int fetch_token(uid_t uid, char *servername, char *sharename, 
		struct auth_token *token)
{
	struct cli_request request;
	struct cli_response response;
	enum auth_result result;

	ZERO_STRUCT(request);

	request.command = AUTH_FETCH_TOKEN;
	request.data.fetch_token.uid = uid;

	if (servername) {
		strcpy(request.data.fetch_token.servername, servername);
	}

	if (sharename) {
		strcpy(request.data.fetch_token.sharename, sharename);
	}

	result = auth_request(&request, &response);

	if (result == AUTH_CMD_OK) {
		struct auth_token *ret = (struct auth_token *)
			response.extra_data;

		token->uid = ret->uid;
		strcpy(token->sharename, ret->sharename);
		strcpy(token->workgroup, ret->workgroup);
		strcpy(token->username, ret->username);
		strcpy(token->password, ret->password);

		free(response.extra_data);
	}

	return result == AUTH_CMD_OK;
}
