Use GSocket and GSocketAddress from GIO.
[cascardo/f2fchat.git] / message.c
1 /*
2  *  Copyright (C) 2013  Thadeu Lima de Souza Cascardo <cascardo@cascardo.info>
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 3 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 #include "message.h"
20 #include "friend.h"
21 #include <glib.h>
22 #include <gio/gio.h>
23
24 #include <stdio.h>
25
26 gboolean ping_timeout(gpointer data)
27 {
28         struct friend *friend = data;
29         return G_SOURCE_REMOVE;
30 }
31
32 static GIOChannel *uchannel;
33 static GSocket *gusock;
34
35 static void command(char *buffer, size_t len)
36 {
37         printf("message from loopback: %d %.*s\n", len, len, buffer);
38 }
39
40 gboolean message_incoming(GIOChannel *channel, GIOCondition cond, gpointer data)
41 {
42         size_t len;
43         char *buffer;
44         GSocketAddress *address;
45         GInetAddress *iaddress;
46         if (!gusock) {
47                 gusock = g_socket_new_from_fd(g_io_channel_unix_get_fd(channel), NULL);
48         }
49         len = g_socket_get_available_bytes(gusock);
50         buffer = g_malloc(len);
51         len = g_socket_receive_from(gusock, &address, buffer, len, NULL, NULL);
52         iaddress = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(address));
53         if (g_inet_address_get_is_loopback(iaddress)) {
54                 command(buffer, len);
55         }
56         g_object_unref(address);
57         g_free(buffer);
58         return TRUE;
59 }
60
61 int message_init(GSocket *sock)
62 {
63         uchannel = g_io_channel_unix_new(g_socket_get_fd(sock));
64         g_io_add_watch(uchannel, G_IO_IN, message_incoming, NULL);
65         return 0;
66 }
67
68 int ping(struct friend *friend)
69 {
70         char ping[5] = "PING";
71         friend_send_message(friend, ping, 4);
72         g_timeout_add(2000, ping_timeout, friend);
73 }