]> jfr.im git - irc/gameservirc.git/blob - gameserv/sockhelp.cpp
Fixed the socket code to allow for host names in the gameserv.conf for remoteserver...
[irc/gameservirc.git] / gameserv / sockhelp.cpp
1 /*
2 * This file is provided for use with the unix-socket-faq. It is public
3 * domain, and may be copied freely. There is no copyright on it. The
4 * original work was by Vic Metcalfe (vic@brutus.tlug.org), and any
5 * modifications made to that work were made with the understanding that
6 * the finished work would be in the public domain.
7 *
8 * If you have found a bug, please pass it on to me at the above address
9 * acknowledging that there will be no copyright on your work.
10 *
11 * The most recent version of this file, and the unix-socket-faq can be
12 * found at http://www.interlog.com/~vic/sock-faq/.
13 */
14
15 #include "sockhelp.h"
16 #include "extern.h"
17
18 /* Take a service name, and a service type, and return a port number. If
19 the
20 service name is not found, it tries it as a decimal number. The number
21 returned is byte ordered for the network. */
22 int atoport(char *service, char *proto)
23 {
24 int port;
25 long int lport;
26 char *errpos;
27
28 lport = strtol(service,&errpos,0);
29 if ( (errpos[0] != 0) || (lport < 1) || (lport > 65535) )
30 return -1; /* Invalid port address */
31
32 port = htons(lport);
33
34 return port;
35 }
36
37 /* Converts ascii text to in_addr struct. NULL is returned if the address
38 can not be found. */
39 struct in_addr *atoaddr(char *address)
40 {
41 struct hostent *host;
42 static struct in_addr saddr;
43
44 /* First try it as aaa.bbb.ccc.ddd. */
45 // saddr.s_addr = inet_addr(address);
46 // if (saddr.s_addr != 0) {
47 // return &saddr;
48 // }
49 host = gethostbyname(address);
50 if (host != NULL) {
51 return (struct in_addr *) *host->h_addr_list;
52 }
53 return NULL;
54 }
55
56 /* This function listens on a port, and returns connections. It forks
57 returns off internally, so your main function doesn't have to worry
58 about that. This can be confusing if you don't know what is going on.
59 The function will create a new process for every incoming connection,
60 so in the listening process, it will never return. Only when a
61 connection
62 comes in, and we create a new process for it will the function return.
63 This means that your code that calls it should _not_ loop.
64
65 The parameters are as follows:
66 socket_type: SOCK_STREAM or SOCK_DGRAM (TCP or UDP sockets)
67 port: The port to listen on. Remember that ports < 1024 are
68 reserved for the root user. Must be passed in network byte
69 order (see "man htons").
70 listener: This is a pointer to a variable for holding the file
71 descriptor of the socket which is being used to listen. It
72 is provided so that you can write a signal handler to close
73 it in the event of program termination. If you aren't interested,
74 just pass NULL. Note that all modern unixes will close file
75 descriptors for you on exit, so this is not required. */
76 int get_connection(int socket_type, u_short port, int *listener)
77 {
78 struct sockaddr_in address;
79 int listening_socket;
80 int connected_socket = -1;
81 int new_process;
82 int reuse_addr = 1;
83
84 /* Setup internet address information.
85 This is used with the bind() call */
86 memset((char *) &address, 0, sizeof(address));
87 address.sin_family = AF_INET;
88 address.sin_port = port;
89 address.sin_addr.s_addr = htonl(INADDR_ANY);
90
91 listening_socket = socket(AF_INET, socket_type, 0);
92 if (listening_socket < 0) {
93 perror("socket");
94 exit(EXIT_FAILURE);
95 }
96
97 if (listener != NULL)
98 *listener = listening_socket;
99
100 setsockopt(listening_socket, SOL_SOCKET, SO_REUSEADDR, &reuse_addr,
101 sizeof(reuse_addr));
102
103 if (bind(listening_socket, (struct sockaddr *) &address,
104 sizeof(address)) < 0) {
105 perror("bind");
106 close(listening_socket);
107 exit(EXIT_FAILURE);
108 }
109
110 if (socket_type == SOCK_STREAM) {
111 listen(listening_socket, 5); /* Queue up to five connections before
112 having them automatically rejected. */
113
114 while(connected_socket < 0) {
115 connected_socket = accept(listening_socket, NULL, NULL);
116 if (connected_socket < 0) {
117 /* Either a real error occured, or blocking was interrupted for
118 some reason. Only abort execution if a real error occured. */
119 if (errno != EINTR) {
120 perror("accept");
121 close(listening_socket);
122 exit(EXIT_FAILURE);
123 } else {
124 continue; /* don't fork - do the accept again */
125 }
126 }
127
128 new_process = fork();
129 if (new_process < 0) {
130 perror("fork");
131 close(connected_socket);
132 connected_socket = -1;
133 }
134 else { /* We have a new process... */
135 if (new_process == 0) {
136 /* This is the new process. */
137 close(listening_socket); /* Close our copy of this socket */
138 if (listener != NULL)
139 *listener = -1; /* Closed in this process. We are not
140 responsible for it. */
141 }
142 else {
143 /* This is the main loop. Close copy of connected socket, and
144 continue loop. */
145 close(connected_socket);
146 connected_socket = -1;
147 }
148 }
149 }
150 return connected_socket;
151 }
152 else
153 return listening_socket;
154 }
155
156 /* This is a generic function to make a connection to a given server/port.
157 service is the port name/number,
158 type is either SOCK_STREAM or SOCK_DGRAM, and
159 netaddress is the host name to connect to.
160 The function returns the socket, ready for action.*/
161 int make_connection(char *service, int type, char *netaddress)
162 {
163 /* First convert service from a string, to a number... */
164 int port = -1;
165 struct in_addr *addr;
166 int sock, connected;
167 struct sockaddr_in address;
168
169 if (type == SOCK_STREAM)
170 port = atoport(service, "tcp");
171 if (type == SOCK_DGRAM)
172 port = atoport(service, "udp");
173 if (port == -1) {
174 fprintf(stderr,"make_connection: Invalid socket type.\n");
175 return -1;
176 }
177 addr = atoaddr(netaddress);
178 if (addr == NULL) {
179 fprintf(stderr,"make_connection: Invalid network address.\n");
180 return -1;
181 }
182
183 memset((char *) &address, 0, sizeof(address));
184 address.sin_family = AF_INET;
185 address.sin_port = (port);
186 address.sin_addr.s_addr = addr->s_addr;
187
188 sock = socket(AF_INET, type, 0);
189
190 log("Connecting to %s on port %d.",inet_ntoa(*addr),htons(port));
191
192 if (type == SOCK_STREAM) {
193 connected = connect(sock, (struct sockaddr *) &address,
194 sizeof(address));
195 if (connected < 0) {
196 perror("connect");
197 return -1;
198 }
199 return sock;
200 }
201 /* Otherwise, must be for udp, so bind to address. */
202 if (bind(sock, (struct sockaddr *) &address, sizeof(address)) < 0) {
203 perror("bind");
204 return -1;
205 }
206 return sock;
207 }
208
209 /* This is just like the read() system call, accept that it will make
210 sure that all your data goes through the socket. */
211 int sock_read(int sockfd, char *buf, size_t count)
212 {
213 size_t bytes_read = 0;
214 int this_read;
215
216 while (bytes_read < count) {
217 do
218 this_read = read(sockfd, buf, count - bytes_read);
219 while ( (this_read < 0) && (errno == EINTR) );
220 if (this_read < 0)
221 return this_read;
222 else if (this_read == 0)
223 return bytes_read;
224 bytes_read += this_read;
225 buf += this_read;
226 }
227 return count;
228 }
229
230 /* This function reads from a socket, until it recieves a linefeed
231 character. It fills the buffer "str" up to the maximum size "count".
232
233 This function will return -1 if the socket is closed during the read
234 operation.
235
236 Note that if a single line exceeds the length of count, the extra data
237 will be read and discarded! You have been warned. */
238 int sock_gets(int sockfd, char *str, size_t count)
239 {
240 int bytes_read;
241 unsigned int total_count = 0;
242 char *current_position;
243 char last_read = 0;
244
245 current_position = str;
246 while (last_read != 10) {
247 bytes_read = read(sockfd, &last_read, 1);
248 if (bytes_read <= 0) {
249 /* The other side may have closed unexpectedly */
250 return -1; /* Is this effective on other platforms than linux? */
251 }
252 if ( (total_count < count) && (last_read != 10) && (last_read !=13) )
253 {
254 current_position[0] = last_read;
255 current_position++;
256 total_count++;
257 }
258 }
259 if (count > 0)
260 current_position[0] = 0;
261 return total_count;
262 }
263
264 /* This is just like the write() system call, accept that it will
265 make sure that all data is transmitted. */
266 int sock_write(int sockfd, const char *buf, size_t count)
267 {
268 size_t bytes_sent = 0;
269 int this_write;
270
271 while (bytes_sent < count) {
272 do
273 this_write = write(sockfd, buf, count - bytes_sent);
274 while ( (this_write < 0) && (errno == EINTR) );
275 if (this_write <= 0)
276 return this_write;
277 bytes_sent += this_write;
278 buf += this_write;
279 }
280 return count;
281 }
282
283 /* This function writes a character string out to a socket. It will
284 return -1 if the connection is closed while it is trying to write. */
285 int sock_puts(int sockfd, const char *str)
286 {
287 return sock_write(sockfd, str, strlen(str));
288 }
289
290 /* This ignores the SIGPIPE signal. This is usually a good idea, since
291 the default behaviour is to terminate the application. SIGPIPE is
292 sent when you try to write to an unconnected socket. You should
293 check your return codes to make sure you catch this error! */
294 void ignore_pipe(void)
295 {
296 struct sigaction sig;
297
298 sig.sa_handler = SIG_IGN;
299 sig.sa_flags = 0;
300 sigemptyset(&sig.sa_mask);
301 sigaction(SIGPIPE,&sig,NULL);
302 }
303