Server.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. #include "Server.h"
  2. #include <openssl/err.h>
  3. #include <openssl/ssl.h>
  4. #ifndef WIN32
  5. # include <string.h>
  6. #endif
  7. #include <iostream>
  8. #include <Key.h>
  9. #include <Logging.h>
  10. #include <Text.h>
  11. using namespace Network;
  12. // Content of the Server class from Server.h
  13. // Constructor
  14. Server::Server()
  15. : ReferenceCounter()
  16. {
  17. sock = 0;
  18. memset(&address, 0, sizeof(address)); // Set address
  19. address.sin_family = AF_INET;
  20. address.sin_addr.s_addr = ADDR_ANY;
  21. clients = 0;
  22. }
  23. // Destructor
  24. Server::~Server()
  25. {
  26. disconnect();
  27. }
  28. // non-constant
  29. bool Server::connect(unsigned short port, int queueLength) // Opens the socket
  30. {
  31. sock = socket(AF_INET, SOCK_STREAM, 0); // Create socket
  32. address.sin_port = htons(port); // set port
  33. if (sock < 0)
  34. {
  35. sock = 0;
  36. return 0;
  37. }
  38. #ifdef WIN32
  39. char reuseSocket = 1;
  40. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseSocket, sizeof(char));
  41. #else
  42. int reuseSocket = 1;
  43. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseSocket, sizeof(int));
  44. #endif
  45. if (bind(sock, (struct sockaddr*)&address, sizeof(address))
  46. == -1) // open socket
  47. {
  48. disconnect();
  49. return 0; // Error
  50. }
  51. if (listen(sock, queueLength) == -1) // accept clients
  52. {
  53. disconnect();
  54. return 0; // Error
  55. }
  56. return 1;
  57. }
  58. SClient* Server::getClient() // accepts a client
  59. {
  60. if (!sock) return 0;
  61. sockaddr_in client;
  62. int len = sizeof(address);
  63. fd_set set;
  64. int rv = 0;
  65. struct timeval timeout;
  66. while (rv == 0 && sock)
  67. {
  68. FD_ZERO(&set); /* clear the set */
  69. FD_SET(sock, &set); /* add our file descriptor to the set */
  70. timeout.tv_sec = 10;
  71. timeout.tv_usec = 0;
  72. rv = select((int)sock + 1, &set, NULL, NULL, &timeout);
  73. if (rv == -1) return 0;
  74. }
  75. if (!sock) return 0;
  76. #ifdef WIN32
  77. SOCKET cls = accept(sock, (sockaddr*)&client, &len); // receive client
  78. if (cls == INVALID_SOCKET)
  79. {
  80. disconnect();
  81. return 0;
  82. }
  83. #else
  84. SOCKET cls
  85. = accept(sock, (sockaddr*)&client, (socklen_t*)&len); // receive client
  86. if (!cls)
  87. {
  88. if (errno == ECONNABORTED || errno == EBADF) disconnect();
  89. return 0;
  90. }
  91. #endif
  92. client.sin_port = address.sin_port;
  93. clients++;
  94. return new SClient(client, cls); // return client handle class
  95. }
  96. int Server::getClients(bool reset) // returns the number of clients
  97. {
  98. int ret = clients;
  99. if (reset) clients = 0;
  100. return ret;
  101. }
  102. bool Server::disconnect() // stops the server
  103. {
  104. if (!sock) return 1;
  105. if (closesocket(sock) < 0) // close socket
  106. return 0;
  107. sock = 0;
  108. return 1;
  109. }
  110. // constant
  111. unsigned short Server::getPort() const // returns the port
  112. {
  113. return htons(address.sin_port);
  114. }
  115. bool Server::isConnected() const // returns 1 if the server is connected
  116. {
  117. return sock != 0;
  118. }
  119. // Content of the SClient class from Server.h
  120. // Constructor
  121. SClient::SClient(sockaddr_in address, SOCKET sock)
  122. : ReferenceCounter()
  123. {
  124. clientAddr = address;
  125. this->sock = sock;
  126. downStreamBytes = 0;
  127. upStreamBytes = 0;
  128. sendKey = 0;
  129. receiveKey = 0;
  130. }
  131. // Destructor
  132. SClient::~SClient()
  133. {
  134. disconnect();
  135. if (sendKey) sendKey->release();
  136. if (receiveKey) receiveKey->release();
  137. }
  138. // non-constant
  139. void SClient::setReceiveTimeout(
  140. int miliseconds) // Sets a timeout for receiving data
  141. {
  142. #ifdef WIN32
  143. DWORD timeout = miliseconds;
  144. setsockopt(
  145. sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);
  146. #else
  147. struct timeval tv;
  148. tv.tv_sec = miliseconds / 1000;
  149. tv.tv_usec = (miliseconds % 1000) * 1000;
  150. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
  151. #endif
  152. }
  153. void SClient::setSendKeyZ(Encryption::Key* key) // Sets the key for sending
  154. {
  155. if (sendKey) sendKey->release();
  156. sendKey = key;
  157. }
  158. void SClient::setReceiveKeyZ(Encryption::Key* key) // Sets the key for receiving
  159. {
  160. if (receiveKey) receiveKey->release();
  161. receiveKey = key;
  162. }
  163. void SClient::setSendKey(const char* key, int len) // Sets the key for sending
  164. {
  165. if (!sendKey) sendKey = new Encryption::Key();
  166. sendKey->setKey(key, len);
  167. }
  168. void SClient::setReceiveKey(
  169. const char* key, int len) // Sets the key for receiving
  170. {
  171. if (!receiveKey) receiveKey = new Encryption::Key();
  172. receiveKey->setKey(key, len);
  173. }
  174. bool SClient::send(const char* message, int len) // sends to client
  175. {
  176. if (!sock) return 0;
  177. int ll = 0;
  178. while (len > 0)
  179. {
  180. #ifdef WIN32
  181. int l = ::send(sock, message + ll, len, 0);
  182. #else
  183. int l = (int)::send(sock, message + ll, len, MSG_NOSIGNAL);
  184. #endif
  185. if (l <= 0)
  186. {
  187. #ifdef WIN32
  188. # ifdef _DEBUG
  189. Framework::Logging::warning()
  190. << "send: " << l << " Error: " << WSAGetLastError();
  191. # endif
  192. #endif
  193. return 0; // Error
  194. }
  195. len -= l;
  196. ll += l;
  197. }
  198. upStreamBytes += ll;
  199. return 1;
  200. }
  201. bool SClient::getMessage(char* message, int len) // receives message from client
  202. {
  203. if (!sock) return 0;
  204. int ll = 0;
  205. while (len > 0)
  206. {
  207. int l = (int)recv(sock, message + ll, len, MSG_WAITALL);
  208. if (l <= 0)
  209. {
  210. #ifdef WIN32
  211. # ifdef _DEBUG
  212. Framework::Logging::warning()
  213. << "recv: " << l << " Error: " << WSAGetLastError();
  214. # endif
  215. #endif
  216. return 0; // Error
  217. }
  218. len -= l;
  219. ll += l;
  220. }
  221. downStreamBytes += ll;
  222. return 1;
  223. }
  224. bool SClient::sendEncrypted(const char* message, int len) // sends to server
  225. {
  226. if (!sendKey) return send(message, len);
  227. Encryption::Bytes* n = new Encryption::Bytes(message, len);
  228. sendKey->encode(dynamic_cast<Encryption::Bytes*>(n->getThis()));
  229. int ll = 0;
  230. while (len > 0)
  231. {
  232. #ifdef WIN32
  233. int l = ::send(sock, n->getBytes() + ll, len, 0);
  234. #else
  235. int l = (int)::send(sock, n->getBytes() + ll, len, MSG_NOSIGNAL);
  236. #endif
  237. if (l <= 0)
  238. {
  239. #ifdef WIN32
  240. # ifdef _DEBUG
  241. Framework::Logging::warning()
  242. << "send: " << l << " Error: " << WSAGetLastError();
  243. # endif
  244. #endif
  245. n->release();
  246. return 0; // Error
  247. }
  248. len -= l;
  249. ll += l;
  250. }
  251. upStreamBytes += ll;
  252. n->release();
  253. return 1;
  254. }
  255. bool SClient::getMessageEncrypted(char* message, int len) // receives message
  256. {
  257. if (!receiveKey) return getMessage(message, len);
  258. int ll = 0;
  259. while (len > 0)
  260. {
  261. int l = (int)recv(sock, message + ll, len, MSG_WAITALL);
  262. if (l <= 0)
  263. {
  264. #ifdef WIN32
  265. # ifdef _DEBUG
  266. Framework::Logging::warning()
  267. << "recv: " << l << " Error: " << WSAGetLastError();
  268. # endif
  269. #endif
  270. return 0; // Error
  271. }
  272. len -= l;
  273. ll += l;
  274. }
  275. Encryption::Bytes* n = new Encryption::Bytes();
  276. n->setBytesZ(message, ll);
  277. receiveKey->decode(n);
  278. downStreamBytes += ll;
  279. return 1;
  280. }
  281. int SClient::getDownloadBytes(
  282. bool reset) // returns the number of received bytes
  283. {
  284. int ret = downStreamBytes;
  285. if (reset) downStreamBytes = 0;
  286. return ret;
  287. }
  288. int SClient::getUploadBytes(bool reset) // returns the number of sent bytes
  289. {
  290. int ret = upStreamBytes;
  291. if (reset) upStreamBytes = 0;
  292. return ret;
  293. }
  294. bool SClient::disconnect() // disconnects from client
  295. {
  296. if (!sock) return 0;
  297. if (closesocket(sock) < 0) // disconnect
  298. return 0;
  299. sock = 0;
  300. return 1;
  301. }
  302. // constant
  303. bool SClient::hasMessage(
  304. int waitTime) const // Waits for a message for a given time
  305. {
  306. fd_set set;
  307. FD_ZERO(&set);
  308. FD_SET(sock, &set);
  309. timeval time = {waitTime / 1000, waitTime};
  310. int result = select(0, &set, 0, 0, &time);
  311. if (result < 0)
  312. {
  313. #ifdef WIN32
  314. # ifdef _DEBUG
  315. Framework::Logging::warning()
  316. << "select: " << result << " Error: " << WSAGetLastError();
  317. # endif
  318. #endif
  319. }
  320. return result > 0;
  321. }
  322. unsigned short SClient::getPort() const // returns the port
  323. {
  324. return htons(clientAddr.sin_port);
  325. }
  326. const char* SClient::getIp() const // returns the client's IP
  327. {
  328. return inet_ntoa(clientAddr.sin_addr);
  329. }
  330. int pem_passwd_cb(char* buf, int size, int rwflag, void* userdata)
  331. {
  332. const char* pw = ((Text*)userdata)->getText();
  333. memcpy(buf, pw, MIN((unsigned int)size, strlen(pw) + 1));
  334. return (int)strlen(buf);
  335. }
  336. bool SSLErrorCheck(int result, SSL* ssl, const char* action)
  337. {
  338. if (result <= 0)
  339. {
  340. Framework::Logging::error()
  341. << "'" << action
  342. << "' returned error code: " << SSL_get_error(ssl, result);
  343. return 0;
  344. }
  345. return 1;
  346. }
  347. bool SSLErrorCheck(__int64 result, const char* action)
  348. {
  349. if (result <= 0)
  350. {
  351. unsigned long error = ERR_get_error();
  352. Framework::Logging::error() << "'" << action << "' returned " << result
  353. << " error code: " << error << "("
  354. << ERR_reason_error_string(error) << ")";
  355. return 0;
  356. }
  357. return 1;
  358. }
  359. bool SClient::waitForNextMessage()
  360. const // waits until there is something to receive
  361. {
  362. fd_set set;
  363. int rv = 0;
  364. struct timeval timeout;
  365. while (rv == 0 && sock)
  366. {
  367. FD_ZERO(&set); /* clear the set */
  368. FD_SET(sock, &set); /* add our file descriptor to the set */
  369. timeout.tv_sec = 10;
  370. timeout.tv_usec = 0;
  371. rv = select((int)sock + 1, &set, NULL, NULL, &timeout);
  372. if (rv == -1)
  373. {
  374. #ifdef WIN32
  375. # ifdef _DEBUG
  376. Framework::Logging::warning()
  377. << "select: " << rv << " Error: " << WSAGetLastError();
  378. # endif
  379. #endif
  380. return 0;
  381. }
  382. }
  383. if (!sock) return 0;
  384. char c;
  385. #ifdef WIN32
  386. int l = (int)recv(sock, &c, 1, MSG_PEEK);
  387. #else
  388. int l = (int)recv(sock, &c, 1, MSG_WAITALL | MSG_PEEK);
  389. #endif
  390. if (l <= 0)
  391. {
  392. #ifdef WIN32
  393. # ifdef _DEBUG
  394. Framework::Logging::warning()
  395. << "recv: " << l << " Error: " << WSAGetLastError();
  396. # endif
  397. #endif
  398. return 0; // Error
  399. }
  400. return 1;
  401. }
  402. // Content of the SSLServer class
  403. // Constructor
  404. SSLServer::SSLServer()
  405. : ReferenceCounter()
  406. {
  407. s = 0;
  408. const SSL_METHOD* method = TLS_server_method();
  409. ctx = SSL_CTX_new(method);
  410. SSLErrorCheck(SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION),
  411. "SSL_CTX_set_min_proto_version");
  412. SSLErrorCheck(SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION),
  413. "SSL_CTX_set_max_proto_version");
  414. SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
  415. SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
  416. password = new Text();
  417. SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
  418. addr.sin_family = AF_INET;
  419. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  420. clients = 0;
  421. }
  422. // Destructor
  423. SSLServer::~SSLServer()
  424. {
  425. disconnect();
  426. SSL_CTX_free(ctx);
  427. password->release();
  428. #ifdef WIN32
  429. OPENSSL_thread_stop();
  430. #endif
  431. }
  432. // non-constant
  433. // Sets the path to the file where the certificate is stored
  434. bool SSLServer::setCertificateFile(const char* file)
  435. {
  436. return SSLErrorCheck(
  437. SSL_CTX_use_certificate_file(ctx, file, SSL_FILETYPE_PEM),
  438. "SSL_CTX_use_certificate_file");
  439. }
  440. // Sets the path to the file where the private key is stored
  441. bool SSLServer::setPrivateKeyFile(const char* file)
  442. {
  443. return SSLErrorCheck(
  444. SSL_CTX_use_PrivateKey_file(ctx, file, SSL_FILETYPE_PEM),
  445. "SSL_CTX_use_PrivateKey_file");
  446. }
  447. // sets the password of the private key (must be called before
  448. // setPrivateKeyFile)
  449. void SSLServer::setPrivateKeyPassword(const char* password)
  450. {
  451. this->password->setText(password);
  452. }
  453. // Opens the socket
  454. bool SSLServer::connect(unsigned short port, int queueLength)
  455. {
  456. addr.sin_port = htons(port);
  457. s = socket(AF_INET, SOCK_STREAM, 0);
  458. if (s < 0)
  459. {
  460. s = 0;
  461. return 0;
  462. }
  463. #ifdef WIN32
  464. char reuseSocket = 1;
  465. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &reuseSocket, sizeof(char));
  466. #else
  467. int reuseSocket = 1;
  468. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &reuseSocket, sizeof(int));
  469. #endif
  470. if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) < 0)
  471. {
  472. disconnect();
  473. return 0;
  474. }
  475. if (listen(s, queueLength) < 0)
  476. {
  477. disconnect();
  478. return 0;
  479. }
  480. return 1;
  481. }
  482. // accepts a client
  483. SSLSClient* SSLServer::getClient()
  484. {
  485. if (!s) return 0;
  486. int len = sizeof(addr);
  487. struct sockaddr_in addr;
  488. fd_set set;
  489. int rv = 0;
  490. struct timeval timeout;
  491. while (rv == 0 && s)
  492. {
  493. FD_ZERO(&set); /* clear the set */
  494. FD_SET(s, &set); /* add our file descriptor to the set */
  495. timeout.tv_sec = 10;
  496. timeout.tv_usec = 0;
  497. rv = select((int)s + 1, &set, NULL, NULL, &timeout);
  498. if (rv == -1) return 0;
  499. }
  500. if (!s) return 0;
  501. #ifdef WIN32
  502. SOCKET client = accept(s, (struct sockaddr*)&addr, &len);
  503. if (client == INVALID_SOCKET)
  504. {
  505. disconnect();
  506. return 0;
  507. }
  508. #else
  509. SOCKET client
  510. = accept(s, (sockaddr*)&addr, (socklen_t*)&len); // receive client
  511. if (!client)
  512. {
  513. if (errno == ECONNABORTED || errno == EBADF) disconnect();
  514. return 0;
  515. }
  516. #endif
  517. addr.sin_port = this->addr.sin_port;
  518. SSL* ssl = SSL_new(ctx);
  519. if (ssl == 0 && !SSLErrorCheck(0, "SSL_new"))
  520. {
  521. closesocket(client);
  522. return 0;
  523. }
  524. if (!SSLErrorCheck(SSL_set_fd(ssl, (int)client), ssl, "SSL_set_fd"))
  525. {
  526. SSL_free(ssl);
  527. closesocket(client);
  528. return 0;
  529. }
  530. if (!SSLErrorCheck(SSL_accept(ssl), ssl, "SSL_accept"))
  531. {
  532. SSL_free(ssl);
  533. closesocket(client);
  534. return 0;
  535. }
  536. clients++;
  537. return new SSLSClient(addr, ssl, client);
  538. }
  539. // returns the number of clients
  540. int SSLServer::getClients(bool reset)
  541. {
  542. int ret = clients;
  543. if (reset) clients = 0;
  544. return ret;
  545. }
  546. // stops the server
  547. bool SSLServer::disconnect()
  548. {
  549. if (!s) return 1;
  550. if (closesocket(s) < 0) // close socket
  551. return 0;
  552. s = 0;
  553. return 1;
  554. }
  555. // constant
  556. // returns the port
  557. unsigned short SSLServer::getPort() const
  558. {
  559. return htons(addr.sin_port);
  560. }
  561. // returns 1 if the server is connected
  562. bool SSLServer::isConnected() const
  563. {
  564. return s != 0;
  565. }
  566. // Content of the SSLSClient class
  567. // Constructor
  568. SSLSClient::SSLSClient(sockaddr_in client, SSL* ssl, SOCKET s)
  569. : ReferenceCounter()
  570. {
  571. this->s = s;
  572. clientAddr = client;
  573. this->ssl = ssl;
  574. downStreamBytes = 0;
  575. upStreamBytes = 0;
  576. }
  577. // Destructor
  578. SSLSClient::~SSLSClient()
  579. {
  580. disconnect();
  581. #ifdef WIN32
  582. OPENSSL_thread_stop();
  583. #endif
  584. }
  585. // non-constant
  586. void SSLSClient::setReceiveTimeout(
  587. int miliseconds) // Sets a timeout for receiving data
  588. {
  589. #ifdef WIN32
  590. DWORD timeout = miliseconds;
  591. setsockopt(
  592. s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);
  593. #else
  594. struct timeval tv;
  595. tv.tv_sec = miliseconds / 1000;
  596. tv.tv_usec = (miliseconds % 1000) * 1000;
  597. setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
  598. #endif
  599. }
  600. bool SSLSClient::send(const char* message, int len) // sends to client
  601. {
  602. if (!ssl) return 0;
  603. int ll = 0;
  604. while (len > 0)
  605. {
  606. int l = SSL_write(ssl, message + ll, len);
  607. if (l <= 0)
  608. {
  609. #ifdef _DEBUG
  610. Framework::Logging::warning()
  611. << "SSL_write: " << l << " Error: " << SSL_get_error(ssl, l);
  612. #endif
  613. return 0; // Error
  614. }
  615. len -= l;
  616. ll += l;
  617. }
  618. upStreamBytes += ll;
  619. return 1;
  620. }
  621. bool SSLSClient::getMessage(
  622. char* message, int len) // receives message from client
  623. {
  624. if (!ssl) return 0;
  625. int ll = 0;
  626. while (len > 0)
  627. {
  628. int l = (int)SSL_read(ssl, message + ll, len);
  629. if (l <= 0)
  630. {
  631. #ifdef _DEBUG
  632. Framework::Logging::warning()
  633. << "SSL_read: " << l << " Error: " << SSL_get_error(ssl, l);
  634. #endif
  635. return 0; // Error
  636. }
  637. len -= l;
  638. ll += l;
  639. }
  640. downStreamBytes += ll;
  641. return 1;
  642. }
  643. int SSLSClient::getDownloadBytes(
  644. bool reset) // returns the number of received bytes
  645. {
  646. int ret = downStreamBytes;
  647. if (reset) downStreamBytes = 0;
  648. return ret;
  649. }
  650. int SSLSClient::getUploadBytes(bool reset) // returns the number of sent bytes
  651. {
  652. int ret = upStreamBytes;
  653. if (reset) upStreamBytes = 0;
  654. return ret;
  655. }
  656. bool SSLSClient::disconnect() // disconnects from client
  657. {
  658. if (!ssl) return 0;
  659. SSL_free(ssl);
  660. if (closesocket(s) < 0) // disconnect
  661. return 0;
  662. ssl = 0;
  663. s = 0;
  664. return 1;
  665. }
  666. // constant
  667. bool SSLSClient::hasMessage(
  668. int waitTime) const // Waits for a message for a given time
  669. {
  670. fd_set set;
  671. FD_ZERO(&set);
  672. FD_SET(SSL_get_rfd(ssl), &set);
  673. timeval time = {waitTime / 1000, waitTime};
  674. return SSL_pending(ssl) > 0 || select(0, &set, 0, 0, &time) == 1;
  675. }
  676. unsigned short SSLSClient::getPort() const // returns the port
  677. {
  678. return htons(clientAddr.sin_port);
  679. }
  680. const char* SSLSClient::getIp() const // returns the client's IP
  681. {
  682. return inet_ntoa(clientAddr.sin_addr);
  683. }