Server.cpp 17 KB

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