setup project. initial import of uzbl
[uzbl-mobile] / uzblctrl.c
1 /* -*- c-basic-offset: 4; -*- */
2 /* Socket code more or less completely copied from here: http://www.ecst.csuchico.edu/~beej/guide/ipc/usock.html */
3
4 #include <gtk/gtk.h>
5 #include <stdio.h>
6 #include <unistd.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/types.h>
10 #include <sys/socket.h>
11 #include <sys/un.h>
12
13 static gchar* sockpath;
14 static gchar* command;
15
16 static GOptionEntry entries[] =
17 {
18     { "socket",  's', 0, G_OPTION_ARG_STRING, &sockpath, "Path to the uzbl socket",        NULL },
19     { "command", 'c', 0, G_OPTION_ARG_STRING, &command,  "The uzbl command to execute",    NULL },
20     { NULL,       0,  0, 0,                    NULL,      NULL,                            NULL }
21 };
22
23 int
24 main(int argc, char* argv[]) {
25     GError *error = NULL;
26     GOptionContext* context = g_option_context_new ("- utility for controlling and interacting with uzbl through its socket file"); /* TODO: get stuff back from uzbl */
27     g_option_context_add_main_entries (context, entries, NULL);
28     g_option_context_add_group        (context, gtk_get_option_group (TRUE));
29     g_option_context_parse            (context, &argc, &argv, &error);
30
31
32     if (sockpath && command) {
33         int s, len;
34         struct sockaddr_un remote;
35         char tmp;
36
37         if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) == -1) {
38             perror ("socket");
39             exit (EXIT_FAILURE);
40         }
41
42         remote.sun_family = AF_UNIX;
43         strcpy (remote.sun_path, (char *) sockpath);
44         len = strlen (remote.sun_path) + sizeof (remote.sun_family);
45
46         if (connect (s, (struct sockaddr *) &remote, len) == -1) {
47             perror ("connect");
48             exit (EXIT_FAILURE);
49         }
50
51         if ((send (s, command, strlen (command), 0) == -1) ||
52             (send (s, "\n", 1, 0) == -1)) {
53             perror ("send");
54             exit (EXIT_FAILURE);
55         }
56
57         while ((len = recv (s, &tmp, 1, 0))) {
58             putchar(tmp);
59             if (tmp == '\n')
60                 break;
61         }
62
63         close(s);
64
65         return 0;
66     } else {
67         fprintf(stderr, "Usage: uzblctrl -s /path/to/socket -c \"command\"");
68         return 1;
69     }
70 }
71 /* vi: set et ts=4: */