1 /*****************************************************************************\
4 * Author : Chris Koeritz *
6 *******************************************************************************
7 * Copyright (c) 1991-$now By Author. This program is free software; you can *
8 * redistribute it and/or modify it under the terms of the GNU General Public *
9 * License as published by the Free Software Foundation; either version 2 of *
10 * the License or (at your option) any later version. This is online at: *
11 * http://www.fsf.org/copyleft/gpl.html *
12 * Please send any updates to: fred@gruntose.com *
13 \*****************************************************************************/
15 #include "raw_socket.h"
16 #include "tcpip_stack.h"
18 #include <basis/functions.h>
19 #include <loggers/critical_events.h>
20 #include <loggers/program_wide_logger.h>
21 #include <timely/time_stamp.h>
28 #include <arpa/inet.h>
30 #include <netinet/tcp.h>
31 #include <sys/ioctl.h>
32 #include <sys/socket.h>
34 #define OPTYPE (void *)
37 #define OPTYPE (char *)
40 using namespace basis;
41 using namespace loggers;
42 using namespace timely;
46 //#define DEBUG_RAW_SOCKET
47 // uncomment for noisy diagnostics.
50 #define LOG(to_print) CLASS_EMERGENCY_LOG(program_wide_logger::get(), to_print)
52 const int MULTIPLE_DISCONNECT_CHECKS = 28;
53 // we will make certain that select really says there's data and ioctl
54 // really says there's no data waiting before we believe there's been
55 // a disconnect. we'll check that state the number of times specified.
57 class fd_set_wrapper : public fd_set {};
61 const basis::un_int NON_BLOCKING = FIONBIO;
62 const basis::un_int IOCTL_READ = FIONREAD;
66 // defined by winsock header but not present in the winsock dll.
67 int PASCAL FAR __WSAFDIsSet(SOCKET fd, fd_set FAR *the_set)
69 int i = the_set->fd_count;
71 if (the_set->fd_array[i] == fd)
80 raw_socket::raw_socket()
81 : _stack(new tcpip_stack())
84 raw_socket::~raw_socket()
89 int raw_socket::close(basis::un_int &socket)
93 to_return = closesocket(socket);
96 to_return = ::close(socket);
102 //move this into parser bits as a OR combiner or something.
103 void combine(astring &existing, const astring &addition)
106 if (existing.t()) existing += " | ";
107 existing += addition;
111 astring raw_socket::interest_name(int interest)
114 if (interest & SI_CONNECTED) combine(to_return, "CONNECTED");
115 if (interest & SI_DISCONNECTED) combine(to_return, "DISCONNECTED");
116 if (interest & SI_WRITABLE) combine(to_return, "WRITABLE");
117 if (interest & SI_READABLE) combine(to_return, "READABLE");
118 if (interest & SI_ERRONEOUS) combine(to_return, "ERRONEOUS");
119 if (!interest) combine(to_return, "NORMAL");
123 int raw_socket::ioctl(basis::un_int socket, int request, void *argp) const
126 return ::ioctl(socket, request, argp);
129 return ioctlsocket(socket, request, (un_long *)argp);
133 bool raw_socket::set_non_blocking(basis::un_int socket, bool non_blocking)
135 FUNCDEF("set_non_blocking");
137 int curr_flags = fcntl(socket, F_GETFL, 0);
138 if (fcntl(socket, F_SETFL, curr_flags | O_NONBLOCK) < 0) return false;
140 int arg = int(non_blocking);
141 if (negative(ioctl(socket, NON_BLOCKING, &arg))) {
142 LOG(a_sprintf("Could not set non-blocking (FIONBIO) option on raw_socket %u.", socket));
149 bool raw_socket::set_nagle_algorithm(basis::un_int socket, bool use_nagle)
151 FUNCDEF("set_nagle_algorithm");
152 int arg = int(!use_nagle); // opposite of the flag, since we set no-delay.
153 if (negative(setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, OPTYPE &arg,
155 LOG(a_sprintf("Could not change nagle coalescing mode on %u.", socket));
161 bool raw_socket::set_broadcast(basis::un_int socket, bool broadcasting)
163 FUNCDEF("set_broadcast");
164 int arg = int(broadcasting);
165 if (negative(setsockopt(socket, SOL_SOCKET, SO_BROADCAST, OPTYPE &arg,
167 LOG(a_sprintf("Could not change broadcast mode on %u.", socket));
173 bool raw_socket::set_reuse_address(basis::un_int socket, bool reuse)
175 FUNCDEF("set_reuse_address");
176 int arg = int(reuse);
177 if (negative(setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, OPTYPE &arg,
179 LOG(a_sprintf("Could not set reuse address mode on %u.", socket));
185 bool raw_socket::set_keep_alive(basis::un_int socket, bool keep_alive)
187 FUNCDEF("set_keep_alive");
188 int arg = int(keep_alive);
189 if (negative(setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, OPTYPE &arg,
191 LOG(a_sprintf("Could not set keep alive mode on %u.", socket));
197 int raw_socket::select(basis::un_int socket, int mode, int timeout) const
199 FUNCDEF("select [single]");
200 if (!socket) return SI_ERRONEOUS;
201 fd_set_wrapper read_list, write_list, exceps;
202 int ret = inner_select(socket, mode, timeout, read_list, write_list, exceps);
203 if (!ret) return 0; // nothing is happening.
204 if (ret == SI_ERRONEOUS) return SI_ERRONEOUS; // something bad happened.
205 // otherwise we should be at base-line status.
206 return analyze_select_result(socket, mode, read_list, write_list, exceps);
209 int raw_socket::inner_select(basis::un_int socket, int mode, int timeout,
210 fd_set_wrapper &read_list, fd_set_wrapper &write_list,
211 fd_set_wrapper &exceptions) const
213 #ifdef DEBUG_RAW_SOCKET
214 FUNCDEF("inner_select");
216 // setup the file descriptor sets for the select. we check readability,
217 // writability and exception status.
218 FD_ZERO(&read_list); FD_SET(socket, &read_list);
219 FD_ZERO(&write_list); FD_SET(socket, &write_list);
220 FD_ZERO(&exceptions); FD_SET(socket, &exceptions);
222 timeval time_out = time_stamp::fill_timeval_ms(timeout);
223 // timeval has tv_sec=seconds, tv_usec=microseconds.
225 // select will tell us about the socket.
226 int ret = ::select(socket + 1,
227 (mode & SELECTING_JUST_WRITE)? NIL : &read_list,
228 (mode & SELECTING_JUST_READ)? NIL : &write_list,
229 &exceptions, &time_out);
230 int error = critical_events::system_error();
232 if (!ret) return 0; // nothing to report.
234 if (ret == SOCKET_ERROR) {
236 // all real errors fall out to the error handling stuff.
237 case SOCK_EFAULT: // intentional fall-through.
238 case SOCK_ENETDOWN: // intentional fall-through.
239 case SOCK_EINVAL: // intentional fall-through.
240 case SOCK_EINTR: // intentional fall-through.
242 case SOCK_NOTINITIALISED: // intentional fall-through.
247 // hopefully all these others are bogus errors...
248 case SOCK_EINPROGRESS: // intentional fall-through.
249 case 0: // intentional fall-through.
251 #ifdef DEBUG_RAW_SOCKET
252 LOG("got to weird case, in progress or zero.");
254 return 0; // not really an error.
256 #ifdef DEBUG_RAW_SOCKET
257 LOG(a_sprintf("socket %u had error %d in select: %s.",
258 socket, error, _stack->tcpip_error_name(error).s()));
263 // if we got to here, then there are some things to report...
267 int raw_socket::test_readability(basis::un_int socket) const
269 FUNCDEF("test_readability");
271 if (negative(ioctl(socket, IOCTL_READ, &len))) {
272 LOG(astring(astring::SPRINTF, "socket %u had ioctl error: %s.",
273 socket, _stack->tcpip_error_name(critical_events::system_error()).s()));
276 if (positive(len)) return SI_READABLE;
277 else return SI_DISCONNECTED;
281 int raw_socket::analyze_select_result(basis::un_int socket, int mode,
282 fd_set_wrapper &read_list, fd_set_wrapper &write_list,
283 fd_set_wrapper &exceptions) const
285 #ifdef DEBUG_RAW_SOCKET
286 FUNCDEF("analyze_select_result");
290 // in case of an exception, we return an error.
291 if (FD_ISSET(socket, &exceptions)) {
292 #ifdef DEBUG_RAW_SOCKET
293 LOG(astring(astring::SPRINTF, "exception seen for socket %u!", socket));
297 // check to see if there are bytes to read.
298 if ( ! (mode & SELECTING_JUST_WRITE) && FD_ISSET(socket, &read_list)) {
299 // make sure we have data. if no data is available, it means a
300 // disconnect occurred.
302 int readable = test_readability(socket);
303 if (readable == SI_ERRONEOUS)
304 to_return |= SI_ERRONEOUS;
305 else if (readable == SI_READABLE)
306 to_return |= SI_READABLE;
307 else if (readable == SI_DISCONNECTED) {
308 // we need to check multiple times to be sure the OS really means this.
309 // either windoze seems to report an erroneous disconnect every few
310 // days or there's a bad synchronization issue as yet uncovered.
311 bool really_disconnected = true;
312 for (int i = 0; i < MULTIPLE_DISCONNECT_CHECKS; i++) {
313 fd_set_wrapper read_list, write_list, exceps;
314 int temp_ret = inner_select(socket, SELECTING_JUST_READ, 0, read_list,
316 // check the return value first...
318 // nothing happening (a zero return) means the socket's no longer
319 // claiming to have a readable state; our disconnect condition is
320 // thus violated and we can leave.
321 really_disconnected = false;
324 if (temp_ret == SI_ERRONEOUS) {
325 // this, on the other hand, sounds really bad. the socket doesn't
326 // seem to exist any more or something else horrid happened.
327 really_disconnected = true;
330 // if the select worked, we can check the fd_set now for readability.
331 if (!FD_ISSET(socket, &read_list)) {
332 // we are not in a disconnected state without being told we're
333 // readable. supposedly.
334 really_disconnected = false;
337 // now we really test the socket for readability by making sure there
338 // really is data pending on the socket. if it's readable but there's
339 // no data, then either a disconnection has occurred or is in progress.
340 readable = test_readability(socket);
341 if (readable != SI_DISCONNECTED) {
342 // we are not disconnected if there's really data waiting.
343 really_disconnected = false;
347 if (really_disconnected) {
348 #ifdef DEBUG_RAW_SOCKET
349 LOG(a_sprintf("connection closed on socket %u.", socket));
351 to_return |= SI_DISCONNECTED;
356 // check writability state.
357 if (! (mode & SELECTING_JUST_READ) && FD_ISSET(socket, &write_list)) {
358 to_return |= SI_WRITABLE;
364 int raw_socket::select(int_array &read_sox, int_array &write_sox,
367 #ifdef DEBUG_RAW_SOCKET
368 FUNCDEF("select [multiple]");
370 if (!read_sox.length() && !write_sox.length())
371 return 0; // nothing happened to nothing.
373 int to_return = 0; // will get bits slammed into it to report results.
375 // setup the file descriptor sets for the select. we check readability,
376 // writability and exception status.
377 fd_set_wrapper read_list; FD_ZERO(&read_list);
378 fd_set_wrapper write_list; FD_ZERO(&write_list);
379 fd_set_wrapper exceptions; FD_ZERO(&exceptions);
380 // set up the lists with the sets we were handed.
381 basis::un_int highest = 0;
383 for (i = 0; i < read_sox.length(); i++) {
384 basis::un_int sock = (basis::un_int)read_sox[i];
385 if (sock > highest) highest = sock;
386 FD_SET(sock, &read_list);
388 for (i = 0; i < write_sox.length(); i++) {
389 basis::un_int sock = (basis::un_int)write_sox[i];
390 if (sock > highest) highest = sock;
391 FD_SET(sock, &write_list);
394 timeval time_out = time_stamp::fill_timeval_ms(timeout);
395 // timeval has tv_sec=seconds, tv_usec=microseconds.
397 // select will tell us about the socket.
398 int ret = ::select(highest + 1,
399 (read_sox.length())? &read_list : NIL,
400 (write_sox.length())? &write_list : NIL,
401 &exceptions, &time_out);
402 int error = critical_events::system_error();
404 if (ret == SOCKET_ERROR) {
406 // all real errors fall out to the error handling stuff.
407 case SOCK_EFAULT: // intentional fall-through.
408 case SOCK_ENETDOWN: // intentional fall-through.
409 case SOCK_EINVAL: // intentional fall-through.
410 case SOCK_EINTR: // intentional fall-through.
412 case SOCK_NOTINITIALISED: // intentional fall-through.
417 // hopefully all these others are bogus errors...
418 case SOCK_EINPROGRESS: // intentional fall-through.
419 case 0: // intentional fall-through.
421 #ifdef DEBUG_RAW_SOCKET
422 LOG("got to weird case, in progress or zero.");
425 //hmmm: fix retd sox? what's this outcome mean for the list?
427 return 0; // not really an error.
429 #ifdef DEBUG_RAW_SOCKET
430 LOG(a_sprintf("sockets had error %d in select: %s.",
431 error, _stack->tcpip_error_name(error).s()));
434 //hmmm: fix retd sox? what's this outcome mean for the list?
438 // we know of nothing exciting for any of these.
441 return 0; // nothing to report.
444 // if we got to here, then there are some things to report...
445 // iterate through the lists and check results.
446 for (int k = 0; k < read_sox.length(); k++) {
447 basis::un_int socket = read_sox[k];
448 int interim = analyze_select_result(socket, SELECTING_JUST_READ, read_list,
449 write_list, exceptions);
451 // nothing happened on that guy.
453 k--; // skip back to before the whack.
456 to_return |= interim; // join the results with overall result.
458 for (int p = 0; p < write_sox.length(); p++) {
459 basis::un_int socket = write_sox[p];
460 int interim = analyze_select_result(socket, SELECTING_JUST_WRITE, read_list,
461 write_list, exceptions);
463 // nothing happened on that guy.
465 p--; // skip back to before the whack.
468 to_return |= interim; // join the results with overall result.