tracking down insane socket tester bugs on windoze, where the main culprit so far...
[feisty_meow.git] / octopi / library / sockets / raw_socket.cpp
1 /*****************************************************************************\
2 *                                                                             *
3 *  Name   : raw_socket                                                        *
4 *  Author : Chris Koeritz                                                     *
5 *                                                                             *
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 \*****************************************************************************/
14
15 #include "raw_socket.h"
16 #include "tcpip_stack.h"
17
18 #include <basis/functions.h>
19 #include <loggers/critical_events.h>
20 #include <loggers/program_wide_logger.h>
21 #include <timely/time_stamp.h>
22
23 #include <stdlib.h>
24 #ifdef __APPLE__
25   #include <fcntl.h>
26 #endif
27 #ifdef __UNIX__
28   #include <arpa/inet.h>
29   #include <errno.h>
30   #include <netinet/tcp.h>
31   #include <sys/ioctl.h>
32   #include <sys/socket.h>
33   #include <unistd.h>
34   #define OPTYPE (void *)
35 #endif
36 #ifdef __WIN32__
37   #define OPTYPE (char *)
38 #endif
39
40 using namespace basis;
41 using namespace loggers;
42 using namespace timely;
43
44 namespace sockets {
45
46 //#define DEBUG_RAW_SOCKET
47   // uncomment for noisy diagnostics.
48
49 #undef LOG
50 #define LOG(to_print) CLASS_EMERGENCY_LOG(program_wide_logger::get(), to_print)
51
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.
56
57 class fd_set_wrapper : public fd_set {};
58
59 //////////////
60
61 const basis::un_int NON_BLOCKING = FIONBIO;
62 const basis::un_int IOCTL_READ = FIONREAD;
63
64 #ifdef __WIN32__
65 /*
66 // defined by winsock header but not present in the winsock dll.
67 int PASCAL FAR __WSAFDIsSet(SOCKET fd, fd_set FAR *the_set)
68 {
69   int i = the_set->fd_count;
70   while (i--)
71     if (the_set->fd_array[i] == fd)
72       return true;
73   return false;
74 }
75 */
76 #endif
77
78 //////////////
79
80 raw_socket::raw_socket()
81 : _stack(new tcpip_stack())
82 {}
83
84 raw_socket::~raw_socket()
85 {
86   WHACK(_stack);
87 }
88
89 int raw_socket::close(basis::un_int &socket)
90 {
91   int to_return = 0;
92 #ifdef __WIN32__
93   to_return = closesocket(socket);
94 #endif
95 #ifdef __UNIX__
96   to_return = ::close(socket);
97 #endif
98   socket = 0;
99   return to_return;
100 }
101
102 //move this into parser bits as a OR combiner or something.
103 void combine(astring &existing, const astring &addition)
104 {
105   if (addition.t()) {
106     if (existing.t()) existing += " | ";
107     existing += addition;
108   }
109 }
110
111 astring raw_socket::interest_name(int interest)
112 {
113   astring to_return;
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");
120   return to_return;
121 }
122
123 int raw_socket::ioctl(basis::un_int socket, int request, void *argp) const
124 {
125 #ifdef __UNIX__
126   return ::ioctl(socket, request, argp);
127 #endif
128 #ifdef __WIN32__
129   return ioctlsocket(socket, request, (un_long *)argp);
130 #endif
131 }
132
133 bool raw_socket::set_non_blocking(basis::un_int socket, bool non_blocking)
134 {
135   FUNCDEF("set_non_blocking");
136 #ifdef __APPLE__
137   int curr_flags = fcntl(socket, F_GETFL, 0);
138   if (fcntl(socket, F_SETFL, curr_flags | O_NONBLOCK) < 0) return false;
139 #else
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));
143     return false;
144   }
145 #endif
146   return true;
147 }
148
149 bool raw_socket::set_nagle_algorithm(basis::un_int socket, bool use_nagle)
150 {
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,
154       sizeof(arg)))) {
155     LOG(a_sprintf("Could not change nagle coalescing mode on %u.", socket));
156     return false;
157   }
158   return true;
159 }
160
161 bool raw_socket::set_broadcast(basis::un_int socket, bool broadcasting)
162 {
163   FUNCDEF("set_broadcast");
164   int arg = int(broadcasting);
165   if (negative(setsockopt(socket, SOL_SOCKET, SO_BROADCAST, OPTYPE &arg,
166       sizeof(arg)))) {
167     LOG(a_sprintf("Could not change broadcast mode on %u.", socket));
168     return false;
169   }
170   return true;
171 }
172
173 bool raw_socket::set_reuse_address(basis::un_int socket, bool reuse)
174 {
175   FUNCDEF("set_reuse_address");
176   int arg = int(reuse);
177   if (negative(setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, OPTYPE &arg,
178       sizeof(arg)))) {
179     LOG(a_sprintf("Could not set reuse address mode on %u.", socket));
180     return false;
181   }
182   return true;
183 }
184
185 bool raw_socket::set_keep_alive(basis::un_int socket, bool keep_alive)
186 {
187   FUNCDEF("set_keep_alive");
188   int arg = int(keep_alive);
189   if (negative(setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, OPTYPE &arg,
190       sizeof(arg)))) {
191     LOG(a_sprintf("Could not set keep alive mode on %u.", socket));
192     return false;
193   }
194   return true;
195 }
196
197 int raw_socket::select(basis::un_int socket, int mode, int timeout) const
198 {
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);
207 }
208
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
212 {
213   FUNCDEF("inner_select");
214   // setup the file descriptor sets for the select.  we check readability,
215   // writability and exception status.
216 LOG("select A");
217   FD_ZERO(&read_list); FD_SET(socket, &read_list);
218 LOG("select B");
219   FD_ZERO(&write_list); FD_SET(socket, &write_list);
220 LOG("select C");
221   FD_ZERO(&exceptions); FD_SET(socket, &exceptions);
222 LOG("select D");
223 timeval *farkle = new timeval;
224 LOG("select D.1");
225 time_stamp *t = new time_stamp();
226 LOG("select D.2");
227
228   timeval time_out;
229   time_stamp::fill_timeval_ms(time_out, timeout);
230     // timeval has tv_sec=seconds, tv_usec=microseconds.
231
232 LOG("select E");
233   // select will tell us about the socket.
234   int ret = ::select(socket + 1,
235       (mode & SELECTING_JUST_WRITE)? NIL : &read_list,
236       (mode & SELECTING_JUST_READ)? NIL : &write_list,
237       &exceptions, &time_out);
238 LOG("select F");
239   int error = critical_events::system_error();
240 LOG("select G");
241
242   if (!ret) return 0;  // nothing to report.
243
244   if (ret == SOCKET_ERROR) {
245 LOG("select H");
246     switch (error) {
247       // all real errors fall out to the error handling stuff.
248       case SOCK_EFAULT:  // intentional fall-through.
249       case SOCK_ENETDOWN:  // intentional fall-through.
250       case SOCK_EINVAL:  // intentional fall-through.
251       case SOCK_EINTR:  // intentional fall-through.
252 #ifdef __WIN32__
253       case SOCK_NOTINITIALISED:  // intentional fall-through.
254 #endif
255       case SOCK_ENOTSOCK:
256         break;
257
258       // hopefully all these others are bogus errors...
259       case SOCK_EINPROGRESS:  // intentional fall-through.
260       case 0:  // intentional fall-through.
261       default:
262 #ifdef DEBUG_RAW_SOCKET
263         LOG("got to weird case, in progress or zero.");
264 #endif
265         return 0;  // not really an error.
266     }
267 LOG("select I");
268 #ifdef DEBUG_RAW_SOCKET
269     LOG(a_sprintf("socket %u had error %d in select: %s.",
270         socket, error, _stack->tcpip_error_name(error).s()));
271 #endif
272     return SI_ERRONEOUS;
273   }
274
275 LOG("select J");
276   // if we got to here, then there are some things to report...
277   return SI_BASELINE;
278 }
279
280 int raw_socket::test_readability(basis::un_int socket) const
281 {
282   FUNCDEF("test_readability");
283   basis::un_int len;
284   if (negative(ioctl(socket, IOCTL_READ, &len))) {
285     LOG(astring(astring::SPRINTF, "socket %u had ioctl error: %s.",
286         socket, _stack->tcpip_error_name(critical_events::system_error()).s()));
287     return SI_ERRONEOUS;
288   } else {
289     if (positive(len)) return SI_READABLE;
290     else return SI_DISCONNECTED;
291   }
292 }
293
294 int raw_socket::analyze_select_result(basis::un_int socket, int mode,
295     fd_set_wrapper &read_list, fd_set_wrapper &write_list,
296     fd_set_wrapper &exceptions) const
297 {
298 #ifdef DEBUG_RAW_SOCKET
299   FUNCDEF("analyze_select_result");
300 #endif
301   int to_return = 0;
302
303   // in case of an exception, we return an error.
304   if (FD_ISSET(socket, &exceptions)) {
305 #ifdef DEBUG_RAW_SOCKET
306     LOG(astring(astring::SPRINTF, "exception seen for socket %u!", socket));
307 #endif
308   }
309
310   // check to see if there are bytes to read.
311   if ( ! (mode & SELECTING_JUST_WRITE) && FD_ISSET(socket, &read_list)) {
312     // make sure we have data.  if no data is available, it means a
313     // disconnect occurred.
314
315     int readable = test_readability(socket);
316     if (readable == SI_ERRONEOUS)
317       to_return |= SI_ERRONEOUS;
318     else if (readable == SI_READABLE)
319       to_return |= SI_READABLE;
320     else if (readable == SI_DISCONNECTED) {
321       // we need to check multiple times to be sure the OS really means this.
322       // either windoze seems to report an erroneous disconnect every few
323       // days or there's a bad synchronization issue as yet uncovered.
324       bool really_disconnected = true;
325       for (int i = 0; i < MULTIPLE_DISCONNECT_CHECKS; i++) {
326         fd_set_wrapper read_list, write_list, exceps;
327         int temp_ret = inner_select(socket, SELECTING_JUST_READ, 0, read_list,
328             write_list, exceps);
329         // check the return value first...
330         if (!temp_ret) {
331           // nothing happening (a zero return) means the socket's no longer
332           // claiming to have a readable state; our disconnect condition is
333           // thus violated and we can leave.
334           really_disconnected = false;
335           break;
336         }
337         if (temp_ret == SI_ERRONEOUS) {
338           // this, on the other hand, sounds really bad.  the socket doesn't
339           // seem to exist any more or something else horrid happened.
340           really_disconnected = true;
341           break;
342         }
343         // if the select worked, we can check the fd_set now for readability.
344         if (!FD_ISSET(socket, &read_list)) {
345           // we are not in a disconnected state without being told we're
346           // readable.  supposedly.
347           really_disconnected = false;
348           break;
349         }
350         // now we really test the socket for readability by making sure there
351         // really is data pending on the socket.  if it's readable but there's
352         // no data, then either a disconnection has occurred or is in progress.
353         readable = test_readability(socket);
354         if (readable != SI_DISCONNECTED) {
355           // we are not disconnected if there's really data waiting.
356           really_disconnected = false;
357           break;
358         }
359       }
360       if (really_disconnected) {
361 #ifdef DEBUG_RAW_SOCKET
362         LOG(a_sprintf("connection closed on socket %u.", socket));
363 #endif
364         to_return |= SI_DISCONNECTED;
365       }
366     }
367   }
368
369   // check writability state.
370   if (! (mode & SELECTING_JUST_READ) && FD_ISSET(socket, &write_list)) {
371     to_return |= SI_WRITABLE;
372   }
373
374   return to_return;
375 }
376
377 int raw_socket::select(int_array &read_sox, int_array &write_sox,
378     int timeout) const
379 {
380 #ifdef DEBUG_RAW_SOCKET
381   FUNCDEF("select [multiple]");
382 #endif
383   if (!read_sox.length() && !write_sox.length())
384    return 0;  // nothing happened to nothing.
385
386   int to_return = 0;  // will get bits slammed into it to report results.
387
388   // setup the file descriptor sets for the select.  we check readability,
389   // writability and exception status.
390   fd_set_wrapper read_list; FD_ZERO(&read_list);
391   fd_set_wrapper write_list; FD_ZERO(&write_list);
392   fd_set_wrapper exceptions; FD_ZERO(&exceptions);
393   // set up the lists with the sets we were handed.
394   basis::un_int highest = 0;
395   int i = 0;
396   for (i = 0; i < read_sox.length(); i++) {
397     basis::un_int sock = (basis::un_int)read_sox[i];
398     if (sock > highest) highest = sock;
399     FD_SET(sock, &read_list);
400   }
401   for (i = 0; i < write_sox.length(); i++) {
402     basis::un_int sock = (basis::un_int)write_sox[i];
403     if (sock > highest) highest = sock;
404     FD_SET(sock, &write_list);
405   }
406
407   timeval time_out;
408   time_stamp::fill_timeval_ms(time_out, timeout);
409     // timeval has tv_sec=seconds, tv_usec=microseconds.
410
411   // select will tell us about the socket.
412   int ret = ::select(highest + 1,
413       (read_sox.length())? &read_list : NIL,
414       (write_sox.length())? &write_list : NIL,
415       &exceptions, &time_out);
416   int error = critical_events::system_error();
417
418   if (ret == SOCKET_ERROR) {
419     switch (error) {
420       // all real errors fall out to the error handling stuff.
421       case SOCK_EFAULT:  // intentional fall-through.
422       case SOCK_ENETDOWN:  // intentional fall-through.
423       case SOCK_EINVAL:  // intentional fall-through.
424       case SOCK_EINTR:  // intentional fall-through.
425 #ifdef __WIN32__
426       case SOCK_NOTINITIALISED:  // intentional fall-through.
427 #endif
428       case SOCK_ENOTSOCK:
429         break;
430
431       // hopefully all these others are bogus errors...
432       case SOCK_EINPROGRESS:  // intentional fall-through.
433       case 0:  // intentional fall-through.
434       default:
435 #ifdef DEBUG_RAW_SOCKET
436         LOG("got to weird case, in progress or zero.");
437 #endif
438
439 //hmmm: fix retd sox?  what's this outcome mean for the list?
440
441         return 0;  // not really an error.
442     }
443 #ifdef DEBUG_RAW_SOCKET
444     LOG(a_sprintf("sockets had error %d in select: %s.",
445         error, _stack->tcpip_error_name(error).s()));
446 #endif
447
448 //hmmm: fix retd sox?  what's this outcome mean for the list?
449
450     return SI_ERRONEOUS;
451   } else if (!ret) {
452     // we know of nothing exciting for any of these.
453     read_sox.reset();
454     write_sox.reset();
455     return 0;  // nothing to report.
456   }
457
458   // if we got to here, then there are some things to report...
459   // iterate through the lists and check results.
460   for (int k = 0; k < read_sox.length(); k++) {
461     basis::un_int socket = read_sox[k];
462     int interim = analyze_select_result(socket, SELECTING_JUST_READ, read_list,
463         write_list, exceptions);
464     if (!interim) {
465       // nothing happened on that guy.
466       read_sox.zap(k, k);
467       k--;  // skip back to before the whack.
468       continue;
469     }
470     to_return |= interim;  // join the results with overall result.
471   }
472   for (int p = 0; p < write_sox.length(); p++) {
473     basis::un_int socket = write_sox[p];
474     int interim = analyze_select_result(socket, SELECTING_JUST_WRITE, read_list,
475         write_list, exceptions);
476     if (!interim) {
477       // nothing happened on that guy.
478       write_sox.zap(p, p);
479       p--;  // skip back to before the whack.
480       continue;
481     }
482     to_return |= interim;  // join the results with overall result.
483   }
484
485   return to_return;
486 }
487
488 } //namespace.
489