a380a7c7cbd19e65009750ea93431426513b2eea
[cascardo/rnetproxy.git] / iochannel.c
1 /*
2  *  Copyright (C) 2009  Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com>
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 2 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License along
15  *  with this program; if not, write to the Free Software Foundation, Inc.,
16  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19
20 #include "iochannel.h"
21
22 struct hc_server_cb
23 {
24   GIOChannel *channel;
25   HCServerFunc func;
26   gpointer data;
27 };
28
29 static void
30 hc_server_cb_destroy (gpointer cb)
31 {
32   g_slice_free (struct hc_server_cb, cb);
33 }
34
35 static gboolean
36 hc_server_watch (GIOChannel *channel, GIOCondition cond, gpointer data)
37 {
38   struct hc_server_cb *cb = data;
39   int fd = g_io_channel_unix_get_fd (channel);
40   struct sockaddr addr;
41   socklen_t saddr = sizeof (addr);
42   int client = accept (fd, &addr, &saddr);
43   if (client >= 0 && cb->func)
44     cb->func (client, &addr, saddr, cb->data);
45   return TRUE;
46 }
47
48 void
49 hc_server_add_watch (int fd,
50                      HCServerFunc func,
51                      gpointer data)
52 {
53   struct hc_server_cb *cb;
54   cb = g_slice_new (struct hc_server_cb);
55   cb->channel = g_io_channel_unix_new (fd);
56   cb->func = func;
57   cb->data = data;
58   g_io_add_watch_full (cb->channel, G_PRIORITY_DEFAULT, G_IO_IN,
59                        hc_server_watch, cb, hc_server_cb_destroy);
60 }