summaryrefslogtreecommitdiff
path: root/piper_webext.c
diff options
context:
space:
mode:
authormiguel <miguel@localhost>2018-03-15 23:36:59 +0100
committermiguel <miguel@localhost>2018-03-15 23:36:59 +0100
commit54e06e03aad71888b3b05a1c249b170f3856da69 (patch)
tree808bd355f2421704e490edd6ad1c3a1e67b33d77 /piper_webext.c
parent7019970b24380cd823beb9760f34a6c00b569054 (diff)
v0.2
Diffstat (limited to 'piper_webext.c')
-rw-r--r--piper_webext.c73
1 files changed, 73 insertions, 0 deletions
diff --git a/piper_webext.c b/piper_webext.c
new file mode 100644
index 0000000..172039e
--- /dev/null
+++ b/piper_webext.c
@@ -0,0 +1,73 @@
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <glib.h>
+#include <stdbool.h>
+#include <errno.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+#include "piper_webext.h"
+
+static int pipe_out_fd;
+static void (*pipe_in_callback)(char *msg);
+
+// returns full path to pipe in users runtime dir.
+// dont forge't to g_free after use
+static gchar* getpath(char *path)
+{
+ return g_strdup_printf("%s/piper-%s",g_get_user_runtime_dir(),path);
+}
+
+// callback function wrapper for received messages
+static gboolean mycallback(GIOChannel *ch, GIOCondition c, gpointer p)
+{
+ gchar *line;
+ g_io_channel_read_line(ch, &line, NULL, NULL, NULL);
+ g_strchomp(line);
+ pipe_in_callback(line);
+ g_free(line);
+ return true;
+}
+
+static void register_callback(char *path)
+{
+ gchar *fullpath=getpath(path);
+ mkfifo(fullpath,0600);
+ GMainContext *ctx = g_main_context_default();
+ GIOChannel *io = g_io_channel_new_file(fullpath, "r+", NULL);
+ GSource *watch = g_io_create_watch(io, G_IO_IN);
+ g_source_attach(watch,ctx);
+ g_source_set_callback(watch,(GSourceFunc)mycallback,NULL,NULL);
+ g_free(fullpath);
+}
+
+// open for writing, lock and return pipe fd
+static int piper_lock(char *path)
+{
+ gchar *fullpath=getpath(path);
+ mkfifo(fullpath,0600);
+ int pipe=open(fullpath, O_RDWR | O_CREAT | O_TRUNC);
+ g_free(fullpath);
+ if(pipe == -1) return -1;
+ int lock=lockf(pipe,F_TLOCK,0);
+ if(lock == -1) return -1;
+ return pipe;
+}
+
+void piper_init(char *path_in,char *path_out,void (*callback_func)(char *msg))
+{
+ pipe_in_callback=callback_func;
+ pipe_out_fd=piper_lock(path_out);
+ if(pipe_out_fd==-1)
+ {
+ g_print("can not get exclusive lock! Bailing out.\n");
+ exit(0);
+ }
+ register_callback(path_in);
+}
+
+void piper_send(char *msg)
+{
+ int ret=write(pipe_out_fd,msg,strlen(msg));
+ if(ret==-1)g_print("Can not write to pipe :(\n");
+}