PageRenderTime 56ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/libretroshare/src/pqi/pqissl.cc

https://gitlab.com/g10h4ck/RetroShare
C++ | 1958 lines | 1322 code | 358 blank | 278 comment | 161 complexity | 8a7d24fc22b3c818345b8c337f034e5b MD5 | raw file
Possible License(s): 0BSD, GPL-2.0, AGPL-1.0
  1. /*
  2. * "$Id: pqissl.cc,v 1.28 2007-03-17 19:32:59 rmf24 Exp $"
  3. *
  4. * 3P/PQI network interface for RetroShare.
  5. *
  6. * Copyright 2004-2006 by Robert Fernie.
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Library General Public
  10. * License Version 2 as published by the Free Software Foundation.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Library General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Library General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  20. * USA.
  21. *
  22. * Please report all bugs and problems to "retroshare@lunamutt.com".
  23. *
  24. */
  25. #include "pqi/pqissl.h"
  26. #include "pqi/pqinetwork.h"
  27. #include "pqi/sslfns.h"
  28. #include "util/rsnet.h"
  29. #include "util/rsdebug.h"
  30. #include "util/rsstring.h"
  31. #include <unistd.h>
  32. #include <errno.h>
  33. #include <openssl/err.h>
  34. #include "pqi/pqissllistener.h"
  35. #include "pqi/p3linkmgr.h"
  36. #include <retroshare/rspeers.h>
  37. #include <retroshare/rsdht.h>
  38. #include <retroshare/rsbanlist.h>
  39. #include "rsserver/p3face.h"
  40. const int pqisslzone = 37714;
  41. /*********
  42. #define WAITING_NOT 0
  43. #define WAITING_LOCAL_ADDR 1
  44. #define WAITING_REMOTE_ADDR 2
  45. #define WAITING_SOCK_CONNECT 3
  46. #define WAITING_SSL_CONNECTION 4
  47. #define WAITING_SSL_AUTHORISE 5
  48. #define WAITING_FAIL_INTERFACE 6
  49. #define PQISSL_PASSIVE 0x00
  50. #define PQISSL_ACTIVE 0x01
  51. #define PQISSL_DEBUG 1
  52. #define PQISSL_LOG_DEBUG 1
  53. const int PQISSL_LOCAL_FLAG = 0x01;
  54. const int PQISSL_REMOTE_FLAG = 0x02;
  55. const int PQISSL_UDP_FLAG = 0x02;
  56. ***********/
  57. static const int PQISSL_MAX_READ_ZERO_COUNT = 20;
  58. static const time_t PQISSL_MAX_READ_ZERO_TIME = 15; // 15 seconds of no data => reset. (atm HeartBeat pkt sent 5 secs)
  59. static const int PQISSL_SSL_CONNECT_TIMEOUT = 30;
  60. /********** PQI SSL STUFF ******************************************
  61. *
  62. * A little note on the notifyEvent(FAILED)....
  63. *
  64. * this is called from
  65. * (1) reset if needed!
  66. * (2) Determine_Remote_Address (when all options have failed).
  67. *
  68. * reset() is only called when a TCP/SSL connection has been
  69. * established, and there is an error. If there is a failed TCP
  70. * connection, then an alternative address can be attempted.
  71. *
  72. * reset() is called from
  73. * (1) destruction.
  74. * (2) disconnect()
  75. * (3) bad waiting state.
  76. *
  77. * // TCP/or SSL connection already established....
  78. * (5) pqissl::SSL_Connection_Complete() <- okay -> cos we made a TCP connection already.
  79. * (6) pqissl::accept() <- okay cos something went wrong.
  80. * (7) moretoread()/cansend() <- okay cos
  81. *
  82. */
  83. pqissl::pqissl(pqissllistener *l, PQInterface *parent, p3LinkMgr *lm)
  84. :NetBinInterface(parent, parent->PeerId()),
  85. mLinkMgr(lm), pqil(l),
  86. mSslMtx("pqissl"),
  87. active(false), certvalid(false), waiting(WAITING_NOT),
  88. sslmode(PQISSL_ACTIVE), ssl_connection(NULL), sockfd(-1),
  89. readpkt(NULL), pktlen(0), total_len(0),
  90. attempt_ts(0),
  91. n_read_zero(0), mReadZeroTS(0), ssl_connect_timeout(0),
  92. mConnectDelay(0), mConnectTS(0),
  93. mConnectTimeout(0), mTimeoutTS(0)
  94. {
  95. RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/
  96. /* set address to zero */
  97. sockaddr_storage_clear(remote_addr);
  98. #ifdef PQISSL_LOG_DEBUG
  99. rslog(RSL_DEBUG_BASIC, pqisslzone, "pqissl for PeerId: " + PeerId());
  100. #endif
  101. #if 0
  102. if (!(AuthSSL::getAuthSSL()->isAuthenticated(PeerId())))
  103. {
  104. rslog(RSL_ALERT, pqisslzone,
  105. "pqissl::Warning Certificate Not Approved!");
  106. rslog(RSL_ALERT, pqisslzone,
  107. "\t pqissl will not initialise....");
  108. }
  109. #else
  110. rslog(RSL_DEBUG_BASIC, pqisslzone,
  111. "pqissl::Warning SSL Certificate Approval Not CHECKED??");
  112. #endif
  113. return;
  114. }
  115. pqissl::~pqissl()
  116. {
  117. rslog(RSL_ALERT, pqisslzone,
  118. "pqissl::~pqissl -> destroying pqissl");
  119. stoplistening(); /* remove from pqissllistener only */
  120. rslog(RSL_ALERT, pqisslzone, "pqissl::~pqissl() -> calling reset()");
  121. reset();
  122. return;
  123. }
  124. /********** Implementation of NetInterface *************************/
  125. int pqissl::connect(const struct sockaddr_storage &raddr)
  126. {
  127. RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/
  128. // reset failures
  129. remote_addr = raddr;
  130. return ConnectAttempt();
  131. }
  132. // tells pqilistener to listen for us.
  133. int pqissl::listen()
  134. {
  135. if (pqil)
  136. {
  137. return pqil -> addlistenaddr(PeerId(), this);
  138. }
  139. return 0;
  140. }
  141. int pqissl::stoplistening()
  142. {
  143. if (pqil)
  144. {
  145. pqil -> removeListenPort(PeerId());
  146. }
  147. return 1;
  148. }
  149. int pqissl::disconnect()
  150. {
  151. rslog(RSL_ALERT, pqisslzone, "pqissl::disconnect() -> calling reset()");
  152. return reset();
  153. }
  154. int pqissl::getConnectAddress(struct sockaddr_storage &raddr)
  155. {
  156. RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/
  157. raddr = remote_addr;
  158. // TODO.
  159. return (!sockaddr_storage_isnull(remote_addr));
  160. }
  161. /* BinInterface version of reset() for pqistreamer */
  162. int pqissl::close()
  163. {
  164. rslog(RSL_ALERT, pqisslzone, "pqissl::close() -> calling reset()");
  165. return reset();
  166. }
  167. // put back on the listening queue.
  168. int pqissl::reset()
  169. {
  170. RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/
  171. return reset_locked();
  172. }
  173. int pqissl::reset_locked()
  174. {
  175. std::string outLog;
  176. bool neededReset = false;
  177. /* a reset shouldn't cause us to stop listening
  178. * only reasons for stoplistening() are;
  179. *
  180. * (1) destruction.
  181. * (2) connection.
  182. * (3) WillListen state change
  183. *
  184. */
  185. outLog += "pqissl::reset():" + PeerId().toStdString();
  186. rs_sprintf_append(outLog, " (A: %d", (int) active);
  187. rs_sprintf_append(outLog, " FD: %d", sockfd);
  188. rs_sprintf_append(outLog, " W: %d", waiting);
  189. rs_sprintf_append(outLog, " SSL: %p) ", ssl_connection);
  190. #ifdef PQISSL_LOG_DEBUG
  191. outLog += "\n";
  192. #endif
  193. if (ssl_connection != NULL)
  194. {
  195. //outLog << "pqissl::reset() Shutting down SSL Connection";
  196. //outLog << std::endl;
  197. SSL_shutdown(ssl_connection);
  198. SSL_free (ssl_connection);
  199. neededReset = true;
  200. }
  201. if (sockfd > 0)
  202. {
  203. #ifdef PQISSL_LOG_DEBUG
  204. outLog += "pqissl::reset() Shutting down (active) socket\n";
  205. #endif
  206. net_internal_close(sockfd);
  207. sockfd = -1;
  208. neededReset = true;
  209. }
  210. active = false;
  211. sockfd = -1;
  212. waiting = WAITING_NOT;
  213. ssl_connection = NULL;
  214. n_read_zero = 0;
  215. mReadZeroTS = 0;
  216. total_len = 0 ;
  217. mTimeoutTS = 0;
  218. if (neededReset)
  219. {
  220. #ifdef PQISSL_LOG_DEBUG
  221. outLog += "pqissl::reset() Reset Required!\n";
  222. outLog += "pqissl::reset() Will Attempt notifyEvent(FAILED)\n";
  223. #endif
  224. }
  225. rslog(RSL_ALERT, pqisslzone, outLog);
  226. // notify people of problem!
  227. // but only if we really shut something down.
  228. if (neededReset)
  229. {
  230. // clean up the streamer
  231. if (parent())
  232. {
  233. struct sockaddr_storage addr;
  234. sockaddr_storage_clear(addr);
  235. parent() -> notifyEvent(this, NET_CONNECT_FAILED, addr);
  236. }
  237. }
  238. return 1;
  239. }
  240. bool pqissl::connect_parameter(uint32_t type, uint32_t value)
  241. {
  242. #ifdef PQISSL_LOG_DEBUG
  243. std::cerr << "pqissl::connect_parameter() Peer: " << PeerId();
  244. #endif
  245. switch(type)
  246. {
  247. case NET_PARAM_CONNECT_DELAY:
  248. {
  249. #ifdef PQISSL_LOG_DEBUG
  250. std::cerr << " DELAY: " << value << std::endl;
  251. #endif
  252. RS_STACK_MUTEX(mSslMtx);
  253. mConnectDelay = value;
  254. return true;
  255. }
  256. case NET_PARAM_CONNECT_TIMEOUT:
  257. {
  258. #ifdef PQISSL_LOG_DEBUG
  259. std::cerr << " TIMEOUT: " << value << std::endl;
  260. #endif
  261. RS_STACK_MUTEX(mSslMtx);
  262. mConnectTimeout = value;
  263. return true;
  264. }
  265. default:
  266. {
  267. #ifdef PQISSL_LOG_DEBUG
  268. std::cerr << " type: " << type << " value: " << value << std::endl;
  269. #endif
  270. return false;
  271. }
  272. }
  273. }
  274. /********** End of Implementation of NetInterface ******************/
  275. /********** Implementation of BinInterface **************************
  276. * Only status() + tick() are here ... as they are really related
  277. * to the NetInterface, and not the BinInterface,
  278. *
  279. */
  280. void pqissl::getCryptoParams(RsPeerCryptoParams& params)
  281. {
  282. RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/
  283. if(active)
  284. {
  285. params.connexion_state = 1 ;
  286. params.cipher_name = std::string( SSL_get_cipher(ssl_connection));
  287. int alg ;
  288. int al2 = SSL_get_cipher_bits(ssl_connection,&alg);
  289. params.cipher_bits_1 = alg ;
  290. params.cipher_bits_2 = al2 ;
  291. char *desc = SSL_CIPHER_description(SSL_get_current_cipher(ssl_connection), NULL, 0);
  292. params.cipher_version = std::string(desc).find("TLSv1.2") != std::string::npos ? std::string("TLSv1.2") : std::string("TLSv1");
  293. OPENSSL_free(desc);
  294. }
  295. else
  296. {
  297. params.connexion_state = 0 ;
  298. params.cipher_name.clear() ;
  299. params.cipher_bits_1 = 0 ;
  300. params.cipher_bits_2 = 0 ;
  301. params.cipher_version.clear() ;
  302. }
  303. }
  304. bool pqissl::actAsServer()
  305. {
  306. return (bool)ssl_connection->server;
  307. }
  308. /* returns ...
  309. * -1 if inactive.
  310. * 0 if connecting.
  311. * 1 if connected.
  312. */
  313. int pqissl::status()
  314. {
  315. RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/
  316. #ifdef PQISSL_LOG_DEBUG
  317. std::string out = "pqissl::status()";
  318. if (active)
  319. {
  320. int alg;
  321. out += " active: \n";
  322. // print out connection.
  323. out += "Connected TO : " + PeerId() + "\n";
  324. // print out cipher.
  325. rs_sprintf_append(out, "\t\tSSL Cipher:%s", SSL_get_cipher(ssl_connection));
  326. rs_sprintf_append(out, " (%d:%d)", SSL_get_cipher_bits(ssl_connection, &alg), alg);
  327. rs_sprintf_append(out, "Vers:%s\n\n", SSL_get_cipher_version(ssl_connection));
  328. }
  329. else
  330. {
  331. out += " Waiting for connection!\n";
  332. }
  333. rslog(RSL_DEBUG_BASIC, pqisslzone, out);
  334. #endif
  335. if (active)
  336. {
  337. return 1;
  338. }
  339. else if (waiting > 0)
  340. {
  341. return 0;
  342. }
  343. return -1;
  344. }
  345. // tick......
  346. int pqissl::tick()
  347. {
  348. RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/
  349. //pqistreamer::tick();
  350. // continue existing connection attempt.
  351. if (!active)
  352. {
  353. // if we are waiting.. continue the connection (only)
  354. if (waiting > 0)
  355. {
  356. #ifdef PQISSL_LOG_DEBUG
  357. rslog(RSL_DEBUG_BASIC, pqisslzone, "pqissl::tick() Continuing Connection Attempt!");
  358. #endif
  359. ConnectAttempt();
  360. return 1;
  361. }
  362. }
  363. return 1;
  364. }
  365. /********** End of Implementation of BinInterface ******************/
  366. /********** Internals of SSL Connection ****************************/
  367. int pqissl::ConnectAttempt()
  368. {
  369. switch(waiting)
  370. {
  371. case WAITING_NOT:
  372. sslmode = PQISSL_ACTIVE; /* we're starting this one */
  373. #ifdef PQISSL_LOG_DEBUG
  374. rslog(RSL_DEBUG_BASIC, pqisslzone,
  375. "pqissl::ConnectAttempt() STATE = Not Waiting, starting connection");
  376. #endif
  377. case WAITING_DELAY:
  378. #ifdef PQISSL_LOG_DEBUG
  379. rslog(RSL_DEBUG_BASIC, pqisslzone,
  380. "pqissl::ConnectAttempt() STATE = Waiting Delay, starting connection");
  381. #endif
  382. return Delay_Connection();
  383. //return Initiate_Connection(); /* now called by Delay_Connection() */
  384. break;
  385. case WAITING_SOCK_CONNECT:
  386. #ifdef PQISSL_LOG_DEBUG
  387. rslog(RSL_DEBUG_BASIC, pqisslzone,
  388. "pqissl::ConnectAttempt() STATE = Waiting Sock Connect");
  389. #endif
  390. return Initiate_SSL_Connection();
  391. break;
  392. case WAITING_SSL_CONNECTION:
  393. #ifdef PQISSL_LOG_DEBUG
  394. rslog(RSL_DEBUG_BASIC, pqisslzone,
  395. "pqissl::ConnectAttempt() STATE = Waiting SSL Connection");
  396. #endif
  397. return Authorise_SSL_Connection();
  398. break;
  399. case WAITING_SSL_AUTHORISE:
  400. #ifdef PQISSL_LOG_DEBUG
  401. rslog(RSL_DEBUG_BASIC, pqisslzone,
  402. "pqissl::ConnectAttempt() STATE = Waiting SSL Authorise");
  403. #endif
  404. return Authorise_SSL_Connection();
  405. break;
  406. case WAITING_FAIL_INTERFACE:
  407. #ifdef PQISSL_LOG_DEBUG
  408. rslog(RSL_DEBUG_BASIC, pqisslzone,
  409. "pqissl::ConnectAttempt() Failed - Retrying");
  410. #endif
  411. return Failed_Connection();
  412. break;
  413. default:
  414. rslog(RSL_ALERT, pqisslzone,
  415. "pqissl::ConnectAttempt() STATE = Unknown - calling reset()");
  416. reset_locked();
  417. break;
  418. }
  419. rslog(RSL_ALERT, pqisslzone, "pqissl::ConnectAttempt() Unknown");
  420. return -1;
  421. }
  422. /****************************** FAILED ATTEMPT ******************************
  423. * Determine the Remote Address.
  424. *
  425. * Specifics:
  426. * TCP / UDP
  427. * TCP - check for which interface to use.
  428. * UDP - check for request proxies....
  429. *
  430. * X509 / XPGP - Same.
  431. *
  432. */
  433. int pqissl::Failed_Connection()
  434. {
  435. #ifdef PQISSL_LOG_DEBUG
  436. rslog(RSL_DEBUG_BASIC, pqisslzone,
  437. "pqissl::ConnectAttempt() Failed - Notifying");
  438. #endif
  439. if (parent())
  440. {
  441. struct sockaddr_storage addr;
  442. sockaddr_storage_clear(addr);
  443. parent() -> notifyEvent(this, NET_CONNECT_UNREACHABLE, addr);
  444. }
  445. waiting = WAITING_NOT;
  446. return 1;
  447. }
  448. /****************************** MAKE CONNECTION *****************************
  449. * Open Socket and Initiate Connection.
  450. *
  451. * Specifics:
  452. * TCP / UDP
  453. * TCP - socket()/connect()
  454. * UDP - tou_socket()/tou_connect()
  455. *
  456. * X509 / XPGP - Same.
  457. *
  458. */
  459. int pqissl::Delay_Connection()
  460. {
  461. #ifdef PQISSL_LOG_DEBUG
  462. rslog(RSL_DEBUG_BASIC, pqisslzone,
  463. "pqissl::Delay_Connection() Attempting Outgoing Connection....");
  464. #endif
  465. if (waiting == WAITING_NOT)
  466. {
  467. waiting = WAITING_DELAY;
  468. /* we cannot just jump to Initiate_Connection,
  469. * but must switch to WAITING_DELAY for at least one cycle.
  470. * to avoid deadlock between threads....
  471. * ie. so the connection stuff is called from tick(), rather than connect()
  472. */
  473. /* set Connection TS.
  474. */
  475. #ifdef PQISSL_LOG_DEBUG
  476. {
  477. std::string out;
  478. rs_sprintf(out, "pqissl::Delay_Connection() Delaying Connection to %s for %lu seconds", PeerId().c_str(), mConnectDelay);
  479. rslog(RSL_DEBUG_BASIC, pqisslzone, out);
  480. }
  481. #endif
  482. mConnectTS = time(NULL) + mConnectDelay;
  483. return 0;
  484. }
  485. else if (waiting == WAITING_DELAY)
  486. {
  487. #ifdef PQISSL_LOG_DEBUG
  488. {
  489. std::string out;
  490. rs_sprintf(out, "pqissl::Delay_Connection() Connection to %s starting in %ld seconds", PeerId().c_str(), mConnectTS - time(NULL));
  491. rslog(RSL_DEBUG_BASIC, pqisslzone, out);
  492. }
  493. #endif
  494. if (time(NULL) >= mConnectTS)
  495. {
  496. return Initiate_Connection();
  497. }
  498. return 0;
  499. }
  500. rslog(RSL_WARNING, pqisslzone,
  501. "pqissl::Initiate_Connection() Already Attempt in Progress!");
  502. return -1;
  503. }
  504. int pqissl::Initiate_Connection()
  505. {
  506. int err;
  507. struct sockaddr_storage addr = remote_addr;
  508. #ifdef PQISSL_LOG_DEBUG
  509. rslog(RSL_DEBUG_BASIC, pqisslzone,
  510. "pqissl::Initiate_Connection() Attempting Outgoing Connection....");
  511. #endif
  512. if (waiting != WAITING_DELAY)
  513. {
  514. rslog(RSL_WARNING, pqisslzone,
  515. "pqissl::Initiate_Connection() Already Attempt in Progress!");
  516. return -1;
  517. }
  518. #ifdef PQISSL_LOG_DEBUG
  519. rslog(RSL_DEBUG_BASIC, pqisslzone,
  520. "pqissl::Initiate_Connection() Opening Socket");
  521. #endif
  522. // open socket connection to addr.
  523. int osock = unix_socket(PF_INET, SOCK_STREAM, 0);
  524. #ifdef PQISSL_LOG_DEBUG
  525. {
  526. std::string out;
  527. rs_sprintf(out, "pqissl::Initiate_Connection() osock = %d", osock);
  528. rslog(RSL_DEBUG_BASIC, pqisslzone, out);
  529. }
  530. #endif
  531. if (osock < 0)
  532. {
  533. std::string out = "pqissl::Initiate_Connection() Failed to open socket!\n";
  534. out += "Socket Error:" + socket_errorType(errno);
  535. rslog(RSL_WARNING, pqisslzone, out);
  536. net_internal_close(osock);
  537. waiting = WAITING_FAIL_INTERFACE;
  538. return -1;
  539. }
  540. #ifdef PQISSL_LOG_DEBUG
  541. rslog(RSL_DEBUG_BASIC, pqisslzone,
  542. "pqissl::Initiate_Connection() Making Non-Blocking");
  543. #endif
  544. err = unix_fcntl_nonblock(osock);
  545. if (err < 0)
  546. {
  547. std::string out;
  548. rs_sprintf(out, "pqissl::Initiate_Connection() Error: Cannot make socket NON-Blocking: %d", err);
  549. rslog(RSL_WARNING, pqisslzone, out);
  550. waiting = WAITING_FAIL_INTERFACE;
  551. net_internal_close(osock);
  552. return -1;
  553. }
  554. {
  555. std::string out;
  556. rs_sprintf(out, "pqissl::Initiate_Connection() Connecting To: %s via: ", PeerId().toStdString().c_str());
  557. out += sockaddr_storage_tostring(addr);
  558. rslog(RSL_WARNING, pqisslzone, out);
  559. }
  560. if (sockaddr_storage_isnull(addr))
  561. {
  562. rslog(RSL_WARNING, pqisslzone, "pqissl::Initiate_Connection() Invalid (0.0.0.0) Remote Address, Aborting Connect.");
  563. waiting = WAITING_FAIL_INTERFACE;
  564. net_internal_close(osock);
  565. return -1;
  566. }
  567. #ifdef WINDOWS_SYS
  568. /* Set TCP buffer size for Windows systems */
  569. int sockbufsize = 0;
  570. int size = sizeof(int);
  571. err = getsockopt(osock, SOL_SOCKET, SO_RCVBUF, (char *)&sockbufsize, &size);
  572. #ifdef PQISSL_DEBUG
  573. if (err == 0) {
  574. std::cerr << "pqissl::Initiate_Connection: Current TCP receive buffer size " << sockbufsize << std::endl;
  575. } else {
  576. std::cerr << "pqissl::Initiate_Connection: Error getting TCP receive buffer size. Error " << err << std::endl;
  577. }
  578. #endif
  579. sockbufsize = 0;
  580. err = getsockopt(osock, SOL_SOCKET, SO_SNDBUF, (char *)&sockbufsize, &size);
  581. #ifdef PQISSL_DEBUG
  582. if (err == 0) {
  583. std::cerr << "pqissl::Initiate_Connection: Current TCP send buffer size " << sockbufsize << std::endl;
  584. } else {
  585. std::cerr << "pqissl::Initiate_Connection: Error getting TCP send buffer size. Error " << err << std::endl;
  586. }
  587. #endif
  588. sockbufsize = WINDOWS_TCP_BUFFER_SIZE;
  589. err = setsockopt(osock, SOL_SOCKET, SO_RCVBUF, (char *)&sockbufsize, sizeof(sockbufsize));
  590. #ifdef PQISSL_DEBUG
  591. if (err == 0) {
  592. std::cerr << "pqissl::Initiate_Connection: TCP receive buffer size set to " << sockbufsize << std::endl;
  593. } else {
  594. std::cerr << "pqissl::Initiate_Connection: Error setting TCP receive buffer size. Error " << err << std::endl;
  595. }
  596. #endif
  597. err = setsockopt(osock, SOL_SOCKET, SO_SNDBUF, (char *)&sockbufsize, sizeof(sockbufsize));
  598. #ifdef PQISSL_DEBUG
  599. if (err == 0) {
  600. std::cerr << "pqissl::Initiate_Connection: TCP send buffer size set to " << sockbufsize << std::endl;
  601. } else {
  602. std::cerr << "pqissl::Initiate_Connection: Error setting TCP send buffer size. Error " << err << std::endl;
  603. }
  604. #endif
  605. #endif // WINDOWS_SYS
  606. mTimeoutTS = time(NULL) + mConnectTimeout;
  607. //std::cerr << "Setting Connect Timeout " << mConnectTimeout << " Seconds into Future " << std::endl;
  608. if (0 != (err = unix_connect(osock, (struct sockaddr *) &addr, sizeof(addr))))
  609. {
  610. std::string out;
  611. rs_sprintf(out, "pqissl::Initiate_Connection() connect returns:%d -> errno: %d error: %s\n", err, errno, socket_errorType(errno).c_str());
  612. if (errno == EINPROGRESS)
  613. {
  614. // set state to waiting.....
  615. waiting = WAITING_SOCK_CONNECT;
  616. sockfd = osock;
  617. #ifdef PQISSL_LOG_DEBUG
  618. out += " EINPROGRESS Waiting for Socket Connection";
  619. rslog(RSL_DEBUG_BASIC, pqisslzone, out);
  620. #endif
  621. return 0;
  622. }
  623. else if ((errno == ENETUNREACH) || (errno == ETIMEDOUT))
  624. {
  625. out += "ENETUNREACHABLE: cert: " + PeerId().toStdString();
  626. rslog(RSL_WARNING, pqisslzone, out);
  627. // Then send unreachable message.
  628. net_internal_close(osock);
  629. osock=-1;
  630. //reset();
  631. waiting = WAITING_FAIL_INTERFACE;
  632. return -1;
  633. }
  634. /* IF we get here ---- we Failed for some other reason.
  635. * Should abandon this interface
  636. * Known reasons to get here: EINVAL (bad address)
  637. */
  638. rs_sprintf_append(out, "Error: Connection Failed: %d - %s", errno, socket_errorType(errno).c_str());
  639. net_internal_close(osock);
  640. osock=-1;
  641. waiting = WAITING_FAIL_INTERFACE;
  642. rslog(RSL_WARNING, pqisslzone, out);
  643. // extra output for the moment.
  644. std::cerr << out;
  645. return -1;
  646. }
  647. else
  648. {
  649. #ifdef PQISSL_LOG_DEBUG
  650. rslog(RSL_DEBUG_BASIC, pqisslzone,
  651. "pqissl::Init_Connection() connect returned 0");
  652. #endif
  653. }
  654. waiting = WAITING_SOCK_CONNECT;
  655. sockfd = osock;
  656. #ifdef PQISSL_LOG_DEBUG
  657. rslog(RSL_DEBUG_BASIC, pqisslzone,
  658. "pqissl::Initiate_Connection() Waiting for Socket Connect");
  659. #endif
  660. return 1;
  661. }
  662. /****************************** CHECK SOCKET *****************************
  663. * Check the Socket.
  664. *
  665. * select() and getsockopt().
  666. *
  667. * Specifics:
  668. * TCP / UDP
  669. * TCP - select()/getsockopt()
  670. * UDP - tou_error()
  671. *
  672. * X509 / XPGP - Same.
  673. *
  674. */
  675. bool pqissl::CheckConnectionTimeout()
  676. {
  677. /* new TimeOut code. */
  678. if (time(NULL) > mTimeoutTS)
  679. {
  680. std::string out;
  681. rs_sprintf(out, "pqissl::Basic_Connection_Complete() Connection Timed Out. Peer: %s Period: %lu", PeerId().toStdString().c_str(), mConnectTimeout);
  682. rslog(RSL_WARNING, pqisslzone, out);
  683. /* as sockfd is valid, this should close it all up */
  684. rslog(RSL_ALERT, pqisslzone, "pqissl::Basic_Connection_Complete() -> calling reset()");
  685. reset_locked();
  686. return true;
  687. }
  688. return false;
  689. }
  690. int pqissl::Basic_Connection_Complete()
  691. {
  692. #ifdef PQISSL_LOG_DEBUG
  693. rslog(RSL_DEBUG_BASIC, pqisslzone,
  694. "pqissl::Basic_Connection_Complete()...");
  695. #endif
  696. if (CheckConnectionTimeout())
  697. {
  698. // calls reset.
  699. return -1;
  700. }
  701. if (waiting != WAITING_SOCK_CONNECT)
  702. {
  703. rslog(RSL_ALERT, pqisslzone,
  704. "pqissl::Basic_Connection_Complete() Wrong Mode");
  705. return -1;
  706. }
  707. if (sockfd == -1)
  708. {
  709. rslog(RSL_ALERT, pqisslzone,
  710. "pqissl::Basic_Connection_Complete() problem with the socket descriptor. Aborting");
  711. rslog(RSL_ALERT, pqisslzone, "pqissl::Basic_Connection_Complete() -> calling reset()");
  712. reset_locked();
  713. return -1;
  714. }
  715. // use select on the opened socket.
  716. // Interestingly - This code might be portable....
  717. fd_set ReadFDs, WriteFDs, ExceptFDs;
  718. FD_ZERO(&ReadFDs);
  719. FD_ZERO(&WriteFDs);
  720. FD_ZERO(&ExceptFDs);
  721. FD_SET(sockfd, &ReadFDs);
  722. FD_SET(sockfd, &WriteFDs);
  723. FD_SET(sockfd, &ExceptFDs);
  724. struct timeval timeout;
  725. timeout.tv_sec = 0;
  726. timeout.tv_usec = 0;
  727. #ifdef PQISSL_LOG_DEBUG
  728. rslog(RSL_DEBUG_BASIC, pqisslzone,
  729. "pqissl::Basic_Connection_Complete() Selecting ....");
  730. #endif
  731. int sr = 0;
  732. if (0 > (sr = select(sockfd + 1,
  733. &ReadFDs, &WriteFDs, &ExceptFDs, &timeout)))
  734. {
  735. // select error.
  736. rslog(RSL_WARNING, pqisslzone,
  737. "pqissl::Basic_Connection_Complete() Select ERROR(1)");
  738. net_internal_close(sockfd);
  739. sockfd=-1;
  740. //reset();
  741. waiting = WAITING_FAIL_INTERFACE;
  742. return -1;
  743. }
  744. #ifdef PQISSL_LOG_DEBUG
  745. {
  746. std::string out;
  747. rs_sprintf(out, "pqissl::Basic_Connection_Complete() Select returned %d", sr);
  748. rslog(RSL_DEBUG_BASIC, pqisslzone, out);
  749. }
  750. #endif
  751. if (FD_ISSET(sockfd, &ExceptFDs))
  752. {
  753. // error - reset socket.
  754. // this is a definite bad socket!.
  755. rslog(RSL_WARNING, pqisslzone,
  756. "pqissl::Basic_Connection_Complete() Select ERROR(2)");
  757. net_internal_close(sockfd);
  758. sockfd=-1;
  759. //reset();
  760. waiting = WAITING_FAIL_INTERFACE;
  761. return -1;
  762. }
  763. if (FD_ISSET(sockfd, &WriteFDs))
  764. {
  765. #ifdef PQISSL_LOG_DEBUG
  766. rslog(RSL_DEBUG_BASIC, pqisslzone,
  767. "pqissl::Basic_Connection_Complete() Can Write!");
  768. #endif
  769. }
  770. else
  771. {
  772. #ifdef PQISSL_LOG_DEBUG
  773. // happens frequently so switched to debug msg.
  774. rslog(RSL_DEBUG_BASIC, pqisslzone,
  775. "pqissl::Basic_Connection_Complete() Not Yet Ready!");
  776. #endif
  777. return 0;
  778. }
  779. if (FD_ISSET(sockfd, &ReadFDs))
  780. {
  781. #ifdef PQISSL_LOG_DEBUG
  782. rslog(RSL_DEBUG_BASIC, pqisslzone,
  783. "pqissl::Basic_Connection_Complete() Can Read!");
  784. #endif
  785. }
  786. else
  787. {
  788. #ifdef PQISSL_LOG_DEBUG
  789. // not ready return -1;
  790. rslog(RSL_DEBUG_BASIC, pqisslzone,
  791. "pqissl::Basic_Connection_Complete() Cannot Read!");
  792. #endif
  793. }
  794. int err = 1;
  795. if (0==unix_getsockopt_error(sockfd, &err))
  796. {
  797. if (err == 0)
  798. {
  799. {
  800. std::string out;
  801. rs_sprintf(out, "pqissl::Basic_Connection_Complete() TCP Connection Complete: cert: %s on osock: ", PeerId().toStdString().c_str(), sockfd);
  802. rslog(RSL_WARNING, pqisslzone, out);
  803. }
  804. return 1;
  805. }
  806. else if (err == EINPROGRESS)
  807. {
  808. rslog(RSL_WARNING, pqisslzone, "pqissl::Basic_Connection_Complete() EINPROGRESS: cert: " + PeerId().toStdString());
  809. return 0;
  810. }
  811. else if ((err == ENETUNREACH) || (err == ETIMEDOUT))
  812. {
  813. rslog(RSL_WARNING, pqisslzone, "pqissl::Basic_Connection_Complete() ENETUNREACH/ETIMEDOUT: cert: " + PeerId().toStdString());
  814. // Then send unreachable message.
  815. net_internal_close(sockfd);
  816. sockfd=-1;
  817. //reset();
  818. waiting = WAITING_FAIL_INTERFACE;
  819. return -1;
  820. }
  821. else if ((err == EHOSTUNREACH) || (err == EHOSTDOWN))
  822. {
  823. rslog(RSL_WARNING, pqisslzone, "pqissl::Basic_Connection_Complete() EHOSTUNREACH/EHOSTDOWN: cert: " + PeerId().toStdString());
  824. // Then send unreachable message.
  825. net_internal_close(sockfd);
  826. sockfd=-1;
  827. //reset();
  828. waiting = WAITING_FAIL_INTERFACE;
  829. return -1;
  830. }
  831. else if ((err == ECONNREFUSED))
  832. {
  833. rslog(RSL_WARNING, pqisslzone, "pqissl::Basic_Connection_Complete() ECONNREFUSED: cert: " + PeerId().toStdString());
  834. // Then send unreachable message.
  835. net_internal_close(sockfd);
  836. sockfd=-1;
  837. //reset();
  838. waiting = WAITING_FAIL_INTERFACE;
  839. return -1;
  840. }
  841. std::string out;
  842. rs_sprintf(out, "Error: Connection Failed UNKNOWN ERROR: %d - %s", err, socket_errorType(err).c_str());
  843. rslog(RSL_WARNING, pqisslzone, out);
  844. net_internal_close(sockfd);
  845. sockfd=-1;
  846. //reset(); // which will send Connect Failed,
  847. return -1;
  848. }
  849. rslog(RSL_ALERT, pqisslzone,
  850. "pqissl::Basic_Connection_Complete() BAD GETSOCKOPT!");
  851. waiting = WAITING_FAIL_INTERFACE;
  852. return -1;
  853. }
  854. int pqissl::Initiate_SSL_Connection()
  855. {
  856. int err;
  857. #ifdef PQISSL_LOG_DEBUG
  858. rslog(RSL_DEBUG_BASIC, pqisslzone,
  859. "pqissl::Initiate_SSL_Connection() Checking Basic Connection");
  860. #endif
  861. if (0 >= (err = Basic_Connection_Complete()))
  862. {
  863. return err;
  864. }
  865. #ifdef PQISSL_LOG_DEBUG
  866. rslog(RSL_DEBUG_BASIC, pqisslzone,
  867. "pqissl::Initiate_SSL_Connection() Basic Connection Okay");
  868. #endif
  869. // setup timeout value.
  870. ssl_connect_timeout = time(NULL) + PQISSL_SSL_CONNECT_TIMEOUT;
  871. // Perform SSL magic.
  872. // library already inited by sslroot().
  873. SSL *ssl = SSL_new(AuthSSL::getAuthSSL()->getCTX());
  874. if (ssl == NULL)
  875. {
  876. rslog(RSL_ALERT, pqisslzone,
  877. "pqissl::Initiate_SSL_Connection() SSL_new failed!");
  878. exit(1);
  879. return -1;
  880. }
  881. #ifdef PQISSL_LOG_DEBUG
  882. rslog(RSL_DEBUG_BASIC, pqisslzone,
  883. "pqissl::Initiate_SSL_Connection() SSL Connection Okay");
  884. #endif
  885. ssl_connection = ssl;
  886. net_internal_SSL_set_fd(ssl, sockfd);
  887. if (err < 1)
  888. {
  889. std::string out = "pqissl::Initiate_SSL_Connection() SSL_set_fd failed!\n";
  890. printSSLError(ssl, err, SSL_get_error(ssl, err), ERR_get_error(), out);
  891. rslog(RSL_ALERT, pqisslzone, out);
  892. }
  893. #ifdef PQISSL_LOG_DEBUG
  894. rslog(RSL_DEBUG_BASIC, pqisslzone,
  895. "pqissl::Initiate_SSL_Connection() Waiting for SSL Connection");
  896. #endif
  897. waiting = WAITING_SSL_CONNECTION;
  898. return 1;
  899. }
  900. int pqissl::SSL_Connection_Complete()
  901. {
  902. #ifdef PQISSL_LOG_DEBUG
  903. rslog(RSL_DEBUG_BASIC, pqisslzone,
  904. "pqissl::SSL_Connection_Complete()??? ... Checking");
  905. #endif
  906. if (waiting == WAITING_SSL_AUTHORISE)
  907. {
  908. rslog(RSL_ALERT, pqisslzone,
  909. "pqissl::SSL_Connection_Complete() Waiting = W_SSL_AUTH");
  910. return 1;
  911. }
  912. if (waiting != WAITING_SSL_CONNECTION)
  913. {
  914. rslog(RSL_ALERT, pqisslzone,
  915. "pqissl::SSL_Connection_Complete() Still Waiting..");
  916. return -1;
  917. }
  918. #ifdef PQISSL_LOG_DEBUG
  919. rslog(RSL_DEBUG_BASIC, pqisslzone,
  920. "pqissl::SSL_Connection_Complete() Attempting SSL_connect");
  921. #endif
  922. /* if we are passive - then accept! */
  923. int err;
  924. if (sslmode)
  925. {
  926. #ifdef PQISSL_LOG_DEBUG
  927. rslog(RSL_DEBUG_BASIC, pqisslzone, "--------> Active Connect! Client side.");
  928. #endif
  929. err = SSL_connect(ssl_connection);
  930. }
  931. else
  932. {
  933. #ifdef PQISSL_LOG_DEBUG
  934. rslog(RSL_DEBUG_BASIC, pqisslzone, "--------> Passive Accept! Server side.");
  935. #endif
  936. err = SSL_accept(ssl_connection);
  937. }
  938. if (err != 1)
  939. {
  940. int serr = SSL_get_error(ssl_connection, err);
  941. if ((serr == SSL_ERROR_WANT_READ)
  942. || (serr == SSL_ERROR_WANT_WRITE))
  943. {
  944. #ifdef PQISSL_LOG_DEBUG
  945. rslog(RSL_DEBUG_BASIC, pqisslzone,
  946. "Waiting for SSL handshake!");
  947. #endif
  948. waiting = WAITING_SSL_CONNECTION;
  949. return 0;
  950. }
  951. std::string out;
  952. rs_sprintf(out, "pqissl::SSL_Connection_Complete()\nIssues with SSL Connect(%d)!\n", err);
  953. printSSLError(ssl_connection, err, serr, ERR_get_error(), out);
  954. rslog(RSL_WARNING, pqisslzone, out);
  955. // attempt real error.
  956. Extract_Failed_SSL_Certificate();
  957. rslog(RSL_ALERT, pqisslzone, "pqissl::SSL_Connection_Complete() -> calling reset()");
  958. reset_locked();
  959. waiting = WAITING_FAIL_INTERFACE;
  960. return -1;
  961. }
  962. // if we get here... success v quickly.
  963. rslog(RSL_WARNING, pqisslzone, "pqissl::SSL_Connection_Complete() Success!: Peer: " + PeerId().toStdString());
  964. waiting = WAITING_SSL_AUTHORISE;
  965. return 1;
  966. }
  967. int pqissl::Extract_Failed_SSL_Certificate()
  968. {
  969. std::cerr << "pqissl::Extract_Failed_SSL_Certificate() FAILED Connection due to Security Issues";
  970. std::cerr << std::endl;
  971. #ifdef PQISSL_LOG_DEBUG
  972. rslog(RSL_DEBUG_BASIC, pqisslzone,
  973. "pqissl::Extract_Failed_SSL_Certificate()");
  974. #endif
  975. // Get the Peer Certificate....
  976. X509 *peercert = SSL_get_peer_certificate(ssl_connection);
  977. if (peercert == NULL)
  978. {
  979. rslog(RSL_WARNING, pqisslzone,
  980. "pqissl::Extract_Failed_SSL_Certificate() Peer Didnt Give Cert");
  981. std::cerr << "pqissl::Extract_Failed_SSL_Certificate() ERROR Peer Didn't Give Us Certificate";
  982. std::cerr << std::endl;
  983. return -1;
  984. }
  985. #ifdef PQISSL_LOG_DEBUG
  986. rslog(RSL_DEBUG_BASIC, pqisslzone,
  987. "pqissl::Extract_Failed_SSL_Certificate() Have Peer Cert - Registering");
  988. #endif
  989. std::cerr << "pqissl::Extract_Failed_SSL_Certificate() Passing FAILED Cert to AuthSSL for analysis";
  990. std::cerr << std::endl;
  991. // save certificate... (and ip locations)
  992. // false for outgoing....
  993. // we actually connected to remote_addr,
  994. // which could be
  995. // (pqissl's case) sslcert->serveraddr or sslcert->localaddr.
  996. RsPeerId sslid ;
  997. getX509id(peercert, sslid) ;
  998. RsPgpId gpgid(getX509CNString(peercert->cert_info->issuer));
  999. std::string sslcn = getX509CNString(peercert->cert_info->subject);
  1000. AuthSSL::getAuthSSL()->FailedCertificate(peercert, gpgid,sslid,sslcn,remote_addr, false);
  1001. mLinkMgr->notifyDeniedConnection(gpgid, sslid, sslcn, remote_addr, false);
  1002. return 1;
  1003. }
  1004. int pqissl::Authorise_SSL_Connection()
  1005. {
  1006. #ifdef PQISSL_LOG_DEBUG
  1007. rslog(RSL_DEBUG_BASIC, pqisslzone,
  1008. "pqissl::Authorise_SSL_Connection()");
  1009. #endif
  1010. if (time(NULL) > ssl_connect_timeout)
  1011. {
  1012. rslog(RSL_WARNING, pqisslzone,
  1013. "pqissl::Authorise_SSL_Connection() Connection Timed Out!");
  1014. /* as sockfd is valid, this should close it all up */
  1015. rslog(RSL_ALERT, pqisslzone, "pqissl::Authorise_Connection_Complete() -> calling reset()");
  1016. reset_locked();
  1017. }
  1018. int err;
  1019. if (0 >= (err = SSL_Connection_Complete()))
  1020. {
  1021. return err;
  1022. }
  1023. #ifdef PQISSL_LOG_DEBUG
  1024. rslog(RSL_DEBUG_BASIC, pqisslzone,
  1025. "pqissl::Authorise_SSL_Connection() SSL_Connection_Complete");
  1026. #endif
  1027. // reset switch.
  1028. waiting = WAITING_NOT;
  1029. X509 *peercert = SSL_get_peer_certificate(ssl_connection);
  1030. if (peercert == NULL)
  1031. {
  1032. rslog(RSL_WARNING, pqisslzone,
  1033. "pqissl::Authorise_SSL_Connection() Peer Didnt Give Cert");
  1034. rslog(RSL_ALERT, pqisslzone, "pqissl::Authorise_Connection_Complete() -> calling reset()");
  1035. // Failed completely
  1036. reset_locked();
  1037. return -1;
  1038. }
  1039. RsPeerId certPeerId;
  1040. getX509id(peercert, certPeerId);
  1041. if (RsPeerId(certPeerId) != PeerId()) {
  1042. rslog(RSL_WARNING, pqisslzone,
  1043. "pqissl::Authorise_SSL_Connection() the cert Id doesn't match the Peer id we're trying to connect to.");
  1044. rslog(RSL_ALERT, pqisslzone, "pqissl::Authorise_Connection_Complete() -> calling reset()");
  1045. // Failed completely
  1046. reset_locked();
  1047. return -1;
  1048. }
  1049. #ifdef PQISSL_LOG_DEBUG
  1050. rslog(RSL_DEBUG_BASIC, pqisslzone,
  1051. "pqissl::Authorise_SSL_Connection() Have Peer Cert");
  1052. #endif
  1053. // save certificate... (and ip locations)
  1054. // false for outgoing....
  1055. // we actually connected to remote_addr,
  1056. // which could be
  1057. // (pqissl's case) sslcert->serveraddr or sslcert->localaddr.
  1058. bool res = AuthSSL::getAuthSSL()->CheckCertificate(PeerId(), peercert);
  1059. bool certCorrect = true; /* WE know it okay already! */
  1060. uint32_t check_result ;
  1061. uint32_t checking_flags = RSBANLIST_CHECKING_FLAGS_BLACKLIST;
  1062. if (rsPeers->servicePermissionFlags(PeerId()) & RS_NODE_PERM_REQUIRE_WL)
  1063. checking_flags |= RSBANLIST_CHECKING_FLAGS_WHITELIST;
  1064. if(!rsBanList->isAddressAccepted(remote_addr,checking_flags,&check_result))
  1065. {
  1066. std::cerr << "(SS) refusing connection attempt from IP address " << sockaddr_storage_iptostring(remote_addr) << ". Reason: " <<
  1067. ((check_result == RSBANLIST_CHECK_RESULT_NOT_WHITELISTED)?"not whitelisted (peer requires whitelist)":"blacklisted") << std::endl;
  1068. RsServer::notify()->AddFeedItem(RS_FEED_ITEM_SEC_IP_BLACKLISTED, PeerId().toStdString(), sockaddr_storage_iptostring(remote_addr), "", "", check_result);
  1069. reset_locked();
  1070. return 0 ;
  1071. }
  1072. // check it's the right one.
  1073. if (certCorrect)
  1074. {
  1075. // then okay...
  1076. rslog(RSL_WARNING, pqisslzone, "pqissl::Authorise_SSL_Connection() Accepting Conn. Peer: " + PeerId().toStdString());
  1077. //std::cerr << "pqissl::Authorise_SSL_Connection(): accepting connection from " << sockaddr_storage_iptostring(remote_addr) << std::endl;
  1078. accept_locked(ssl_connection, sockfd, remote_addr);
  1079. return 1;
  1080. }
  1081. rslog(RSL_WARNING, pqisslzone, "pqissl::Authorise_SSL_Connection() Something Wrong ... Shutdown. Peer: " + PeerId().toStdString());
  1082. // else shutdown ssl connection.
  1083. rslog(RSL_ALERT, pqisslzone, "pqissl::Authorise_Connection_Complete() -> calling reset()");
  1084. reset_locked();
  1085. return 0;
  1086. }
  1087. /* This function is public, and callable from pqilistener - so must be mutex protected */
  1088. int pqissl::accept(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr) // initiate incoming connection.
  1089. {
  1090. #ifdef PQISSL_DEBUG
  1091. std::cerr << "pqissl::accept()";
  1092. std::cerr << std::endl;
  1093. #endif
  1094. RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/
  1095. return accept_locked(ssl, fd, foreign_addr);
  1096. }
  1097. int pqissl::accept_locked(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr) // initiate incoming connection.
  1098. {
  1099. uint32_t check_result;
  1100. uint32_t checking_flags = RSBANLIST_CHECKING_FLAGS_BLACKLIST;
  1101. if (rsPeers->servicePermissionFlags(PeerId()) & RS_NODE_PERM_REQUIRE_WL)
  1102. checking_flags |= RSBANLIST_CHECKING_FLAGS_WHITELIST;
  1103. if(!rsBanList->isAddressAccepted(foreign_addr,checking_flags,&check_result))
  1104. {
  1105. std::cerr << "(SS) refusing incoming SSL connection from blacklisted foreign address " << sockaddr_storage_iptostring(foreign_addr)
  1106. << ". Reason: " << check_result << "." << std::endl;
  1107. RsServer::notify()->AddFeedItem(RS_FEED_ITEM_SEC_IP_BLACKLISTED, PeerId().toStdString(), sockaddr_storage_iptostring(foreign_addr), "", "", check_result);
  1108. reset_locked();
  1109. return -1;
  1110. }
  1111. if (waiting != WAITING_NOT)
  1112. {
  1113. rslog(RSL_WARNING, pqisslzone, "pqissl::accept() Peer: " + PeerId().toStdString() + " - Two connections in progress - Shut 1 down!");
  1114. // outgoing connection in progress.
  1115. // shut this baby down.
  1116. //
  1117. // Thought I should shut down one in progress, and continue existing one!
  1118. // But the existing one might be broke.... take second.
  1119. // all we need is to never stop listening.
  1120. switch(waiting)
  1121. {
  1122. case WAITING_SOCK_CONNECT:
  1123. #ifdef PQISSL_LOG_DEBUG
  1124. rslog(RSL_DEBUG_BASIC, pqisslzone,
  1125. "pqissl::accept() STATE = Waiting Sock Connect - close the socket");
  1126. #endif
  1127. break;
  1128. case WAITING_SSL_CONNECTION:
  1129. #ifdef PQISSL_LOG_DEBUG
  1130. rslog(RSL_DEBUG_BASIC, pqisslzone,
  1131. "pqissl::accept() STATE = Waiting SSL Connection - close sockfd + ssl_conn");
  1132. #endif
  1133. break;
  1134. case WAITING_SSL_AUTHORISE:
  1135. #ifdef PQISSL_LOG_DEBUG
  1136. rslog(RSL_DEBUG_BASIC, pqisslzone,
  1137. "pqissl::accept() STATE = Waiting SSL Authorise - close sockfd + ssl_conn");
  1138. #endif
  1139. break;
  1140. case WAITING_FAIL_INTERFACE:
  1141. #ifdef PQISSL_LOG_DEBUG
  1142. rslog(RSL_DEBUG_BASIC, pqisslzone,
  1143. "pqissl::accept() STATE = Failed, ignore?");
  1144. #endif
  1145. break;
  1146. default:
  1147. rslog(RSL_ALERT, pqisslzone,
  1148. "pqissl::accept() STATE = Unknown - ignore?");
  1149. rslog(RSL_ALERT, pqisslzone, "pqissl::accept() -> calling reset()");
  1150. reset_locked();
  1151. break;
  1152. }
  1153. //waiting = WAITING_FAIL_INTERFACE;
  1154. //return -1;
  1155. }
  1156. /* shutdown existing - in all cases use the new one */
  1157. if ((ssl_connection) && (ssl_connection != ssl))
  1158. {
  1159. rslog(RSL_ALERT, pqisslzone,
  1160. "pqissl::accept() closing Previous/Existing ssl_connection");
  1161. SSL_shutdown(ssl_connection);
  1162. SSL_free (ssl_connection);
  1163. }
  1164. if ((sockfd > -1) && (sockfd != fd))
  1165. {
  1166. rslog(RSL_ALERT, pqisslzone,
  1167. "pqissl::accept() closing Previous/Existing sockfd");
  1168. net_internal_close(sockfd);
  1169. }
  1170. // save ssl + sock.
  1171. ssl_connection = ssl;
  1172. sockfd = fd;
  1173. /* if we connected - then just writing the same over,
  1174. * but if from ssllistener then we need to save the address.
  1175. */
  1176. remote_addr = foreign_addr;
  1177. /* check whether it is on the same LAN */
  1178. struct sockaddr_storage localaddr;
  1179. mLinkMgr->getLocalAddress(localaddr);
  1180. {
  1181. std::string out = "pqissl::accept() SUCCESSFUL connection to: " + PeerId().toStdString();
  1182. out += " localaddr: " + sockaddr_storage_iptostring(localaddr);
  1183. out += " remoteaddr: " + sockaddr_storage_iptostring(remote_addr);
  1184. rslog(RSL_WARNING, pqisslzone, out);
  1185. }
  1186. // establish the ssl details.
  1187. // cipher name.
  1188. int err;
  1189. #ifdef PQISSL_LOG_DEBUG
  1190. {
  1191. int alg;
  1192. std::string out;
  1193. rs_sprintf(out, "SSL Cipher:%s\n", SSL_get_cipher(ssl));
  1194. rs_sprintf_append(out, "SSL Cipher Bits:%d - %d\n", SSL_get_cipher_bits(ssl, &alg), alg);
  1195. rs_sprintf_append(out, "SSL Cipher Version:%s\n", SSL_get_cipher_version(ssl));
  1196. rslog(RSL_DEBUG_BASIC, pqisslzone, out);
  1197. }
  1198. #endif
  1199. // make non-blocking / or check.....
  1200. if ((err = net_internal_fcntl_nonblock(sockfd)) < 0)
  1201. {
  1202. rslog(RSL_ALERT, pqisslzone, "Error: Cannot make socket NON-Blocking: ");
  1203. active = false;
  1204. waiting = WAITING_FAIL_INTERFACE;
  1205. // failed completely.
  1206. rslog(RSL_ALERT, pqisslzone, "pqissl::accept() -> calling reset()");
  1207. reset_locked();
  1208. return -1;
  1209. }
  1210. else
  1211. {
  1212. #ifdef PQISSL_LOG_DEBUG
  1213. rslog(RSL_DEBUG_BASIC, pqisslzone, "pqissl::accept() Socket Made Non-Blocking!");
  1214. #endif
  1215. }
  1216. // we want to continue listening - incase this socket is crap, and they try again.
  1217. //stoplistening();
  1218. active = true;
  1219. waiting = WAITING_NOT;
  1220. #ifdef PQISSL_DEBUG
  1221. std::cerr << "pqissl::accept_locked() connection complete - notifying parent";
  1222. std::cerr << std::endl;
  1223. #endif
  1224. // Notify the pqiperson.... (Both Connect/Receive)
  1225. if (parent())
  1226. {
  1227. struct sockaddr_storage addr = remote_addr;
  1228. parent() -> notifyEvent(this, NET_CONNECT_SUCCESS, addr);
  1229. }
  1230. return 1;
  1231. }
  1232. /********** Implementation of BinInterface **************************
  1233. * All the rest of the BinInterface.
  1234. * This functions much be Mutex protected.
  1235. *
  1236. */
  1237. int pqissl::senddata(void *data, int len)
  1238. {
  1239. RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/
  1240. int tmppktlen ;
  1241. // safety check. Apparently this avoids some SIGSEGV.
  1242. //
  1243. if(ssl_connection == NULL)
  1244. return -1;
  1245. #ifdef PQISSL_DEBUG
  1246. std::cout << "Sending data thread=" << pthread_self() << ", ssl=" << (void*)this << ", size=" << len << std::endl ;
  1247. #endif
  1248. tmppktlen = SSL_write(ssl_connection, data, len) ;
  1249. if (len != tmppktlen)
  1250. {
  1251. std::string out = "pqissl::senddata() " + PeerId().toStdString();
  1252. rs_sprintf_append(out, " Partial Send: len: %d sent: %d ", len, tmppktlen);
  1253. int err = SSL_get_error(ssl_connection, tmppktlen);
  1254. // incomplete operations - to repeat....
  1255. // handled by the pqistreamer...
  1256. if (err == SSL_ERROR_SYSCALL)
  1257. {
  1258. rs_sprintf_append(out, "SSL_write() SSL_ERROR_SYSCALL SOCKET_DEAD -> calling reset() errno: %d ", errno);
  1259. out += socket_errorType(errno);
  1260. std::cerr << out << std::endl;
  1261. rslog(RSL_ALERT, pqisslzone, out);
  1262. /* extra debugging - based on SSL_get_error() man page */
  1263. {
  1264. int errsys = errno;
  1265. int sslerr = 0;
  1266. std::string out2;
  1267. rs_sprintf(out2, "SSL_ERROR_SYSCALL, ret == %d errno: %d %s\n", tmppktlen, errsys, socket_errorType(errsys).c_str());
  1268. while(0 != (sslerr = ERR_get_error()))
  1269. {
  1270. rs_sprintf_append(out2, "SSLERR:%d:", sslerr);
  1271. char sslbuf[256] = {0};
  1272. out2 += ERR_error_string(sslerr, sslbuf);
  1273. out2 += "\n";
  1274. }
  1275. rslog(RSL_ALERT, pqisslzone, out2);
  1276. }
  1277. rslog(RSL_ALERT, pqisslzone, "pqissl::senddata() -> calling reset()");
  1278. reset_locked();
  1279. return -1;
  1280. }
  1281. else if (err == SSL_ERROR_WANT_WRITE)
  1282. {
  1283. out += "SSL_write() SSL_ERROR_WANT_WRITE";
  1284. rslog(RSL_WARNING, pqisslzone, out);
  1285. return -1;
  1286. }
  1287. else if (err == SSL_ERROR_WANT_READ)
  1288. {
  1289. out += "SSL_write() SSL_ERROR_WANT_READ";
  1290. rslog(RSL_WARNING, pqisslzone, out);
  1291. //std::cerr << out << std::endl;
  1292. return -1;
  1293. }
  1294. else
  1295. {
  1296. rs_sprintf_append(out, "SSL_write() UNKNOWN ERROR: %d\n", err);
  1297. printSSLError(ssl_connection, tmppktlen, err, ERR_get_error(), out);
  1298. out += "\n\tResetting!";
  1299. std::cerr << out << std::endl;
  1300. rslog(RSL_ALERT, pqisslzone, out);
  1301. rslog(RSL_ALERT, pqisslzone, "pqissl::senddata() -> calling reset()");
  1302. reset_locked();
  1303. return -1;
  1304. }
  1305. }
  1306. return tmppktlen;
  1307. }
  1308. int pqissl::readdata(void *data, int len)
  1309. {
  1310. RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/
  1311. #ifdef PQISSL_DEBUG
  1312. std::cout << "Reading data thread=" << pthread_self() << ", ssl=" << (void*)this << std::endl ;
  1313. #endif
  1314. // There is a do, because packets can be splitted into multiple ssl buffers
  1315. // when they are larger than 16384 bytes. Such packets have to be read in
  1316. // multiple slices.
  1317. do
  1318. {
  1319. int tmppktlen ;
  1320. #ifdef PQISSL_DEBUG
  1321. std::cerr << "calling SSL_read. len=" << len << ", total_len=" << total_len << std::endl ;
  1322. #endif
  1323. tmppktlen = SSL_read(ssl_connection, (void*)( &(((uint8_t*)data)[total_len])), len-total_len) ;
  1324. #ifdef PQISSL_DEBUG
  1325. std::cerr << "have read " << tmppktlen << " bytes" << std::endl ;
  1326. std::cerr << "data[0] = "
  1327. << (int)((uint8_t*)data)[total_len+0] << " "
  1328. << (int)((uint8_t*)data)[total_len+1] << " "
  1329. << (int)((uint8_t*)data)[total_len+2] << " "
  1330. << (int)((uint8_t*)data)[total_len+3] << " "
  1331. << (int)((uint8_t*)data)[total_len+4] << " "
  1332. << (int)((uint8_t*)data)[total_len+5] << " "
  1333. << (int)((uint8_t*)data)[total_len+6] << " "
  1334. << (int)((uint8_t*)data)[total_len+7] << std::endl ;
  1335. #endif
  1336. // Need to catch errors.....
  1337. //
  1338. if (tmppktlen <= 0) // probably needs a reset.
  1339. {
  1340. std::string out;
  1341. int error = SSL_get_error(ssl_connection, tmppktlen);
  1342. unsigned long err2 = ERR_get_error();
  1343. //printSSLError(ssl_connection, tmppktlen, error, err2, out);
  1344. if ((error == SSL_ERROR_ZERO_RETURN) && (err2 == 0))
  1345. {
  1346. /* this code will be called when
  1347. * (1) moretoread -> returns true. +
  1348. * (2) SSL_read fails.
  1349. *
  1350. * There are two ways this can happen:
  1351. * (1) there is a little data on the socket, but not enough
  1352. * for a full SSL record, so there legimitately is no error, and the moretoread()
  1353. * was correct, but the read fails.
  1354. *
  1355. * (2) the socket has been closed correctly. this leads to moretoread() -> true,
  1356. * and ZERO error.... we catch this case by counting how many times
  1357. * it occurs in a row (cos the other one will not).
  1358. */
  1359. if (n_read_zero == 0)
  1360. {
  1361. /* first read_zero */
  1362. mReadZeroTS = time(NULL);
  1363. }
  1364. ++n_read_zero;
  1365. out += "pqissl::readdata() " + PeerId().toStdString();
  1366. rs_sprintf_append(out, " SSL_read() SSL_ERROR_ZERO_RETURN : nReadZero: %d", n_read_zero);
  1367. if ((PQISSL_MAX_READ_ZERO_COUNT < n_read_zero)
  1368. && (time(NULL) - mReadZeroTS > PQISSL_MAX_READ_ZERO_TIME))
  1369. {
  1370. out += " Count passed Limit, shutting down!";
  1371. rs_sprintf_append(out, " ReadZero Age: %ld", time(NULL) - mReadZeroTS);
  1372. rslog(RSL_ALERT, pqisslzone, "pqissl::readdata() -> calling reset()");
  1373. reset_locked();
  1374. }
  1375. rslog(RSL_ALERT, pqisslzone, out);
  1376. //std::cerr << out << std::endl ;
  1377. return -1;
  1378. }
  1379. /* the only real error we expect */
  1380. if (error == SSL_ERROR_SYSCALL)
  1381. {
  1382. out += "pqissl::readdata() " + PeerId().toStdString();
  1383. out += " SSL_read() SSL_ERROR_SYSCALL";
  1384. out += " SOCKET_DEAD -> calling reset()";
  1385. rs_sprintf_append(out, " errno: %d", errno);
  1386. out += " " + socket_errorType(errno);
  1387. rslog(RSL_ALERT, pqisslzone, out);
  1388. /* extra debugging - based on SSL_get_error() man page */
  1389. {
  1390. int syserr = errno;
  1391. int sslerr = 0;
  1392. std::string out2;
  1393. rs_sprintf(out2, "SSL_ERROR_SYSCALL, ret == %d errno: %d %s\n", tmppktlen, syserr, socket_errorType(syserr).c_str());
  1394. while(0 != (sslerr = ERR_get_error()))
  1395. {
  1396. rs_sprintf_append(out2, "SSLERR:%d : ", sslerr);
  1397. char sslbuf[256] = {0};
  1398. out2 += ERR_error_string(sslerr, sslbuf);
  1399. out2 += "\n";
  1400. }
  1401. rslog(RSL_ALERT, pqisslzone, out2);
  1402. }
  1403. rslog(RSL_ALERT, pqisslzone, "pqissl::readdata() -> calling reset()");
  1404. reset_locked();
  1405. std::cerr << out << std::endl ;
  1406. return -1;
  1407. }
  1408. else if (error == SSL_ERROR_WANT_WRITE)
  1409. {
  1410. out += "SSL_read() SSL_ERROR_WANT_WRITE";
  1411. rslog(RSL_WARNING, pqisslzone, out);
  1412. std::cerr << out << std::endl ;
  1413. return -1;
  1414. }
  1415. else if (error == SSL_ERROR_WANT_READ)
  1416. {
  1417. // SSL_WANT_READ is not a crittical error. It's just a sign that
  1418. // the internal SSL buffer is not ready to accept more data. So -1
  1419. // is returned, and the connection will be retried as is on next
  1420. // call of readdata().
  1421. #ifdef PQISSL_DEBUG
  1422. out += "SSL_read() SSL_ERROR_WANT_READ";
  1423. rslog(RSL_DEBUG_BASIC, pqisslzone, out);
  1424. #endif
  1425. return -1;
  1426. }
  1427. else
  1428. {
  1429. rs_sprintf_append(out, "SSL_read() UNKNOWN ERROR: %d Resetting!", error);
  1430. rslog(RSL_ALERT, pqisslzone, out);
  1431. std::cerr << out << std::endl ;
  1432. rslog(RSL_ALERT, pqisslzone, "pqissl::readdata() -> calling reset()");
  1433. reset_locked();
  1434. return -1;
  1435. }
  1436. rslog(RSL_ALERT, pqisslzone, out);
  1437. //exit(1);
  1438. }
  1439. else
  1440. total_len+=tmppktlen ;
  1441. } while(total_len < len) ;
  1442. #ifdef PQISSL_DEBUG
  1443. std::cerr << "pqissl: have read data of length " << total_len << ", expected is " << len << std::endl ;
  1444. #endif
  1445. if (len != total_len)
  1446. {
  1447. std::string out;
  1448. rs_sprintf(out, "pqissl::readdata() Full Packet Not read!\n -> Expected len(%d) actually read(%d)", len, total_len);
  1449. std::cerr << out << std::endl;
  1450. rslog(RSL_WARNING, pqisslzone, out);
  1451. }
  1452. total_len = 0 ; // reset the packet pointer as we have finished a packet.
  1453. n_read_zero = 0;
  1454. return len;//tmppktlen;
  1455. }
  1456. // dummy function currently.
  1457. int pqissl::netstatus()
  1458. {
  1459. return 1;
  1460. }
  1461. int pqissl::isactive()
  1462. {
  1463. return active; // no need to mutex this. It's atomic.
  1464. }
  1465. bool pqissl::moretoread(uint32_t usec)
  1466. {
  1467. RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/
  1468. #ifdef PQISSL_DEBUG
  1469. {
  1470. std::string out;
  1471. rs_sprintf(out, "pqissl::moretoread() polling socket (%d)", sockfd);
  1472. rslog(RSL_DEBUG_ALL, pqisslzone, out);
  1473. }
  1474. #endif
  1475. if(sockfd == -1)
  1476. {
  1477. std::cerr << "pqissl::moretoread(): socket is invalid or closed." << std::endl;
  1478. return 0 ;
  1479. }
  1480. fd_set ReadFDs, WriteFDs, ExceptFDs;
  1481. FD_ZERO(&ReadFDs);
  1482. FD_ZERO(&WriteFDs);
  1483. FD_ZERO(&ExceptFDs);
  1484. FD_SET(sockfd, &ReadFDs);
  1485. // Dont set WriteFDs.
  1486. FD_SET(sockfd, &ExceptFDs);
  1487. struct timeval timeout;
  1488. timeout.tv_sec = 0;
  1489. timeout.tv_usec = usec;
  1490. if (select(sockfd + 1, &ReadFDs, &WriteFDs, &ExceptFDs, &timeout) < 0)
  1491. {
  1492. rslog(RSL_ALERT, pqisslzone,
  1493. "pqissl::moretoread() Select ERROR!");
  1494. return 0;
  1495. }
  1496. if (FD_ISSET(sockfd, &ExceptFDs))
  1497. {
  1498. // error - reset socket.
  1499. rslog(RSL_ALERT, pqisslzone,
  1500. "pqissl::moretoread() Select Exception ERROR!");
  1501. // this is a definite bad socket!.
  1502. // reset.
  1503. rslog(RSL_ALERT, pqisslzone, "pqissl::moretoread() -> calling reset()");
  1504. reset_locked();
  1505. return 0;
  1506. }
  1507. if (FD_ISSET(sockfd, &ReadFDs))
  1508. {
  1509. #ifdef PQISSL_LOG_DEBUG
  1510. rslog(RSL_DEBUG_BASIC, pqisslzone,
  1511. "pqissl::moretoread() Data to Read!");
  1512. #endif
  1513. return 1;
  1514. }
  1515. else
  1516. {
  1517. #ifdef PQISSL_DEBUG
  1518. rslog(RSL_DEBUG_ALL, pqisslzone,
  1519. "pqissl::moretoread() No Data to Read!");
  1520. #endif
  1521. return 0;
  1522. }
  1523. }
  1524. bool pqissl::cansend(uint32_t usec)
  1525. {
  1526. RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/
  1527. #ifdef PQISSL_DEBUG
  1528. rslog(RSL_DEBUG_ALL, pqisslzone,
  1529. "pqissl::cansend() polling socket!");
  1530. #endif
  1531. if(sockfd == -1)
  1532. {
  1533. std::cerr << "pqissl::cansend(): socket is invalid or closed." << std::endl;
  1534. return 0 ;
  1535. }
  1536. // Interestingly - This code might be portable....
  1537. fd_set ReadFDs, WriteFDs, ExceptFDs;
  1538. FD_ZERO(&ReadFDs);
  1539. FD_ZERO(&WriteFDs);
  1540. FD_ZERO(&ExceptFDs);
  1541. // Dont Set ReadFDs.
  1542. FD_SET(sockfd, &WriteFDs);
  1543. FD_SET(sockfd, &ExceptFDs);
  1544. struct timeval timeout;
  1545. timeout.tv_sec = 0;
  1546. timeout.tv_usec = usec;
  1547. if (select(sockfd + 1, &ReadFDs, &WriteFDs, &ExceptFDs, &timeout) < 0)
  1548. {
  1549. // select error.
  1550. rslog(RSL_ALERT, pqisslzone,
  1551. "pqissl::cansend() Select Error!");
  1552. return 0;
  1553. }
  1554. if (FD_ISSET(sockfd, &ExceptFDs))
  1555. {
  1556. // error - reset socket.
  1557. rslog(RSL_ALERT, pqisslzone,
  1558. "pqissl::cansend() Select Exception!");
  1559. // this is a definite bad socket!.
  1560. // reset.
  1561. rslog(RSL_ALERT, pqisslzone, "pqissl::cansend() -> calling reset()");
  1562. reset_locked();
  1563. return 0;
  1564. }
  1565. if (FD_ISSET(sockfd, &WriteFDs))
  1566. {
  1567. #ifdef PQISSL_DEBUG
  1568. // write can work.
  1569. rslog(RSL_DEBUG_ALL, pqisslzone,
  1570. "pqissl::cansend() Can Write!");
  1571. #endif
  1572. return 1;
  1573. }
  1574. else
  1575. {
  1576. #ifdef PQISSL_DEBUG
  1577. // write can work.
  1578. rslog(RSL_DEBUG_BASIC, pqisslzone,
  1579. "pqissl::cansend() Can *NOT* Write!");
  1580. #endif
  1581. return 0;
  1582. }
  1583. }
  1584. RsFileHash pqissl::gethash() { return RsFileHash(); }
  1585. /********** End of Implementation of BinInterface ******************/
  1586. int pqissl::net_internal_close(int fd)
  1587. {
  1588. return unix_close(fd);
  1589. }
  1590. int pqissl::net_internal_SSL_set_fd(SSL *ssl, int fd)
  1591. {
  1592. return SSL_set_fd(ssl, fd);
  1593. }
  1594. int pqissl::net_internal_fcntl_nonblock(int fd)
  1595. {
  1596. return unix_fcntl_nonblock(fd);
  1597. }