Add socket and message.
[cascardo/f2fchat.git] / message.c
diff --git a/message.c b/message.c
new file mode 100644 (file)
index 0000000..7c73006
--- /dev/null
+++ b/message.c
@@ -0,0 +1,73 @@
+/*
+ *  Copyright (C) 2013  Thadeu Lima de Souza Cascardo <cascardo@cascardo.info>
+ *
+ *  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 3 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.,
+ *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include "message.h"
+#include "friend.h"
+#include <glib.h>
+#include <gio/gio.h>
+
+#include <stdio.h>
+
+gboolean ping_timeout(gpointer data)
+{
+       struct friend *friend = data;
+       return G_SOURCE_REMOVE;
+}
+
+static GIOChannel *uchannel;
+static GSocket *gusock;
+
+static void command(char *buffer, size_t len)
+{
+       printf("message from loopback: %d %.*s\n", len, len, buffer);
+}
+
+gboolean message_incoming(GIOChannel *channel, GIOCondition cond, gpointer data)
+{
+       size_t len;
+       char *buffer;
+       GSocketAddress *address;
+       GInetAddress *iaddress;
+       if (!gusock) {
+               gusock = g_socket_new_from_fd(g_io_channel_unix_get_fd(channel), NULL);
+       }
+       len = g_socket_get_available_bytes(gusock);
+       buffer = g_malloc(len);
+       len = g_socket_receive_from(gusock, &address, buffer, len, NULL, NULL);
+       iaddress = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(address));
+       if (g_inet_address_get_is_loopback(iaddress)) {
+               command(buffer, len);
+       }
+       g_object_unref(address);
+       g_free(buffer);
+       return TRUE;
+}
+
+int message_init(int sock)
+{
+       uchannel = g_io_channel_unix_new(sock);
+       g_io_add_watch(uchannel, G_IO_IN, message_incoming, NULL);
+       return 0;
+}
+
+int ping(struct friend *friend)
+{
+       char ping[5] = "PING";
+       friend_send_message(friend, ping, 4);
+       g_timeout_add(2000, ping_timeout, friend);
+}