2 * Copyright 2004-2005 Timo Hirvonen
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
22 #include <command_mode.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
33 static struct sockaddr_un addr
;
34 static int remote_socket
= -1;
36 #define MAX_CLIENTS 10
38 static void read_commands(int fd
)
46 rc
= read(fd
, buf
+ pos
, sizeof(buf
) - pos
);
59 for (i
= s
; i
< pos
; i
++) {
70 memmove(buf
, buf
+ s
, pos
- s
);
75 int remote_server_serve(void)
77 struct sockaddr saddr
;
78 socklen_t saddr_size
= sizeof(saddr
);
81 fd
= accept(remote_socket
, &saddr
, &saddr_size
);
90 int remote_server_init(const char *address
)
92 /* create socket - domain, type, protocol (IP) */
93 remote_socket
= socket(PF_UNIX
, SOCK_STREAM
, 0);
94 if (remote_socket
== -1)
96 addr
.sun_family
= AF_UNIX
;
97 strncpy(addr
.sun_path
, address
, sizeof(addr
.sun_path
) - 1);
99 if (bind(remote_socket
, (struct sockaddr
*)&addr
, sizeof(addr
)) == -1) {
102 if (errno
!= EADDRINUSE
)
105 /* address already in use */
107 /* try to connect to server */
108 sock
= socket(PF_UNIX
, SOCK_STREAM
, 0);
112 if (connect(sock
, (struct sockaddr
*)&addr
, sizeof(addr
)) == -1) {
113 if (errno
!= ENOENT
&& errno
!= ECONNREFUSED
)
114 die_errno("connect");
117 /* server not running => dead socket */
119 /* try to remove dead socket */
120 if (unlink(addr
.sun_path
) == -1 && errno
!= ENOENT
)
122 if (bind(remote_socket
, (struct sockaddr
*)&addr
, sizeof(addr
)) == -1)
125 /* server already running */
127 die(PACKAGE
" is already listening on socket %s\n", address
);
130 /* start listening */
131 BUG_ON(listen(remote_socket
, MAX_CLIENTS
) == -1);
132 return remote_socket
;
135 void remote_server_exit(void)
137 close(remote_socket
);
138 if (unlink(addr
.sun_path
) == -1)
139 d_print("unlink failed\n");