Improve API docs for editor_insert_text_block().
[geany-mirror.git] / src / socket.c
blobe7080506453f83fecfe3fa91b313164486e8b915
1 /*
2 * socket.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2006-2010 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2010 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
6 * Copyright 2006 Hiroyuki Yamamoto (author of Sylpheed)
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * $Id$
26 * Socket setup and messages handling.
27 * The socket allows detection and messages to be sent to the first running instance of Geany.
28 * Only the first instance loads session files at startup, and opens files from the command-line.
32 * Little dev doc:
33 * Each command which is sent between two instances (see send_open_command and
34 * socket_lock_input_cb) should have the following scheme:
35 * command name\n
36 * data\n
37 * data\n
38 * ...
39 * .\n
40 * The first thing should be the command name followed by the data belonging to the command and
41 * to mark the end of data send a single '.'. Each message should be ended with \n.
42 * The command window is only available on Windows and takes no additional data, instead it
43 * writes back a Windows handle (HWND) for the main window to set it to the foreground (focus).
45 * At the moment the commands window, open, line and column are available.
47 * About the socket files on Unix-like systems:
48 * Geany creates a socket in /tmp (or any other directory returned by g_get_tmp_dir()) and
49 * a symlink in the current configuration to the created socket file. The symlink is named
50 * geany_socket_<hostname>_<displayname> (displayname is the name of the active X display).
51 * If the socket file cannot be created in the temporary directory, Geany creates the socket file
52 * directly in the configuration directory as a fallback.
57 #include "geany.h"
59 #ifdef HAVE_SOCKET
61 #ifndef G_OS_WIN32
62 # include <string.h>
63 # include <sys/time.h>
64 # include <sys/types.h>
65 # include <sys/socket.h>
66 # include <sys/un.h>
67 # include <netinet/in.h>
68 # include <glib/gstdio.h>
69 #else
70 # include <gdk/gdkwin32.h>
71 # include <windows.h>
72 # include <winsock2.h>
73 # include <ws2tcpip.h>
74 #endif
75 #include <stdlib.h>
76 #include <unistd.h>
77 #include <fcntl.h>
79 #ifdef GDK_WINDOWING_X11
80 #include <gdk/gdkx.h>
81 #endif
83 #include "main.h"
84 #include "socket.h"
85 #include "document.h"
86 #include "support.h"
87 #include "ui_utils.h"
88 #include "utils.h"
89 #include "encodings.h"
93 #ifdef G_OS_WIN32
94 #define REMOTE_CMD_PORT 49876
95 #define SOCKET_IS_VALID(s) (G_LIKELY((s) != INVALID_SOCKET))
96 #else
97 #define SOCKET_IS_VALID(s) (G_LIKELY((s) >= 0))
98 #define INVALID_SOCKET (-1)
99 #endif
102 struct socket_info_struct socket_info;
105 #ifdef G_OS_WIN32
106 static gint socket_fd_connect_inet (gushort port);
107 static gint socket_fd_open_inet (gushort port);
108 static void socket_init_win32 (void);
109 #else
110 static gint socket_fd_connect_unix (const gchar *path);
111 static gint socket_fd_open_unix (const gchar *path);
112 #endif
114 static gint socket_fd_write (gint sock, const gchar *buf, gint len);
115 static gint socket_fd_write_all (gint sock, const gchar *buf, gint len);
116 static gint socket_fd_gets (gint sock, gchar *buf, gint len);
117 static gint socket_fd_check_io (gint fd, GIOCondition cond);
118 static gint socket_fd_read (gint sock, gchar *buf, gint len);
119 static gint socket_fd_recv (gint fd, gchar *buf, gint len, gint flags);
120 static gint socket_fd_close (gint sock);
124 void send_open_command(gint sock, gint argc, gchar **argv)
126 gint i;
127 gchar *filename;
129 g_return_if_fail(argc > 1);
130 geany_debug("using running instance of Geany");
132 if (cl_options.goto_line >= 0)
134 gchar *line = g_strdup_printf("%d\n", cl_options.goto_line);
135 socket_fd_write_all(sock, "line\n", 5);
136 socket_fd_write_all(sock, line, strlen(line));
137 socket_fd_write_all(sock, ".\n", 2);
138 g_free(line);
141 if (cl_options.goto_column >= 0)
143 gchar *col = g_strdup_printf("%d\n", cl_options.goto_column);
144 socket_fd_write_all(sock, "column\n", 7);
145 socket_fd_write_all(sock, col, strlen(col));
146 socket_fd_write_all(sock, ".\n", 2);
147 g_free(col);
150 socket_fd_write_all(sock, "open\n", 5);
152 for (i = 1; i < argc && argv[i] != NULL; i++)
154 filename = main_get_argv_filename(argv[i]);
156 /* if the filename is valid or if a new file should be opened is check on the other side */
157 if (filename != NULL)
159 socket_fd_write_all(sock, filename, strlen(filename));
160 socket_fd_write_all(sock, "\n", 1);
162 else
164 g_printerr(_("Could not find file '%s'."), filename);
165 g_printerr("\n"); /* keep translation from open_cl_files() in main.c. */
167 g_free(filename);
169 socket_fd_write_all(sock, ".\n", 2);
173 #ifndef G_OS_WIN32
174 static void remove_socket_link_full(void)
176 gchar real_path[512];
177 gsize len;
179 real_path[0] = '\0';
181 /* read the contents of the symbolic link socket_info.file_name and delete it
182 * readlink should return something like "/tmp/geany_socket.499602d2" */
183 len = readlink(socket_info.file_name, real_path, sizeof(real_path) - 1);
184 if ((gint) len > 0)
186 real_path[len] = '\0';
187 g_unlink(real_path);
189 g_unlink(socket_info.file_name);
191 #endif
194 /* (Unix domain) socket support to replace the old FIFO code
195 * (taken from Sylpheed, thanks)
196 * Returns the created socket, -1 if an error occurred or -2 if another socket exists and files
197 * were sent to it. */
198 gint socket_init(gint argc, gchar **argv)
200 gint sock;
201 #ifdef G_OS_WIN32
202 HANDLE hmutex;
203 HWND hwnd;
204 socket_init_win32();
205 hmutex = CreateMutexA(NULL, FALSE, "Geany");
206 if (! hmutex)
208 geany_debug("cannot create Mutex\n");
209 return -1;
211 if (GetLastError() != ERROR_ALREADY_EXISTS)
213 /* To support multiple instances with different configuration directories (as we do on
214 * non-Windows systems) we would need to use different port number s but it might be
215 * difficult to get a port number which is unique for a configuration directory (path)
216 * and which is unused. This port number has to be guessed by the first and new instance
217 * and the only data is the configuration directory path.
218 * For now we use one port number, that is we support only one instance at all. */
219 sock = socket_fd_open_inet(REMOTE_CMD_PORT);
220 if (sock < 0)
221 return 0;
222 return sock;
225 sock = socket_fd_connect_inet(REMOTE_CMD_PORT);
226 if (sock < 0)
227 return -1;
228 #else
229 gchar *display_name = gdk_get_display();
230 gchar *hostname = utils_get_hostname();
231 gchar *p;
233 if (display_name == NULL)
234 display_name = g_strdup("NODISPLAY");
236 /* these lines are taken from dcopc.c in kdelibs */
237 if ((p = strrchr(display_name, '.')) > strrchr(display_name, ':') && p != NULL)
238 *p = '\0';
239 while ((p = strchr(display_name, ':')) != NULL)
240 *p = '_';
242 if (socket_info.file_name == NULL)
243 socket_info.file_name = g_strdup_printf("%s%cgeany_socket_%s_%s",
244 app->configdir, G_DIR_SEPARATOR, hostname, display_name);
246 g_free(display_name);
247 g_free(hostname);
249 sock = socket_fd_connect_unix(socket_info.file_name);
250 if (sock < 0)
252 remove_socket_link_full(); /* deletes the socket file and the symlink */
253 return socket_fd_open_unix(socket_info.file_name);
255 #endif
257 /* remote command mode, here we have another running instance and want to use it */
259 #ifdef G_OS_WIN32
260 /* first we send a request to retrieve the window handle and focus the window */
261 socket_fd_write_all(sock, "window\n", 7);
262 if (socket_fd_read(sock, (gchar *)&hwnd, sizeof(hwnd)) == sizeof(hwnd))
263 SetForegroundWindow(hwnd);
264 #endif
265 /* now we send the command line args */
266 if (argc > 1)
268 send_open_command(sock, argc, argv);
271 socket_fd_close(sock);
272 return -2;
276 gint socket_finalize(void)
278 if (socket_info.lock_socket < 0)
279 return -1;
281 if (socket_info.lock_socket_tag > 0)
282 g_source_remove(socket_info.lock_socket_tag);
283 if (socket_info.read_ioc)
285 g_io_channel_shutdown(socket_info.read_ioc, FALSE, NULL);
286 g_io_channel_unref(socket_info.read_ioc);
287 socket_info.read_ioc = NULL;
290 #ifdef G_OS_WIN32
291 WSACleanup();
292 #else
293 if (socket_info.file_name != NULL)
295 remove_socket_link_full(); /* deletes the socket file and the symlink */
296 g_free(socket_info.file_name);
298 #endif
300 return 0;
304 #ifdef G_OS_UNIX
305 static gint socket_fd_connect_unix(const gchar *path)
307 gint sock;
308 struct sockaddr_un addr;
310 sock = socket(PF_UNIX, SOCK_STREAM, 0);
311 if (sock < 0)
313 perror("fd_connect_unix(): socket");
314 return -1;
317 memset(&addr, 0, sizeof(addr));
318 addr.sun_family = AF_UNIX;
319 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
321 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
323 socket_fd_close(sock);
324 return -1;
327 return sock;
331 static gint socket_fd_open_unix(const gchar *path)
333 gint sock;
334 struct sockaddr_un addr;
335 gint val;
336 gchar *real_path;
338 sock = socket(PF_UNIX, SOCK_STREAM, 0);
340 if (sock < 0)
342 perror("sock_open_unix(): socket");
343 return -1;
346 val = 1;
347 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
349 perror("setsockopt");
350 socket_fd_close(sock);
351 return -1;
354 /* fix for #1888561:
355 * in case the configuration directory is located on a network file system or any other
356 * file system which doesn't support sockets, we just link the socket there and create the
357 * real socket in the system's tmp directory assuming it supports sockets */
358 real_path = g_strdup_printf("%s%cgeany_socket.%08x",
359 g_get_tmp_dir(), G_DIR_SEPARATOR, g_random_int());
361 if (utils_is_file_writeable(real_path) != 0)
362 { /* if real_path is not writable for us, fall back to ~/.config/geany/geany_socket_*_* */
363 /* instead of creating a symlink and print a warning */
364 g_warning("Socket %s could not be written, using %s as fallback.", real_path, path);
365 setptr(real_path, g_strdup(path));
367 /* create a symlink in e.g. ~/.config/geany/geany_socket_hostname__0 to /tmp/geany_socket.499602d2 */
368 else if (symlink(real_path, path) != 0)
370 perror("symlink");
371 socket_fd_close(sock);
372 return -1;
375 memset(&addr, 0, sizeof(addr));
376 addr.sun_family = AF_UNIX;
377 strncpy(addr.sun_path, real_path, sizeof(addr.sun_path) - 1);
379 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
381 perror("bind");
382 socket_fd_close(sock);
383 return -1;
386 if (listen(sock, 1) < 0)
388 perror("listen");
389 socket_fd_close(sock);
390 return -1;
393 g_chmod(real_path, 0600);
395 g_free(real_path);
397 return sock;
399 #endif
401 static gint socket_fd_close(gint fd)
403 #ifdef G_OS_WIN32
404 return closesocket(fd);
405 #else
406 return close(fd);
407 #endif
411 #ifdef G_OS_WIN32
412 static gint socket_fd_open_inet(gushort port)
414 SOCKET sock;
415 struct sockaddr_in addr;
416 gchar val;
418 sock = socket(AF_INET, SOCK_STREAM, 0);
419 if (! SOCKET_IS_VALID(sock))
421 geany_debug("fd_open_inet(): socket() failed: %d\n", WSAGetLastError());
422 return -1;
425 val = 1;
426 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
428 perror("setsockopt");
429 socket_fd_close(sock);
430 return -1;
433 memset(&addr, 0, sizeof(addr));
434 addr.sin_family = AF_INET;
435 addr.sin_port = htons(port);
436 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
438 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
440 perror("bind");
441 socket_fd_close(sock);
442 return -1;
445 if (listen(sock, 1) < 0)
447 perror("listen");
448 socket_fd_close(sock);
449 return -1;
452 return sock;
456 static gint socket_fd_connect_inet(gushort port)
458 SOCKET sock;
459 struct sockaddr_in addr;
461 sock = socket(AF_INET, SOCK_STREAM, 0);
462 if (! SOCKET_IS_VALID(sock))
464 geany_debug("fd_connect_inet(): socket() failed: %d\n", WSAGetLastError());
465 return -1;
468 memset(&addr, 0, sizeof(addr));
469 addr.sin_family = AF_INET;
470 addr.sin_port = htons(port);
471 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
473 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
475 socket_fd_close(sock);
476 return -1;
479 return sock;
483 static void socket_init_win32(void)
485 WSADATA wsadata;
487 if (WSAStartup(MAKEWORD(2, 2), &wsadata) != NO_ERROR)
488 geany_debug("WSAStartup() failed\n");
490 return;
492 #endif
495 static void handle_input_filename(const gchar *buf)
497 gchar *utf8_filename, *locale_filename;
499 /* we never know how the input is encoded, so do the best auto detection we can */
500 if (! g_utf8_validate(buf, -1, NULL))
501 utf8_filename = encodings_convert_to_utf8(buf, (gsize) -1, NULL);
502 else
503 utf8_filename = g_strdup(buf);
505 locale_filename = utils_get_locale_from_utf8(utf8_filename);
506 if (locale_filename)
508 if (g_str_has_suffix(locale_filename, ".geany"))
509 main_load_project_from_command_line(locale_filename, TRUE);
510 else
511 main_handle_filename(locale_filename);
513 g_free(utf8_filename);
514 g_free(locale_filename);
518 gboolean socket_lock_input_cb(GIOChannel *source, GIOCondition condition, gpointer data)
520 gint fd, sock;
521 gchar buf[4096];
522 struct sockaddr_in caddr;
523 guint caddr_len = sizeof(caddr);
524 GtkWidget *window = data;
525 gboolean popup = FALSE;
527 fd = g_io_channel_unix_get_fd(source);
528 sock = accept(fd, (struct sockaddr *)&caddr, &caddr_len);
530 /* first get the command */
531 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1)
533 if (strncmp(buf, "open", 4) == 0)
535 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
537 handle_input_filename(g_strstrip(buf));
539 popup = TRUE;
541 else if (strncmp(buf, "line", 4) == 0)
543 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
545 g_strstrip(buf); /* remove \n char */
546 /* on any error we get 0 which should be safe enough as fallback */
547 cl_options.goto_line = atoi(buf);
550 else if (strncmp(buf, "column", 6) == 0)
552 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
554 g_strstrip(buf); /* remove \n char */
555 /* on any error we get 0 which should be safe enough as fallback */
556 cl_options.goto_column = atoi(buf);
559 #ifdef G_OS_WIN32
560 else if (strncmp(buf, "window", 6) == 0)
562 HWND hwnd = (HWND) gdk_win32_drawable_get_handle(GDK_DRAWABLE(window->window));
563 socket_fd_write(sock, (gchar *)&hwnd, sizeof(hwnd));
565 #endif
568 if (popup)
570 #ifdef GDK_WINDOWING_X11
571 /* Set the proper interaction time on the window. This seems necessary to make
572 * gtk_window_present() really bring the main window into the foreground on some
573 * window managers like Gnome's metacity.
574 * Code taken from Gedit. */
575 gdk_x11_window_set_user_time(window->window, gdk_x11_get_server_time(window->window));
576 #endif
577 gtk_window_present(GTK_WINDOW(window));
578 #ifdef G_OS_WIN32
579 gdk_window_show(window->window);
580 #endif
583 socket_fd_close(sock);
585 return TRUE;
589 static gint socket_fd_gets(gint fd, gchar *buf, gint len)
591 gchar *newline, *bp = buf;
592 gint n;
594 if (--len < 1)
595 return -1;
598 if ((n = socket_fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
599 return -1;
600 if ((newline = memchr(bp, '\n', n)) != NULL)
601 n = newline - bp + 1;
602 if ((n = socket_fd_read(fd, bp, n)) < 0)
603 return -1;
604 bp += n;
605 len -= n;
606 } while (! newline && len);
608 *bp = '\0';
609 return bp - buf;
613 static gint socket_fd_recv(gint fd, gchar *buf, gint len, gint flags)
615 if (socket_fd_check_io(fd, G_IO_IN) < 0)
616 return -1;
618 return recv(fd, buf, len, flags);
622 static gint socket_fd_read(gint fd, gchar *buf, gint len)
624 if (socket_fd_check_io(fd, G_IO_IN) < 0)
625 return -1;
627 #ifdef G_OS_WIN32
628 return recv(fd, buf, len, 0);
629 #else
630 return read(fd, buf, len);
631 #endif
635 static gint socket_fd_check_io(gint fd, GIOCondition cond)
637 struct timeval timeout;
638 fd_set fds;
639 #ifdef G_OS_UNIX
640 gint flags;
641 #endif
643 timeout.tv_sec = 60;
644 timeout.tv_usec = 0;
646 #ifdef G_OS_UNIX
647 /* checking for non-blocking mode */
648 flags = fcntl(fd, F_GETFL, 0);
649 if (flags < 0)
651 perror("fcntl");
652 return 0;
654 if ((flags & O_NONBLOCK) != 0)
655 return 0;
656 #endif
658 FD_ZERO(&fds);
659 FD_SET(fd, &fds);
661 if (cond == G_IO_IN)
663 select(fd + 1, &fds, NULL, NULL, &timeout);
665 else
667 select(fd + 1, NULL, &fds, NULL, &timeout);
670 if (FD_ISSET(fd, &fds))
672 return 0;
674 else
676 geany_debug("Socket IO timeout");
677 return -1;
682 static gint socket_fd_write_all(gint fd, const gchar *buf, gint len)
684 gint n, wrlen = 0;
686 while (len)
688 n = socket_fd_write(fd, buf, len);
689 if (n <= 0)
690 return -1;
691 len -= n;
692 wrlen += n;
693 buf += n;
696 return wrlen;
700 gint socket_fd_write(gint fd, const gchar *buf, gint len)
702 if (socket_fd_check_io(fd, G_IO_OUT) < 0)
703 return -1;
705 #ifdef G_OS_WIN32
706 return send(fd, buf, len, 0);
707 #else
708 return write(fd, buf, len);
709 #endif
713 #endif