ProtoBSDIP.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595
  1. ////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2016 RWS Inc, All Rights Reserved
  4. //
  5. // This program is free software; you can redistribute it and/or modify
  6. // it under the terms of version 2 of the GNU General Public License as published by
  7. // the Free Software Foundation
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License along
  15. // with this program; if not, write to the Free Software Foundation, Inc.,
  16. // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. //
  18. // ProtoBSDIP.cpp
  19. // Project: Postal
  20. //
  21. // History:
  22. // 08/04/97 BRH Started.
  23. //
  24. // 08/06/97 BRH Debugged - restored to working order.
  25. // MJR
  26. //
  27. // 08/07/97 BRH Fixed error message that referred to RSocket
  28. //
  29. // 08/08/97 MJR Upgraded to latest revision of plugin stuff.
  30. //
  31. // 08/09/97 MJR Added broadcast support.
  32. //
  33. // 08/14/97 MJR Fixed GetAddress() to avoid database function when
  34. // working with a dotted address.
  35. //
  36. // 08/18/97 MJR Fixed stupid error in GetAddress() that caused crashes.
  37. //
  38. // 08/20/97 MJR Added support for setting whether socket blocks or not.
  39. //
  40. // 09/02/97 MJR Got rid of TRACE() on "would block" situations.
  41. //
  42. // MJR Fixed serious bug that caused functions to return -1
  43. // as the number of actual bytes sent/received if an
  44. // error occurred -- they now properly return 0 instead.
  45. //
  46. // 09/09/97 MJR Added RSocket::errNotSupported return value to Open().
  47. //
  48. // 11/18/97 JMI Added message and Close() in destructor for case when
  49. // an opened socket is never closed. Trying to find memory
  50. // leak but this was apparently not the problem.
  51. //
  52. //////////////////////////////////////////////////////////////////////////////
  53. //
  54. // WINSOCK NOTES
  55. // -------------
  56. //
  57. //
  58. // Windows NT WorkStation 4.0 only allow a maximum of 5 backlogs on listen().
  59. // Earlier versions of NT were also limited to 5. NT servers defaults to 200.
  60. // No idea what Win95 does.
  61. //
  62. // Sockets allow for "stream" (TCP) and "datagram" (UDP). TCP is referred to
  63. // as "connected", while UDP is normally connectionless.
  64. //
  65. // You can use UDP in connected mode, which saves you from having to specify
  66. // the destination for each send operation and also automatically discards any
  67. // data received from anywhere other than that same destination. This may be
  68. // faster, depending on the WinSock implimentation.
  69. //
  70. // I suppose one important advantage of being "unconnected" is that you can
  71. // send and receive to/from multiple remote systems, which may be more suitable
  72. // if you were doing some sort of "star" network, where any system can talk to
  73. // any other system. It seems, though, that you could simulate this with TCP
  74. // or connected UDP by using multiple ports, one per remote system.
  75. //
  76. // TCP is reliable, UDP is not.
  77. //
  78. // With TCP, data may be "coalesced" into larger packets before transmission,
  79. // which is why you need to keep calling receive until you get the amount of
  80. // data you were expecting. (I also read that you might have to send until
  81. // all the data has been sent, which may make some sense -- you send 100 bytes,
  82. // but the system only needed 50 to "complete" the current data buffer, and so
  83. // it sends only 50 of the 100 you gave it and returns, so you have to call it
  84. // again to send the remaining 50).
  85. //
  86. // With UDP, data is NEVER coalesced, as it may be with TCP. In both cases,
  87. // data may be split up into multiple blocks based on the maximum transmission
  88. // unit (MTU). This is supposed to be transparent to the app, and it's obvious
  89. // how it would be with TCP, but I don't see how it could be with UDP since
  90. // it's supposedly unreliable.
  91. //
  92. // We can check the MTU at some point when the socket stuff hands back info
  93. // about the selected protocol (can't remember exact spot, but it exists).
  94. // Other documentation claims that there is no defined way to determine the
  95. // MTU.
  96. //
  97. // We might want to consider the user of broadcasting on LANs. We might also
  98. // consider using UDP on LAN's (doing our own sequencing and resending of data)
  99. // and TCP on WAN's. This may work well for another reason, which is that
  100. // I've read several times that TCP headers are usually compressed over PPP
  101. // links, which most people use to connect to WAN's.
  102. //
  103. // PUSH Bit Interpretation
  104. // By default, Windows NT versions 4.0 and 3.5x complete a recv() call when:
  105. // · Data arrives with the PUSH bit set.
  106. // · The user recv() buffer is full.
  107. // · 0.5 seconds have elapsed since any data arrived.
  108. // If a client program is run on a computer with a TCP/IP implementation that
  109. // does not set the PUSH bit on sends, response delays may result. It’s best
  110. // to correct this on the client side; however, a configuration parameter
  111. // (IgnorePushBitOnReceives) is added to Afd.sys to force it to treat all
  112. // arriving packets as though the PUSH bit were set.
  113. //
  114. // Delayed Acknowledgments
  115. // Per RFC 1122, TCP uses delayed acknowledgments to reduce the number of
  116. // packets sent on the media. The Microsoft stack takes a common approach
  117. // to implementing delayed acknowledgments. The following conditions cause
  118. // an acknowledgment to be sent as data is received by TCP on a given
  119. // connection:
  120. // · No ACK is sent for the previous received segment.
  121. // · Segment is received, and no other segment arrives within 200ms for that connection.
  122. // In summary, normally an ACK is sent for every other TCP segment received
  123. // on a connection, unless the delayed ACK timer (200ms) expires. There is no
  124. // configuration parameter to disable delayed ACKs.
  125. //
  126. //
  127. // THINGS TO CHANGE
  128. // ----------------
  129. //
  130. // Do we need to impliment a checksum on UDP data?
  131. //
  132. // We need to check what type of command is being cancelled via the blocking
  133. // hook. If it's an acceptable command, there's no problem. If not, then
  134. // the socket becomes unusable. It would be good if this could be done in some
  135. // way as to be transparent to the app. Then again, that might not make sense,
  136. // because if certain operations are cancelled, it might make sense that the
  137. // socket is unusable. I'm no longer sure this is really necessary. I think
  138. // the general implication should be that any time a function fails, you can
  139. // no longer use that socket, whether it failed because it was aborted or for
  140. // some other reason.
  141. //
  142. // Check into how connections are currently being terminated. Simply calling
  143. // closesocket() sounds like it would work, but I'm not sure how the other end
  144. // will react. This needs to be worked out and implimented.
  145. //
  146. // Should we allow user to specify send and recieve buffer sizes, which some
  147. // winsock implimentations support?
  148. //
  149. //////////////////////////////////////////////////////////////////////////////
  150. #include "RSPiX.h"
  151. #include "socket.h"
  152. //////////////////////////////////////////////////////////////////////////////
  153. // Macros
  154. //////////////////////////////////////////////////////////////////////////////
  155. //////////////////////////////////////////////////////////////////////////////
  156. // Static data
  157. //////////////////////////////////////////////////////////////////////////////
  158. WSADATA RProtocolBSDIP::ms_WSAData;
  159. bool RProtocolBSDIP::ms_bDidStartup;
  160. bool RProtocolBSDIP::ms_bWSAStartup;
  161. #ifdef WIN32
  162. bool RProtocolBSDIP::ms_bWSASetBlockingHook;
  163. RSocket::FuncNum RProtocolBSDIP::ms_funcnum;
  164. RSocket::BLOCK_CALLBACK RProtocolBSDIP::ms_callback;
  165. #endif
  166. //////////////////////////////////////////////////////////////////////////////
  167. // Functions
  168. //////////////////////////////////////////////////////////////////////////////
  169. //////////////////////////////////////////////////////////////////////////////
  170. // Constructor
  171. //////////////////////////////////////////////////////////////////////////////
  172. RProtocolBSDIP::RProtocolBSDIP(void)
  173. {
  174. Init();
  175. }
  176. //////////////////////////////////////////////////////////////////////////////
  177. // Destructor
  178. //////////////////////////////////////////////////////////////////////////////
  179. RProtocolBSDIP::~RProtocolBSDIP(void)
  180. {
  181. if (m_sock != INVALID_SOCKET)
  182. {
  183. TRACE("~RProtocolBSDIP(): Closing socket you forgot to, hoser!\n");
  184. Close();
  185. }
  186. }
  187. //////////////////////////////////////////////////////////////////////////////
  188. // Reset
  189. //////////////////////////////////////////////////////////////////////////////
  190. void RProtocolBSDIP::Reset(void)
  191. {
  192. Close();
  193. Init();
  194. RProtocol::Reset();
  195. }
  196. //////////////////////////////////////////////////////////////////////////////
  197. // Init
  198. //////////////////////////////////////////////////////////////////////////////
  199. void RProtocolBSDIP::Init(void)
  200. {
  201. m_sock = INVALID_SOCKET;
  202. RProtocol::Init();
  203. }
  204. //////////////////////////////////////////////////////////////////////////////
  205. // Startup socket API. This is normally called from the socket's Startup
  206. // function. Since we have multiple protocols using the same winsock
  207. // code, the Startup and Shutdown will have to be called after creating
  208. // an RSocket and before calling Open()
  209. //////////////////////////////////////////////////////////////////////////////
  210. short RProtocolBSDIP::Startup(void)
  211. {
  212. short sResult = 0;
  213. // Only do this once, but multiple calls are not considered an error
  214. if (!ms_bDidStartup)
  215. {
  216. // Startup winsock API. If this fails, the typical call the WSGetLastError() is
  217. // not supported, so there's no way to get a specific error code.
  218. if (WSAStartup(MAKEWORD(1,1), &ms_WSAData) == 0)
  219. {
  220. ms_bWSAStartup = true;
  221. #ifdef WIN32
  222. // Confirm that this winsock implimentation supports 1.1. If it supports
  223. // version greater than 1.1 in addition to 1.1, it will still return 1.1
  224. // since that's what we inquired about.
  225. if (LOBYTE(ms_WSAData.wVersion) == 1 && HIBYTE(ms_WSAData.wVersion) == 1)
  226. {
  227. // Set static hook to 0 as default
  228. ms_callback = 0;
  229. // Set our blocking hook function
  230. if (WSASetBlockingHook(RProtocolBSDIP::BlockingHook) != NULL)
  231. {
  232. ms_bWSASetBlockingHook = true;
  233. // success!
  234. ms_bDidStartup = true;
  235. // Set protocol
  236. ms_prototype = RSocket::TCPIP;
  237. }
  238. else
  239. {
  240. sResult = -1;
  241. TRACE("RProtocolBSDIP::Hook(): Error returned by WSASetBlockingHook(): %ld\n", WSAGetLastError());
  242. }
  243. }
  244. else
  245. {
  246. sResult = -1;
  247. TRACE("RProtocolBSDIP::Startup(): Incorrect version of WinSock DLL!\n");
  248. }
  249. #endif
  250. }
  251. else
  252. {
  253. sResult = -1;
  254. TRACE("RProtocolBSDIP::Startup(): Incorrect version of WinSock DLL or can't find WinSock DLL!\n");
  255. }
  256. // If there's an error, clean up after ourselves
  257. if (sResult)
  258. Shutdown();
  259. }
  260. return sResult;
  261. }
  262. //////////////////////////////////////////////////////////////////////////////
  263. // Shutdown socket API. This is normally called from the socket's Startup
  264. // function. Since we have multiple protocols using the same winsock
  265. // code, the Startup and Shutdown will have to be called after creating
  266. // an RSocket and before calling Open()
  267. //////////////////////////////////////////////////////////////////////////////
  268. void RProtocolBSDIP::Shutdown(void)
  269. {
  270. #ifdef WIN32
  271. if (ms_bWSASetBlockingHook)
  272. {
  273. // Remove blocking hook
  274. if (WSAUnhookBlockingHook() == SOCKET_ERROR)
  275. TRACE("RProtocolBSDIP::Unhook(): Error returned by WSAUnhookBlockingHook(): %ld\n", WSAGetLastError());
  276. ms_bWSASetBlockingHook = false;
  277. }
  278. #endif
  279. if (ms_bWSAStartup)
  280. {
  281. // Cleanup winsock API
  282. if (WSACleanup() == SOCKET_ERROR)
  283. TRACE("RProtocolBSDIP::Shutdown(): Error returned by WSACleanup(): %ld\n", WSAGetLastError());
  284. ms_bWSAStartup = false;
  285. }
  286. // Set protocol
  287. ms_prototype = RSocket::NO_PROTOCOL;
  288. ms_bDidStartup = false;
  289. }
  290. //////////////////////////////////////////////////////////////////////////////
  291. // Open socket
  292. // A return value of RSocket::errNotSupported means this protocol is
  293. // not supported.
  294. //////////////////////////////////////////////////////////////////////////////
  295. short RProtocolBSDIP::Open( // Returns 0 if successful, non-zero otherwise
  296. unsigned short usPort, // In: Port number or 0 for any port
  297. short sType, // In: Any one RSocket::typ* enum
  298. short sOptionFlags, // In: Any combo of RSocket::opt* enums
  299. RSocket::BLOCK_CALLBACK callback /*NULL */) // In: Blocking callback (or NULL to keep current)
  300. {
  301. #if PLATFORM_UNIX
  302. return(-1); // !!! FIXME
  303. #else
  304. short sResult = 0;
  305. // Make sure startup was called. Only this function needs to do this
  306. // because all the others check for a valid socket, which can only be
  307. // created via this function.
  308. if (ms_bDidStartup)
  309. {
  310. // Make sure socket isn't already open
  311. if (m_sock == INVALID_SOCKET)
  312. {
  313. // If callback was specified, use it.
  314. #ifdef WIN32
  315. if (callback != NULL)
  316. m_callback = callback;
  317. // Set current callback
  318. ms_callback = m_callback;
  319. #endif
  320. // Save type
  321. m_sType = sType;
  322. // Select socket type
  323. int iType;
  324. if (sType == RSocket::typStream)
  325. iType = SOCK_STREAM;
  326. else if (sType == RSocket::typDatagram)
  327. iType = SOCK_DGRAM;
  328. else
  329. {
  330. sResult = -1;
  331. TRACE("RProtocolBSDIP::Open(): Invalid type specified!\n");
  332. }
  333. if (sResult == 0)
  334. {
  335. // Create socket
  336. #ifdef WIN32
  337. ms_funcnum = RSocket::OtherFunc;
  338. #endif
  339. m_sock = socket(AF_INET, iType, 0);
  340. if (m_sock != INVALID_SOCKET)
  341. {
  342. // Set defaults
  343. m_bListening = false;
  344. m_bConnected = false;
  345. m_bConnecting = false;
  346. // Check if they want blocking turned off
  347. if (sOptionFlags & RSocket::optDontBlock)
  348. {
  349. unsigned long ulEnableNonBlockingMode = 1;
  350. if (ioctlsocket(m_sock, FIONBIO, &ulEnableNonBlockingMode) == SOCKET_ERROR)
  351. {
  352. sResult = -1;
  353. TRACE("RProtocolBSDIP::Open(): Error setting non-blocking mode, error returned by ioctlsocket(): %ld\n", WSAGetLastError());
  354. }
  355. }
  356. // Check if they want coalescing turned off
  357. if ((sOptionFlags & RSocket::optDontCoalesce) && !sResult)
  358. {
  359. if (sType == RSocket::typStream)
  360. {
  361. int optval = 1;
  362. if (setsockopt(m_sock, IPPROTO_TCP, TCP_NODELAY, (char*)&optval, sizeof(optval)) == SOCKET_ERROR)
  363. {
  364. sResult = -1;
  365. TRACE("RProtocolBSDIP::Open(): Error setting TCP_NODELAY, error returned by setsockopt(): %ld\n", WSAGetLastError());
  366. }
  367. }
  368. else
  369. {
  370. sResult = -1;
  371. TRACE("RPRotocolBSDIP::Open(): optDontCoalesce is only valid for typStream!\n");
  372. }
  373. }
  374. // Check if they want lingering turned off
  375. if ((sOptionFlags & RSocket::optDontWaitOnClose) && !sResult)
  376. {
  377. if (sType == RSocket::typStream)
  378. {
  379. int optval = 1;
  380. if (setsockopt(m_sock, SOL_SOCKET, SO_DONTLINGER, (char*)&optval, sizeof(optval)) == SOCKET_ERROR)
  381. {
  382. sResult = -1;
  383. TRACE("RProtocolBSDIP::Open(): Error setting SO_DONTLINGER, error returned by setsockopt(): %ld\n", WSAGetLastError());
  384. }
  385. }
  386. else
  387. {
  388. sResult = -1;
  389. TRACE("RPRotocolBSDIP::Open(): optDontWaitOnClose is only valid for typStream!\n");
  390. }
  391. }
  392. if (sResult == 0)
  393. {
  394. // Setup local address (any address is fine)
  395. SOCKADDR_IN addr;
  396. addr.sin_family = AF_INET;
  397. addr.sin_port = htons(usPort);
  398. addr.sin_addr.s_addr = INADDR_ANY;
  399. // Bind socket to local address
  400. if (bind(m_sock, (SOCKADDR*) &addr, sizeof(addr)) != SOCKET_ERROR)
  401. {
  402. // success
  403. }
  404. else
  405. {
  406. sResult = -1;
  407. TRACE("RProtocolBSDIP::Open(): Error returned by bind(): %ld\n", WSAGetLastError());
  408. }
  409. }
  410. // If anything went wrong, close the socket
  411. if (sResult)
  412. Close();
  413. }
  414. else
  415. {
  416. int iErr = WSAGetLastError();
  417. if (iErr == WSAEAFNOSUPPORT)
  418. sResult = RSocket::errNotSupported;
  419. else
  420. sResult = -1;
  421. TRACE("RProtocolBSDIP::Open(): Error returned by socket(): %ld\n", iErr);
  422. }
  423. }
  424. }
  425. else
  426. {
  427. sResult = -1;
  428. TRACE("RProtocolBSDIP::Open(): Socket already open!\n");
  429. }
  430. }
  431. else
  432. {
  433. sResult = -1;
  434. TRACE("RProtocolBSDIP::Open(): Didn't call WSAStartup()!\n");
  435. }
  436. return sResult;
  437. #endif
  438. }
  439. //////////////////////////////////////////////////////////////////////////////
  440. // Close socket
  441. //////////////////////////////////////////////////////////////////////////////
  442. short RProtocolBSDIP::Close( // Returns 0 if successfull, non-zero otherwise
  443. bool bForceNow /*= true */) // In: 'true' means do it now, false follows normal rules
  444. {
  445. #if PLATFORM_UNIX
  446. return(-1); // !!! FIXME
  447. #else
  448. short sResult = 0;
  449. // Only close it if it's open, but don't consider it an error if it isn't
  450. if (m_sock != INVALID_SOCKET)
  451. {
  452. // Set current callback
  453. ms_callback = m_callback;
  454. // See if they want to force this to happen RIGHT NOW
  455. if (bForceNow && (m_sType == RSocket::typStream))
  456. {
  457. // Set the "don't linger" option, which will cause the closesocket()
  458. // to return immediately, but the underlying socket implimentation will
  459. // attempt to send all unsent data before it actually closes the connection.
  460. int optval = 1;
  461. ms_funcnum = RSocket::OtherFunc;
  462. if (setsockopt(m_sock, SOL_SOCKET, SO_DONTLINGER, (char*)&optval, sizeof(optval)) == SOCKET_ERROR)
  463. {
  464. sResult = -1;
  465. TRACE("RProtocolBSDIP::Close(): Error setting SO_DONTLINGER, error returned by setsockopt(): %ld\n", WSAGetLastError());
  466. }
  467. }
  468. // If an error occurred, we can't do the close because it might block, which
  469. // is presumably the whole reason the caller asked for us to turn of lingering
  470. if (sResult == 0)
  471. {
  472. // Close socket
  473. ms_funcnum = RSocket::OtherFunc;
  474. if (closesocket(m_sock) != SOCKET_ERROR)
  475. {
  476. // Reset flags
  477. m_bListening = false;
  478. m_bConnected = false;
  479. m_bConnecting = false;
  480. // Mark it as invalid
  481. m_sock = INVALID_SOCKET;
  482. }
  483. else
  484. {
  485. int iErr = WSAGetLastError();
  486. if (iErr == WSAEWOULDBLOCK)
  487. sResult = RSocket::errWouldBlock;
  488. else
  489. {
  490. sResult = -1;
  491. TRACE("RProtocolBSDIP::Close(): Error returned by closesocket(): %ld\n", iErr);
  492. }
  493. }
  494. }
  495. }
  496. return sResult;
  497. #endif
  498. }
  499. ////////////////////////////////////////////////////////////////////////////////
  500. // Set socket to broadcast mode
  501. ////////////////////////////////////////////////////////////////////////////////
  502. short RProtocolBSDIP::Broadcast(void) // Returns 0 if successfull, non-zero otherwise
  503. {
  504. #if PLATFORM_UNIX
  505. return(-1); // !!! FIXME
  506. #else
  507. short sResult = 0;
  508. if (m_sock != INVALID_SOCKET)
  509. {
  510. if (!m_bListening)
  511. {
  512. // Set current callback
  513. ms_callback = m_callback;
  514. int optval = 1;
  515. ms_funcnum = RSocket::OtherFunc;
  516. if (setsockopt(m_sock, SOL_SOCKET, SO_BROADCAST, (char*)&optval, sizeof(optval)) == SOCKET_ERROR)
  517. {
  518. sResult = -1;
  519. TRACE("RProtocolBSDIP::Broadcast(): Error setting SO_BROADCAST, error returned by setsockopt(): %ld\n", WSAGetLastError());
  520. }
  521. }
  522. else
  523. {
  524. sResult = -1;
  525. TRACE("RProtocolBSDIP::Broadcast(): Socket is already listening!\n");
  526. }
  527. }
  528. else
  529. {
  530. sResult = -1;
  531. TRACE("RProtocolBSDIP::Broadcast(): Socket is not open!\n");
  532. }
  533. return sResult;
  534. #endif
  535. }
  536. //////////////////////////////////////////////////////////////////////////////
  537. // Set socket to listen for connection requests
  538. //
  539. // Current winsock implimentations support a maximum of 5 queued connectons.
  540. // Requesting more than 5 will cause this function to return an error.
  541. //////////////////////////////////////////////////////////////////////////////
  542. short RProtocolBSDIP::Listen( // Returns 0 if successfull, non-zero otherwise
  543. short sMaxQueued /* = 5*/) // In: Maximum number of queued connection requests
  544. {
  545. #if PLATFORM_UNIX
  546. return(-1); // !!! FIXME
  547. #else
  548. short sResult = 0;
  549. if (m_sock != INVALID_SOCKET)
  550. {
  551. if (!m_bListening)
  552. {
  553. if ((sMaxQueued >= 1) && (sMaxQueued <= 5))
  554. {
  555. // Set current callback
  556. ms_callback = m_callback;
  557. // Current winsock implimentations are silently hardwired to support
  558. // no more than 5 queued connections. They will NOT complain if you
  559. // set a higher number, but instead will silently set their internal
  560. // value to the max value (5). Note, however, that it could be less
  561. // than 5, just not greater than 5.
  562. ms_funcnum = RSocket::OtherFunc;
  563. if (listen(m_sock, (int)sMaxQueued) != SOCKET_ERROR)
  564. {
  565. // Socket is listening
  566. m_bListening = true;
  567. }
  568. else
  569. {
  570. sResult = -1;
  571. TRACE("RProtocolBSDIP::Listen(): Error returned by listen(): %ld\n", WSAGetLastError());
  572. }
  573. }
  574. else
  575. {
  576. sResult = -1;
  577. TRACE("RProtocolBSDIP::Listen(): Max queued connections must be between 1 and 5!\n");
  578. }
  579. }
  580. else
  581. {
  582. sResult = -1;
  583. TRACE("RProtocolBSDIP::Listen(): Socket is already listening!\n");
  584. }
  585. }
  586. else
  587. {
  588. sResult = -1;
  589. TRACE("RProtocolBSDIP::Listen(): Socket is not open!\n");
  590. }
  591. return sResult;
  592. #endif
  593. }
  594. //////////////////////////////////////////////////////////////////////////////
  595. // Accept request for connection
  596. //////////////////////////////////////////////////////////////////////////////
  597. short RProtocolBSDIP::Accept( // Returns 0 on success, non-zero otherwise
  598. RSocket::RProtocol* pProtocolClient, // I/O: Client protocol
  599. RSocket::Address* paddressClient) // Out: Client address
  600. {
  601. #if PLATFORM_UNIX
  602. return(-1); // !!! FIXME
  603. #else
  604. short sResult = 0;
  605. if (m_sock != INVALID_SOCKET)
  606. {
  607. if (m_bListening)
  608. {
  609. // Set current callback
  610. ms_callback = m_callback;
  611. // Make sure client socket isn't already in use
  612. if (((RProtocolBSDIP*) pProtocolClient)->m_sock == INVALID_SOCKET)
  613. {
  614. // Client address will be filled in here. Length must be set to available bytes
  615. // before calling accept().
  616. AddressIP addressClient;
  617. addressClient.prototype = RSocket::TCPIP;
  618. addressClient.lAddressLen = sizeof(addressClient.address);
  619. // Accept a client connection. If no client is pending, then this will block.
  620. // Upon return, the specified address is filled in, and the specified length
  621. // is set to the actual length of the address (in bytes).
  622. ms_funcnum = RSocket::AcceptFunc;
  623. ((RProtocolBSDIP*)pProtocolClient)->m_sock = accept(m_sock, (SOCKADDR*)&(addressClient.address), (int*)(&addressClient.lAddressLen));
  624. if (((RProtocolBSDIP*)pProtocolClient)->m_sock != INVALID_SOCKET)
  625. {
  626. // Client socket is connected
  627. pProtocolClient->m_bConnected = true;
  628. pProtocolClient->m_bConnecting = false;
  629. // If caller requested client address, return it now
  630. if (paddressClient != NULL)
  631. {
  632. // A memcpy is perfectly safe since these structs are interchangable
  633. memcpy(paddressClient, &addressClient, sizeof(RSocket::Address));
  634. }
  635. }
  636. else
  637. {
  638. int iErr = WSAGetLastError();
  639. if (iErr == WSAEWOULDBLOCK)
  640. sResult = RSocket::errWouldBlock;
  641. else
  642. {
  643. sResult = -1;
  644. TRACE("RProtocolBSDIP::AcceptClient(): Error returned by accept(): %ld\n", iErr);
  645. }
  646. }
  647. }
  648. else
  649. {
  650. sResult = -1;
  651. TRACE("RProtocolBSDIP::AcceptClient(): Specified client socket is already in use!\n");
  652. }
  653. }
  654. else
  655. {
  656. sResult = -1;
  657. TRACE("RProtocolBSDIP::AcceptClient(): Socket is not listening!\n");
  658. }
  659. }
  660. else
  661. {
  662. sResult = -1;
  663. TRACE("RProtocolBSDIP::AcceptClient(): Socket is not open!\n");
  664. }
  665. return sResult;
  666. #endif
  667. }
  668. //////////////////////////////////////////////////////////////////////////////
  669. // Connect to address
  670. //
  671. // If the RSocket::optDontBlock option was set on this socket, then this
  672. // function may return RSocket::errWouldBlock, which indicates that it is
  673. // still trying to connect, but has not yet managed to do so. In that case,
  674. // this function should be called repeatedly (polled) until it returns either
  675. // an actual error message other than RSocket::errWouldBlock, which would
  676. // indicate that the connection attempt has failed, or 0, which indicates
  677. // that it has actually connected successfully.
  678. //////////////////////////////////////////////////////////////////////////////
  679. short RProtocolBSDIP::Connect( // Returns 0 if successfull, non-zero otherwise
  680. RSocket::Address* paddress) // In: Remote address to connect to
  681. {
  682. #if PLATFORM_UNIX
  683. return(-1); // !!! FIXME
  684. #else
  685. short sResult = 0;
  686. if (m_sock != INVALID_SOCKET)
  687. {
  688. if (!m_bListening)
  689. {
  690. // Set current callback
  691. ms_callback = m_callback;
  692. // Make sure socket is not already trying to connect
  693. if (!m_bConnecting)
  694. {
  695. // Try to connect to remote socket
  696. ms_funcnum = RSocket::OtherFunc;
  697. if (connect(m_sock, (SOCKADDR*)&(paddress->address), sizeof(SOCKADDR_IN)) != SOCKET_ERROR)
  698. {
  699. // Connected!
  700. m_bConnecting = false;
  701. m_bConnected = true;
  702. }
  703. else
  704. {
  705. int iErr = WSAGetLastError();
  706. if (iErr == WSAEWOULDBLOCK)
  707. {
  708. // WSAEWOULDBLOCK indicates that connect() would have blocked. Unlike other
  709. // winsock functions, it will magically continue trying to connect!!!
  710. sResult = RSocket::errWouldBlock;
  711. m_bConnected = false;
  712. m_bConnecting = true;
  713. }
  714. else
  715. {
  716. sResult = -1;
  717. TRACE("RProtocolBSDIP::Connect(): Error returned by connect(): %ld\n", iErr);
  718. }
  719. }
  720. }
  721. else
  722. {
  723. // The socket is trying to connect, so we check whether it succeeded or failed
  724. // Create a set containing just this socket
  725. FD_SET set;
  726. FD_ZERO(&set);
  727. FD_SET(m_sock, &set);
  728. // Set time value to 0, which makes this into a polling operation
  729. TIMEVAL timeval = { 0, 0 };
  730. // Select exception/error sockets
  731. ms_funcnum = RSocket::SelectFunc;
  732. long lCount = select(0, NULL, NULL, &set, &timeval);
  733. if (lCount == 0)
  734. {
  735. // Create a set containing just this socket
  736. FD_SET set;
  737. FD_ZERO(&set);
  738. FD_SET(m_sock, &set);
  739. // Set time value to 0, which makes this into a polling operation
  740. TIMEVAL timeval = { 0, 0 };
  741. // Select writable sockets
  742. ms_funcnum = RSocket::SelectFunc;
  743. long lCount = select(0, NULL, &set, NULL, &timeval);
  744. if (lCount > 0)
  745. {
  746. // Connected!
  747. m_bConnecting = false;
  748. m_bConnected = true;
  749. }
  750. else
  751. {
  752. // Return the "would block" error, which means we're still trying to connect
  753. sResult = RSocket::errWouldBlock;
  754. }
  755. }
  756. else
  757. {
  758. // Connection attempt has failed
  759. m_bConnecting = false;
  760. m_bConnected = false;
  761. sResult = -1;
  762. TRACE("RProtocolBSDIP::Connect(): Non-blocking connection attempt has failed!\n");
  763. }
  764. }
  765. }
  766. else
  767. {
  768. sResult = -1;
  769. TRACE("RProtocolBSDIP::Connect(): Socket is listening -- can't connect!\n");
  770. }
  771. }
  772. else
  773. {
  774. sResult = -1;
  775. TRACE("RProtocolBSDIP::Connect(): Socket is not open!\n");
  776. }
  777. return sResult;
  778. #endif
  779. }
  780. //////////////////////////////////////////////////////////////////////////////
  781. // Send data to connected socket
  782. // NOTE: If an error occurs, plActualBytes will return 0.
  783. //////////////////////////////////////////////////////////////////////////////
  784. short RProtocolBSDIP::Send( // Returns 0 on success, non-zero otherwise
  785. void* pBuf, // In: Pointer to data buffer
  786. long lNumBytes, // In: Number of bytes to send
  787. long* plActualBytes) // Out: Actual number of bytes sent
  788. {
  789. #if PLATFORM_UNIX
  790. return(-1); // !!! FIXME
  791. #else
  792. short sResult = 0;
  793. if (m_sock != INVALID_SOCKET)
  794. {
  795. if (!m_bListening)
  796. {
  797. if (m_bConnected)
  798. {
  799. // Set current callback
  800. ms_callback = m_callback;
  801. // Send data
  802. ms_funcnum = RSocket::OtherFunc;
  803. *plActualBytes = send(m_sock, (char*)pBuf, lNumBytes, 0);
  804. if (*plActualBytes == SOCKET_ERROR)
  805. {
  806. *plActualBytes = 0;
  807. int iErr = WSAGetLastError();
  808. if (iErr == WSAEWOULDBLOCK)
  809. sResult = RSocket::errWouldBlock;
  810. else
  811. {
  812. sResult = -1;
  813. TRACE("RProtocolBSDIP::Send(): Error returned by send(): %ld\n", iErr);
  814. }
  815. }
  816. }
  817. else
  818. {
  819. sResult = -1;
  820. TRACE("RProtocolBSDIP::Send(): Socket not connected!\n");
  821. }
  822. }
  823. else
  824. {
  825. sResult = -1;
  826. TRACE("RProtocolBSDIP::Send(): Socket is listening -- can't send data!\n");
  827. }
  828. }
  829. else
  830. {
  831. sResult = -1;
  832. TRACE("RProtocolBSDIP::Send(): Socket is not open!\n");
  833. }
  834. return sResult;
  835. #endif
  836. }
  837. //////////////////////////////////////////////////////////////////////////////
  838. // Send data to specified address
  839. // NOTE: If an error occurs, plActualBytes will return 0.
  840. //////////////////////////////////////////////////////////////////////////////
  841. short RProtocolBSDIP::SendTo( // Returns 0 on success, non-zero otherwise
  842. void* pBuf, // In: Pointer to data buffer
  843. long lNumBytes, // In: Number of bytes to send
  844. long* plActualBytes, // Out: Actual number of bytes sent
  845. RSocket::Address* paddress) // In: Address to send to
  846. {
  847. #if PLATFORM_UNIX
  848. return(-1); // !!! FIXME
  849. #else
  850. short sResult = 0;
  851. if (m_sock != INVALID_SOCKET)
  852. {
  853. if (!m_bListening)
  854. {
  855. // Set current callback
  856. ms_callback = m_callback;
  857. // Send data
  858. ms_funcnum = RSocket::OtherFunc;
  859. *plActualBytes = sendto(m_sock, (char*)pBuf, lNumBytes, 0, (SOCKADDR*)&(paddress->address), paddress->lAddressLen);
  860. if (*plActualBytes == SOCKET_ERROR)
  861. {
  862. *plActualBytes = 0;
  863. int iErr = WSAGetLastError();
  864. if (iErr == WSAEWOULDBLOCK)
  865. sResult = RSocket::errWouldBlock;
  866. else
  867. {
  868. sResult = -1;
  869. TRACE("RProtocolBSDIP::SendTo(): Error returned by sendto(): %ld\n", iErr);
  870. }
  871. }
  872. }
  873. else
  874. {
  875. sResult = -1;
  876. TRACE("RProtocolBSDIP::SendTo(): Socket is listening -- can't send data!\n");
  877. }
  878. }
  879. else
  880. {
  881. sResult = -1;
  882. TRACE("RProtocolBSDIP::SendTo(): Socket is not open!\n");
  883. }
  884. return sResult;
  885. #endif
  886. }
  887. //////////////////////////////////////////////////////////////////////////////
  888. // Receive data - only valid with connected sockets
  889. //
  890. // For datagram (UDP) sockets, there is a one-to-one correspondence between
  891. // sends and receives. Each send implies a matching receive. The specified
  892. // buffer must at least as large as the amount of data that was sent, or the
  893. // data will be truncated and an error will be returned.
  894. //
  895. // For stream (TCP) sockets, there is no direct correspondence between sends
  896. // and receive. One send can be broken up and require multiple receives, and
  897. // and multiple sends can be coalesced into a single recieve. There is no
  898. // limitation on the amount of data being received.
  899. //
  900. // For stream (TCP) sockets, if the actual number of bytes received is 0, it
  901. // means the other end disconnected gracefully.
  902. //
  903. // In all cases, if the connection was abortively disconnected, an error will
  904. // be returned.
  905. //
  906. // NOTE: If an error occurs, plActualBytes will return 0.
  907. //////////////////////////////////////////////////////////////////////////////
  908. short RProtocolBSDIP::Receive( // Returns 0 on success, non-zero otherwise
  909. void* pBuf, // In: Pointer to data buffer
  910. long lMaxBytes, // In: Maximum number of bytes that fit in the buffer
  911. long* plActualBytes) // Out: Actual number of bytes recieved into the buffer
  912. {
  913. #if PLATFORM_UNIX
  914. return(-1); // !!! FIXME
  915. #else
  916. short sResult = 0;
  917. if (m_sock != INVALID_SOCKET)
  918. {
  919. if (!m_bListening)
  920. {
  921. if (m_bConnected)
  922. {
  923. // Set current callback
  924. ms_callback = m_callback;
  925. // Receive data
  926. ms_funcnum = RSocket::OtherFunc;
  927. *plActualBytes = recv(m_sock, (char*)pBuf, lMaxBytes, 0);
  928. if (*plActualBytes == SOCKET_ERROR)
  929. {
  930. *plActualBytes = 0;
  931. int iErr = WSAGetLastError();
  932. if (iErr == WSAEWOULDBLOCK)
  933. sResult = RSocket::errWouldBlock;
  934. else
  935. {
  936. sResult = -1;
  937. TRACE("RProtocolBSDIP::Receive(): Error returned by recv(): %ld\n", iErr);
  938. }
  939. }
  940. }
  941. else
  942. {
  943. sResult = -1;
  944. TRACE("RProtocolBSDIP::Receive(): Socket not connected!\n");
  945. }
  946. }
  947. else
  948. {
  949. sResult = -1;
  950. TRACE("RProtcolWinTcpip::Receive(): Socket is listening -- can't receive data!\n");
  951. }
  952. }
  953. else
  954. {
  955. sResult = -1;
  956. TRACE("RProtocolBSDIP::Receive(): Socket is not open!\n");
  957. }
  958. return sResult;
  959. #endif
  960. }
  961. //////////////////////////////////////////////////////////////////////////////
  962. // Receive data from the given address
  963. // NOTE: If an error occurs, plActualBytes will return 0.
  964. //////////////////////////////////////////////////////////////////////////////
  965. short RProtocolBSDIP::ReceiveFrom( // Returns 0 on success, non-zero otherwise
  966. void* pBuf, // In: Pointer to data buffer
  967. long lMaxBytes, // In: Maximum bytes that can fit in the buffer
  968. long* plActualBytes, // Out: Actual number of bytes recieved into buffer
  969. RSocket::Address* paddress) // Out: Source address returned here
  970. {
  971. #if PLATFORM_UNIX
  972. return(-1); // !!! FIXME
  973. #else
  974. short sResult = 0;
  975. if (m_sock != INVALID_SOCKET)
  976. {
  977. if (!m_bListening)
  978. {
  979. // Set current callback
  980. ms_callback = m_callback;
  981. // Source address
  982. AddressIP addr;
  983. addr.prototype = RSocket::TCPIP;
  984. addr.lAddressLen = sizeof(addr.address);
  985. // Receive data
  986. ms_funcnum = RSocket::OtherFunc;
  987. *plActualBytes = recvfrom(m_sock, (char*)pBuf, lMaxBytes, 0, (SOCKADDR*)&(addr.address), (int*)(&addr.lAddressLen));
  988. if (*plActualBytes != SOCKET_ERROR)
  989. {
  990. // If caller requested source address, return it now
  991. if (paddress != NULL)
  992. {
  993. // A memcpy is perfectly safe since these structs are interchangable
  994. memcpy(paddress, &addr, sizeof(RSocket::Address));
  995. }
  996. }
  997. else
  998. {
  999. *plActualBytes = 0;
  1000. int iErr = WSAGetLastError();
  1001. if (iErr == WSAEWOULDBLOCK)
  1002. sResult = RSocket::errWouldBlock;
  1003. else
  1004. {
  1005. sResult = -1;
  1006. TRACE("RProtocolBSDIP::ReceiveFrom(): Error returned by recvfrom(): %ld\n", iErr);
  1007. }
  1008. }
  1009. }
  1010. else
  1011. {
  1012. sResult = -1;
  1013. TRACE("RProtocolBSDIP::ReceiveFrom(): Socket is listening -- can't receive data!\n");
  1014. }
  1015. }
  1016. else
  1017. {
  1018. sResult = -1;
  1019. TRACE("RProtocolBSDIP::ReceiveFrom(): Socket is not open!\n");
  1020. }
  1021. return sResult;
  1022. #endif
  1023. }
  1024. //////////////////////////////////////////////////////////////////////////////
  1025. // Check if connection can be accepted without blocking
  1026. //////////////////////////////////////////////////////////////////////////////
  1027. bool RProtocolBSDIP::CanAcceptWithoutBlocking(void)
  1028. {
  1029. #if PLATFORM_UNIX
  1030. return(false);
  1031. #else
  1032. bool bResult = false;
  1033. if (m_sock != INVALID_SOCKET)
  1034. {
  1035. if (m_bListening)
  1036. {
  1037. // Set current callback
  1038. ms_callback = m_callback;
  1039. // Create a set containing just this socket
  1040. FD_SET set;
  1041. FD_ZERO(&set);
  1042. FD_SET(m_sock, &set);
  1043. // Set time value to 0, which makes this into a polling operation
  1044. TIMEVAL timeval = { 0, 0 };
  1045. // Select listening sockets that have actual connections pending
  1046. ms_funcnum = RSocket::SelectFunc;
  1047. long lCount = select(0, &set, NULL, NULL, &timeval);
  1048. if (lCount > 0)
  1049. bResult = true;
  1050. }
  1051. else
  1052. {
  1053. //sResult = -1;
  1054. TRACE("RProtocolBSDIP::CanAcceptWithoutBlocking(): Socket is not listening!\n");
  1055. }
  1056. }
  1057. else
  1058. {
  1059. //sResult = -1;
  1060. TRACE("RProtocolBSDIP::CanAcceptWithoutBlocking(): Socket is not open!\n");
  1061. }
  1062. return bResult;
  1063. #endif
  1064. }
  1065. //////////////////////////////////////////////////////////////////////////////
  1066. // Check if socket can send without blocking. There is no way of knowing
  1067. // how long this will be true, especially in a multi-threading environment
  1068. //////////////////////////////////////////////////////////////////////////////
  1069. bool RProtocolBSDIP::CanSendWithoutBlocking(void)
  1070. {
  1071. #if PLATFORM_UNIX
  1072. return(-1); // !!! FIXME
  1073. #else
  1074. bool bResult = false;
  1075. if (m_sock != INVALID_SOCKET)
  1076. {
  1077. if (!m_bListening)
  1078. {
  1079. // Set current callback
  1080. ms_callback = m_callback;
  1081. // Create a set containing just this socket
  1082. FD_SET set;
  1083. FD_ZERO(&set);
  1084. FD_SET(m_sock, &set);
  1085. // Set time value to 0, which makes this into a polling operation
  1086. TIMEVAL timeval = { 0, 0 };
  1087. // Select writable sockets
  1088. ms_funcnum = RSocket::SelectFunc;
  1089. long lCount = select(0, NULL, &set, NULL, &timeval);
  1090. if (lCount > 0)
  1091. bResult = true;
  1092. }
  1093. else
  1094. {
  1095. //sResult = -1;
  1096. TRACE("RProtocolBSDIP::CanSendWithoutBlocking(): Socket is listening -- can't send data!\n");
  1097. }
  1098. }
  1099. else
  1100. {
  1101. //sResult = -1;
  1102. TRACE("RProtocolBSDIP::CanSendWithoutBlocking(): Socket is not open!\n");
  1103. }
  1104. return bResult;
  1105. #endif
  1106. }
  1107. //////////////////////////////////////////////////////////////////////////////
  1108. // Check if socket can be read without blocking. For datagrams 'true' means
  1109. // queued data is available. For streams 'true' means the connection has been
  1110. // closed. If it was grecefully closed, the next read will return 0 bytes read.
  1111. // If it was aborted, the next read will return with an error.
  1112. //////////////////////////////////////////////////////////////////////////////
  1113. bool RProtocolBSDIP::CanReceiveWithoutBlocking(void)
  1114. {
  1115. #if PLATFORM_UNIX
  1116. return(-1); // !!! FIXME
  1117. #else
  1118. bool bResult = false;
  1119. if (m_sock != INVALID_SOCKET)
  1120. {
  1121. if (!m_bListening)
  1122. {
  1123. // Set current callback
  1124. ms_callback = m_callback;
  1125. // Create a set containing just this socket
  1126. FD_SET set;
  1127. FD_ZERO(&set);
  1128. FD_SET(m_sock, &set);
  1129. // Set time value to 0, which makes this into a polling operation
  1130. TIMEVAL timeval = { 0, 0 };
  1131. // Select readable sockets
  1132. ms_funcnum = RSocket::SelectFunc;
  1133. long lCount = select(0, &set, NULL, NULL, &timeval);
  1134. if (lCount > 0)
  1135. bResult = true;
  1136. }
  1137. else
  1138. {
  1139. //sResult = -1;
  1140. TRACE("RProtocolBSDIP::CanReceiveWithoutBlocking(): Socket is listening -- can't receive data!\n");
  1141. }
  1142. }
  1143. else
  1144. {
  1145. //sResult = -1;
  1146. TRACE("RProtocolBSDIP::CanReceiveWithoutBlocking(): Socket is not open!\n");
  1147. }
  1148. return bResult;
  1149. #endif
  1150. }
  1151. //////////////////////////////////////////////////////////////////////////////
  1152. // Check the number of bytes of data receivable without blocking. For
  1153. // datagrams this returns the size of the next queued datagram. For streams
  1154. // this returns the total amount of data that can be read with a single
  1155. // Receive() which is normally equal to the total amount of queued data.
  1156. //////////////////////////////////////////////////////////////////////////////
  1157. long RProtocolBSDIP::CheckReceivableBytes(void)
  1158. {
  1159. #if PLATFORM_UNIX
  1160. return(0); // !!! FIXME
  1161. #else
  1162. long lResult = 0;
  1163. if (m_sock != INVALID_SOCKET)
  1164. {
  1165. if (!m_bListening)
  1166. {
  1167. // Set current callback
  1168. ms_callback = m_callback;
  1169. // Get amount of data available for reading
  1170. ms_funcnum = RSocket::OtherFunc;
  1171. if (ioctlsocket(m_sock, FIONREAD, (unsigned long*)&lResult) == SOCKET_ERROR)
  1172. {
  1173. lResult = 0;
  1174. TRACE("RProtocolBSDIP::GetAvailableForReceive(): Error returned by ioctrlsocket(): %ld\n", WSAGetLastError());
  1175. }
  1176. }
  1177. else
  1178. {
  1179. //sResult = -1;
  1180. TRACE("RProtocolBSDIP::CanReceiveWithoutBlocking(): Socket is listening -- can't receive data!\n");
  1181. }
  1182. }
  1183. else
  1184. {
  1185. //sResult = -1;
  1186. TRACE("RProtocolBSDIP::CanReceiveWithoutBlocking(): Socket is not open!\n");
  1187. }
  1188. return lResult;
  1189. #endif
  1190. }
  1191. //////////////////////////////////////////////////////////////////////////////
  1192. // check status of protocol and this socket.
  1193. //////////////////////////////////////////////////////////////////////////////
  1194. bool RProtocolBSDIP::IsError(void)
  1195. {
  1196. #if PLATFORM_UNIX
  1197. return(true); // !!! FIXME
  1198. #else
  1199. bool bResult = false;
  1200. if (m_sock != INVALID_SOCKET)
  1201. {
  1202. // Set current callback
  1203. ms_callback = m_callback;
  1204. // Create a set containing just this socket
  1205. FD_SET set;
  1206. FD_ZERO(&set);
  1207. FD_SET(m_sock, &set);
  1208. // Set time value to 0, which makes this into a polling operation
  1209. TIMEVAL timeval = { 0, 0 };
  1210. // Select exception/error sockets
  1211. ms_funcnum = RSocket::SelectFunc;
  1212. long lCount = select(0, NULL, NULL, &set, &timeval);
  1213. if (lCount > 0)
  1214. bResult = true;
  1215. }
  1216. return bResult;
  1217. #endif
  1218. }
  1219. //////////////////////////////////////////////////////////////////////////////
  1220. // SetCallback
  1221. //////////////////////////////////////////////////////////////////////////////
  1222. void RProtocolBSDIP::SetCallback(
  1223. RSocket::BLOCK_CALLBACK callback)
  1224. {
  1225. m_callback = callback;
  1226. }
  1227. //////////////////////////////////////////////////////////////////////////////
  1228. // GetCallback
  1229. //////////////////////////////////////////////////////////////////////////////
  1230. RSocket::BLOCK_CALLBACK RProtocolBSDIP::GetCallback(void)
  1231. {
  1232. return m_callback;
  1233. }
  1234. //////////////////////////////////////////////////////////////////////////////
  1235. // GetMaxDatagramSize
  1236. //////////////////////////////////////////////////////////////////////////////
  1237. /* static */
  1238. short RProtocolBSDIP::GetMaxDatagramSize( // Returns zero on success, non-zero otherwise
  1239. long* plSize) // Out: Maximum datagram size in bytes
  1240. {
  1241. short sResult = 0;
  1242. #ifdef WIN32
  1243. if (ms_bDidStartup)
  1244. {
  1245. *plSize = (long)ms_WSAData.iMaxUdpDg;
  1246. }
  1247. else
  1248. {
  1249. sResult = -1;
  1250. TRACE("RProtocolBSDIP::GetMaxDatagramSize(): Never called Startup()!\n");
  1251. }
  1252. #else
  1253. *plSize = 1024; // uh, sure.
  1254. #endif
  1255. return sResult;
  1256. }
  1257. //////////////////////////////////////////////////////////////////////////////
  1258. // Get maximum number of sockets. This may be a system "global" value, which
  1259. // means that if other applications are using sockets, then the number
  1260. // available to this application may be lower than the returned value.
  1261. //////////////////////////////////////////////////////////////////////////////
  1262. /* static */
  1263. short RProtocolBSDIP::GetMaxSockets( // Returns 0 if successfull, non-zero otherwise
  1264. long* plNum) // Out: maximum number of sockets
  1265. {
  1266. short sResult = 0;
  1267. #ifdef WIN32
  1268. if (ms_bDidStartup)
  1269. {
  1270. *plNum = (long)ms_WSAData.iMaxSockets;
  1271. }
  1272. else
  1273. {
  1274. sResult = -1;
  1275. TRACE("RProtocolBSDIP::GetMaxSockets(): Never called Startup()!\n");
  1276. }
  1277. #else
  1278. *plNum = 25; // uh...ok.
  1279. #endif
  1280. return sResult;
  1281. }
  1282. //////////////////////////////////////////////////////////////////////////////
  1283. // Get the address of the specified host from the string provided which may be
  1284. // a name or address
  1285. //////////////////////////////////////////////////////////////////////////////
  1286. /* static */
  1287. short RProtocolBSDIP::GetAddress( // Returns 0 if successfull, non-zero otherwise
  1288. char* pszName, // In: Host's name or dotted address (x.x.x.x)
  1289. USHORT usPort, // In: Host's port number
  1290. RSocket::Address* paddress) // Out: Address
  1291. {
  1292. #if PLATFORM_UNIX
  1293. return(-1); // !!! FIXME
  1294. #else
  1295. short sResult = 0;
  1296. if (ms_bDidStartup)
  1297. {
  1298. // Cast address to IP address to make it easier to work with
  1299. AddressIP* pip = (AddressIP*)paddress;
  1300. // If the string contains only digits and/or dots and there's at least one dot
  1301. // then we assume it's a dotted address.
  1302. if ((strspn(pszName, "0123456789.") >= strlen(pszName)) && (strchr(pszName, '.') != NULL))
  1303. {
  1304. // Convert dotted address into value (returned in network order!)
  1305. unsigned long ulAddr = inet_addr(pszName);
  1306. if (ulAddr != INADDR_NONE)
  1307. {
  1308. // Fill in the address
  1309. pip->prototype = RSocket::TCPIP;
  1310. pip->lAddressLen = sizeof(pip->address);
  1311. pip->address.sin_family = AF_INET;
  1312. pip->address.sin_addr.S_un.S_addr = ulAddr;
  1313. pip->address.sin_port = htons(usPort);
  1314. }
  1315. else
  1316. {
  1317. sResult = -1;
  1318. TRACE("RProtocolBSDIP::GetAddress(): Invalid dotted address: %s\n", pszName);
  1319. }
  1320. }
  1321. else
  1322. {
  1323. // Lookup address based on specified name
  1324. ms_funcnum = RSocket::OtherFunc;
  1325. HOSTENT* phost = gethostbyname(pszName);
  1326. if (phost != NULL)
  1327. {
  1328. // Fill in the address
  1329. pip->prototype = RSocket::TCPIP;
  1330. pip->lAddressLen = sizeof(pip->address);
  1331. pip->address.sin_family = phost->h_addrtype;
  1332. memcpy((char*)&(pip->address.sin_addr), phost->h_addr_list[0], phost->h_length);
  1333. pip->address.sin_port = htons(usPort);
  1334. }
  1335. else
  1336. {
  1337. sResult = -1;
  1338. TRACE("RProtocolBSDIP::GetAddress(): Error returned by gethostbyname(): %ld\n", WSAGetLastError());
  1339. }
  1340. }
  1341. }
  1342. else
  1343. {
  1344. sResult = -1;
  1345. TRACE("RProtocolBSDIP::GetHostAddress(): Never called Startup()!\n");
  1346. }
  1347. return sResult;
  1348. #endif
  1349. }
  1350. ////////////////////////////////////////////////////////////////////////////////
  1351. // Create broadcast address using specified port
  1352. ////////////////////////////////////////////////////////////////////////////////
  1353. // static
  1354. void RProtocolBSDIP::CreateBroadcastAddress(
  1355. unsigned short usPort, // In: Port to broadcast to
  1356. RSocket::Address* paddress) // Out: Broadcast address returned here
  1357. {
  1358. // Cast address to IP address to make it easier to work with
  1359. AddressIP* pip = (AddressIP*)paddress;
  1360. // Create broadcast address using specified port
  1361. pip->prototype = RSocket::TCPIP;
  1362. pip->lAddressLen = sizeof(pip->address);
  1363. pip->address.sin_family = AF_INET;
  1364. pip->address.sin_port = htons(usPort);
  1365. #ifdef WIN32
  1366. pip->address.sin_addr.S_un.S_addr = htonl(INADDR_BROADCAST);
  1367. #else
  1368. pip->address.sin_addr.s_addr = htonl(INADDR_BROADCAST);
  1369. #endif
  1370. }
  1371. //////////////////////////////////////////////////////////////////////////////
  1372. // Get the specified address' current port number
  1373. //////////////////////////////////////////////////////////////////////////////
  1374. /* static */
  1375. unsigned short RProtocolBSDIP::GetAddressPort( // Returns port number
  1376. RSocket::Address* paddress) // In: Address from which to get port
  1377. {
  1378. PSOCKADDR_IN pin = (PSOCKADDR_IN) &(paddress->address);
  1379. return ntohs(pin->sin_port);
  1380. }
  1381. //////////////////////////////////////////////////////////////////////////////
  1382. // Set the specified address' port to the specified value
  1383. //////////////////////////////////////////////////////////////////////////////
  1384. /* static */
  1385. void RProtocolBSDIP::SetAddressPort(
  1386. USHORT usPort, // In: New port number
  1387. RSocket::Address* paddress) // I/O: Address who's port is to be set
  1388. {
  1389. PSOCKADDR_IN pin = (PSOCKADDR_IN) &(paddress->address);
  1390. pin->sin_port = htons(usPort);
  1391. }
  1392. ////////////////////////////////////////////////////////////////////////////////
  1393. // This is a blocking-hook callback function.
  1394. // The winsock code will call this repeatedly while the return value is
  1395. // non-zero, but the documentation implies that it doesn't do anything else
  1396. // while calling this, so it seems like a better idea to return 0 all the time.
  1397. ////////////////////////////////////////////////////////////////////////////////
  1398. /* static */
  1399. #ifdef WIN32
  1400. int CALLBACK RProtocolBSDIP::BlockingHook(void)
  1401. {
  1402. // !!!
  1403. // The only Windows Socket API function you can call from this
  1404. // function is WSACancelBlockingCall()
  1405. // !!!
  1406. // Call user-installed callback. If return value is non-zero, cancel
  1407. // the current blocking call.
  1408. if (ms_callback != 0)
  1409. {
  1410. if ((*ms_callback)() != 0)
  1411. {
  1412. // Cancelling accept() or select() is fine -- only that particular
  1413. // operation will fail, and the socket itself will be unaffected.
  1414. // Cancelling any other operation will leave the socket in an unknown/
  1415. // unstable state. The only function you can call after cancelling
  1416. // operations other than accept() or select() is closesocket().
  1417. WSACancelBlockingCall();
  1418. }
  1419. }
  1420. return 0;
  1421. }
  1422. #endif
  1423. //////////////////////////////////////////////////////////////////////////////
  1424. // EOF
  1425. //////////////////////////////////////////////////////////////////////////////