unix_client.c
author viric@mandarina
Mon, 28 Apr 2008 21:37:16 +0200
changeset 89 2692e4742267
parent 76 5c0b9c9f9801
permissions -rw-r--r--
Moving the utils from stdinmix to tm.

/*
    Terminal Mixer - multi-point multi-user access to terminal applications
    Copyright (C) 2007  LluĂ­s Batlle i Rossell

    Please find the license in the provided COPYING file.
*/
#include <sys/un.h>
#include <sys/socket.h>
#include <unistd.h>
#include <assert.h>

#include "main.h"
#include "handlers.h"
#include "filter.h"

static int conn_socket = -1;

extern struct FilterRules *client_recv_fr;

void c_unix_connect_socket()
{
    struct sockaddr_un addr;
    int res;

    assert(command_line.unix_path != 0);
    assert(conn_socket == -1);

    conn_socket = socket(AF_UNIX, SOCK_STREAM, 0);
    if (conn_socket == -1)
        error("Cannot create the unix connect socket in the client");

    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, command_line.unix_path, sizeof(addr.sun_path));

    res = connect(conn_socket, (struct sockaddr *) &addr, sizeof(addr));
    if (res == -1)
        error("Cannot connect to %s", command_line.unix_path);
}

void c_unix_prepare_read_fdset(fd_set *read_set, int *maxfd)
{
    FD_SET(conn_socket, read_set); /* For reading other side's close() */
    *maxfd = max(*maxfd, conn_socket);
}

/* Send -1 on eof */
int c_unix_process_read_fdset(fd_set *read_set)
{
    int res;
    if (FD_ISSET(conn_socket, read_set))
    {
        int olen;
        res = read(conn_socket, stream_buffer, stream_buffer_size);
        if (res == 0) /* EOF */
        {
            filter_flush(client_recv_fr, ostream_buffer, &olen);
            if (olen > 0)
                send_to_client_stdout(ostream_buffer, olen);
            return -1;
        }
        hex_dump("recv_unix_client",stream_buffer, res);

        filter_stream(client_recv_fr, ostream_buffer, &olen, stream_buffer,
                res);
        if (olen > 0)
            send_to_client_stdout(ostream_buffer, olen);
    }
    return 0;
}

void c_unix_send(const char *buf, size_t len)
{
    hex_dump("send_unix_client",buf, len);
    write(conn_socket, buf, len);
}