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.
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.
33 * Each command which is sent between two instances (see send_open_command and
34 * socket_lock_input_cb) should have the following scheme:
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.
63 # include <sys/time.h>
64 # include <sys/types.h>
65 # include <sys/socket.h>
67 # include <netinet/in.h>
68 # include <glib/gstdio.h>
70 # include <gdk/gdkwin32.h>
72 # include <winsock2.h>
73 # include <ws2tcpip.h>
79 #ifdef GDK_WINDOWING_X11
89 #include "encodings.h"
94 #define REMOTE_CMD_PORT 49876
95 #define SOCKET_IS_VALID(s) (G_LIKELY((s) != INVALID_SOCKET))
97 #define SOCKET_IS_VALID(s) (G_LIKELY((s) >= 0))
98 #define INVALID_SOCKET (-1)
102 struct socket_info_struct socket_info
;
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);
110 static gint
socket_fd_connect_unix (const gchar
*path
);
111 static gint
socket_fd_open_unix (const gchar
*path
);
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
)
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);
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);
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);
164 g_printerr(_("Could not find file '%s'."), filename
);
165 g_printerr("\n"); /* keep translation from open_cl_files() in main.c. */
169 socket_fd_write_all(sock
, ".\n", 2);
174 static void remove_socket_link_full(void)
176 gchar real_path
[512];
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);
186 real_path
[len
] = '\0';
189 g_unlink(socket_info
.file_name
);
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
)
205 hmutex
= CreateMutexA(NULL
, FALSE
, "Geany");
208 geany_debug("cannot create Mutex\n");
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
);
225 sock
= socket_fd_connect_inet(REMOTE_CMD_PORT
);
229 gchar
*display_name
= gdk_get_display();
230 gchar
*hostname
= utils_get_hostname();
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
)
239 while ((p
= strchr(display_name
, ':')) != NULL
)
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
);
249 sock
= socket_fd_connect_unix(socket_info
.file_name
);
252 remove_socket_link_full(); /* deletes the socket file and the symlink */
253 return socket_fd_open_unix(socket_info
.file_name
);
257 /* remote command mode, here we have another running instance and want to use it */
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
);
265 /* now we send the command line args */
268 send_open_command(sock
, argc
, argv
);
271 socket_fd_close(sock
);
276 gint
socket_finalize(void)
278 if (socket_info
.lock_socket
< 0)
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
;
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
);
305 static gint
socket_fd_connect_unix(const gchar
*path
)
308 struct sockaddr_un addr
;
310 sock
= socket(PF_UNIX
, SOCK_STREAM
, 0);
313 perror("fd_connect_unix(): socket");
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
);
331 static gint
socket_fd_open_unix(const gchar
*path
)
334 struct sockaddr_un addr
;
338 sock
= socket(PF_UNIX
, SOCK_STREAM
, 0);
342 perror("sock_open_unix(): socket");
347 if (setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
)) < 0)
349 perror("setsockopt");
350 socket_fd_close(sock
);
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)
371 socket_fd_close(sock
);
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)
382 socket_fd_close(sock
);
386 if (listen(sock
, 1) < 0)
389 socket_fd_close(sock
);
393 g_chmod(real_path
, 0600);
401 static gint
socket_fd_close(gint fd
)
404 return closesocket(fd
);
412 static gint
socket_fd_open_inet(gushort port
)
415 struct sockaddr_in addr
;
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());
426 if (setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
)) < 0)
428 perror("setsockopt");
429 socket_fd_close(sock
);
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)
441 socket_fd_close(sock
);
445 if (listen(sock
, 1) < 0)
448 socket_fd_close(sock
);
456 static gint
socket_fd_connect_inet(gushort port
)
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());
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
);
483 static void socket_init_win32(void)
487 if (WSAStartup(MAKEWORD(2, 2), &wsadata
) != NO_ERROR
)
488 geany_debug("WSAStartup() failed\n");
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
);
503 utf8_filename
= g_strdup(buf
);
505 locale_filename
= utils_get_locale_from_utf8(utf8_filename
);
508 if (g_str_has_suffix(locale_filename
, ".geany"))
509 main_load_project_from_command_line(locale_filename
, TRUE
);
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
)
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
));
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
);
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
));
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
));
577 gtk_window_present(GTK_WINDOW(window
));
579 gdk_window_show(window
->window
);
583 socket_fd_close(sock
);
589 static gint
socket_fd_gets(gint fd
, gchar
*buf
, gint len
)
591 gchar
*newline
, *bp
= buf
;
598 if ((n
= socket_fd_recv(fd
, bp
, len
, MSG_PEEK
)) <= 0)
600 if ((newline
= memchr(bp
, '\n', n
)) != NULL
)
601 n
= newline
- bp
+ 1;
602 if ((n
= socket_fd_read(fd
, bp
, n
)) < 0)
606 } while (! newline
&& len
);
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)
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)
628 return recv(fd
, buf
, len
, 0);
630 return read(fd
, buf
, len
);
635 static gint
socket_fd_check_io(gint fd
, GIOCondition cond
)
637 struct timeval timeout
;
647 /* checking for non-blocking mode */
648 flags
= fcntl(fd
, F_GETFL
, 0);
654 if ((flags
& O_NONBLOCK
) != 0)
663 select(fd
+ 1, &fds
, NULL
, NULL
, &timeout
);
667 select(fd
+ 1, NULL
, &fds
, NULL
, &timeout
);
670 if (FD_ISSET(fd
, &fds
))
676 geany_debug("Socket IO timeout");
682 static gint
socket_fd_write_all(gint fd
, const gchar
*buf
, gint len
)
688 n
= socket_fd_write(fd
, buf
, len
);
700 gint
socket_fd_write(gint fd
, const gchar
*buf
, gint len
)
702 if (socket_fd_check_io(fd
, G_IO_OUT
) < 0)
706 return send(fd
, buf
, len
, 0);
708 return write(fd
, buf
, len
);