
/*
 * $Id: io.c,v 1.2 1999/05/08 14:21:47 csmall Exp $
 * Turtle -- Part of the GXSNMP snmp management application
 * Copyright (C) 1999 Craig Small <csmall@small.dropbear.id.au>
 *  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.,  59 Temple Place - Suite 330, Cambridge, MA 02139, USA.
 *
 * Communications for turtle back to main system.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <glib.h>
#include <io.h>

/* The callback when we get something on the socket */
gboolean
turtleio_cb(GIOChannel *source, GIOCondition condition, gpointer data)
{
    int newskt;
    struct sockaddr_in cli_addr;
    int clilen;
    int skt = (int)data;
    char *string = "Hello world, this is the turtle talking!!\n";

	g_print("We got some input!! %d\n", condition);


        if (condition == G_IO_IN)
        {
            if ((newskt = accept(skt, (struct sockaddr*)&cli_addr, &clilen)) < 0)
            {
                g_warning("turtleio_cb() Unable to accept new connection\n");
                return TRUE;
            }
            write(newskt, string, strlen(string));
            close(newskt);
        }

	return TRUE;
}

/* This function needs to be called first */
int
turtleio_init()
{
    struct sockaddr_in serv_addr;
    GIOChannel *channel;
    GIOCondition cond;
    int skt;
    int result;

    if ( (skt = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        g_error("turtleio_init() Unable to create io socket");
        return -1;
    }

    bzero((char*)&serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(TURTLEIO_PORT);

    if (bind(skt, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
    {
        g_error("turtleio_init() Unable to bind io socket");
        return -1;
    }

    listen(skt, 5);

    cond = (G_IO_IN | G_IO_PRI); /* GDK_INPUT_READ */
    channel = g_io_channel_unix_new(skt);
    result = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT, cond,
            turtleio_cb, skt, NULL);
    g_io_channel_unref(channel);

    return skt;
}

     



