sock.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. #pragma once
  2. #include <util/folder/path.h>
  3. #include <util/system/defaults.h>
  4. #include <util/string/cast.h>
  5. #include <util/stream/output.h>
  6. #include <util/system/sysstat.h>
  7. #if defined(_win_) || defined(_cygwin_)
  8. #include <util/system/file.h>
  9. #else
  10. #include <sys/un.h>
  11. #include <sys/stat.h>
  12. #endif //_win_
  13. #include "init.h"
  14. #include "ip.h"
  15. #include "socket.h"
  16. constexpr ui16 DEF_LOCAL_SOCK_MODE = 00644;
  17. // Base abstract class for socket address
  18. struct ISockAddr {
  19. virtual ~ISockAddr() = default;
  20. // Max size of the address that we can store (arg of recvfrom)
  21. virtual socklen_t Size() const = 0;
  22. // Real length of the address (arg of sendto)
  23. virtual socklen_t Len() const = 0;
  24. // cast to sockaddr* to pass to any syscall
  25. virtual sockaddr* SockAddr() = 0;
  26. virtual const sockaddr* SockAddr() const = 0;
  27. // address in human readable form
  28. virtual TString ToString() const = 0;
  29. protected:
  30. // below are the implemetation methods that can be called by T*Socket classes
  31. friend class TBaseSocket;
  32. friend class TDgramSocket;
  33. friend class TStreamSocket;
  34. virtual int ResolveAddr() const {
  35. // usually it's nothing to do here
  36. return 0;
  37. }
  38. virtual int Bind(SOCKET s, ui16 mode) const = 0;
  39. };
  40. #if defined(_win_) || defined(_cygwin_)
  41. #define YAF_LOCAL AF_INET
  42. struct TSockAddrLocal: public ISockAddr {
  43. TSockAddrLocal() {
  44. Clear();
  45. }
  46. TSockAddrLocal(const char* path) {
  47. Set(path);
  48. }
  49. socklen_t Size() const {
  50. return sizeof(sockaddr_in);
  51. }
  52. socklen_t Len() const {
  53. return Size();
  54. }
  55. inline void Clear() noexcept {
  56. Zero(in);
  57. Zero(Path);
  58. }
  59. inline void Set(const char* path) noexcept {
  60. Clear();
  61. in.sin_family = AF_INET;
  62. in.sin_addr.s_addr = IpFromString("127.0.0.1");
  63. in.sin_port = 0;
  64. strlcpy(Path, path, PathSize);
  65. }
  66. inline void Set(TStringBuf path) noexcept {
  67. Clear();
  68. in.sin_family = AF_INET;
  69. in.sin_addr.s_addr = IpFromString("127.0.0.1");
  70. in.sin_port = 0;
  71. strlcpy(Path, path.data(), Min(PathSize, path.size() + 1));
  72. }
  73. sockaddr* SockAddr() {
  74. return (struct sockaddr*)(&in);
  75. }
  76. const sockaddr* SockAddr() const {
  77. return (const struct sockaddr*)(&in);
  78. }
  79. TString ToString() const {
  80. return TString(Path);
  81. }
  82. TFsPath ToPath() const {
  83. return TFsPath(Path);
  84. }
  85. int ResolveAddr() const {
  86. if (in.sin_port == 0) {
  87. int ret = 0;
  88. // 1. open file
  89. TFileHandle f(Path, OpenExisting | RdOnly);
  90. if (!f.IsOpen())
  91. return -errno;
  92. // 2. read the port from file
  93. ret = f.Read(&in.sin_port, sizeof(in.sin_port));
  94. if (ret != sizeof(in.sin_port))
  95. return -(errno ? errno : EFAULT);
  96. }
  97. return 0;
  98. }
  99. int Bind(SOCKET s, ui16 mode) const {
  100. Y_UNUSED(mode);
  101. int ret = 0;
  102. // 1. open file
  103. TFileHandle f(Path, CreateAlways | WrOnly);
  104. if (!f.IsOpen())
  105. return -errno;
  106. // 2. find port and bind to it
  107. in.sin_port = 0;
  108. ret = bind(s, SockAddr(), Len());
  109. if (ret != 0)
  110. return -WSAGetLastError();
  111. int size = Size();
  112. ret = getsockname(s, (struct sockaddr*)(&in), &size);
  113. if (ret != 0)
  114. return -WSAGetLastError();
  115. // 3. write port to file
  116. ret = f.Write(&(in.sin_port), sizeof(in.sin_port));
  117. if (ret != sizeof(in.sin_port))
  118. return -errno;
  119. return 0;
  120. }
  121. static constexpr size_t PathSize = 128;
  122. mutable struct sockaddr_in in;
  123. char Path[PathSize];
  124. };
  125. #else
  126. #define YAF_LOCAL AF_LOCAL
  127. struct TSockAddrLocal: public sockaddr_un, public ISockAddr {
  128. TSockAddrLocal() {
  129. Clear();
  130. }
  131. TSockAddrLocal(TStringBuf path) {
  132. Set(path);
  133. }
  134. TSockAddrLocal(const char* path) {
  135. Set(path);
  136. }
  137. socklen_t Size() const override {
  138. return sizeof(sockaddr_un);
  139. }
  140. socklen_t Len() const override {
  141. return strlen(sun_path) + 2;
  142. }
  143. inline void Clear() noexcept {
  144. Zero(*(sockaddr_un*)this);
  145. }
  146. inline void Set(const char* path) noexcept {
  147. Clear();
  148. sun_family = AF_UNIX;
  149. strlcpy(sun_path, path, sizeof(sun_path));
  150. }
  151. inline void Set(TStringBuf path) noexcept {
  152. Clear();
  153. sun_family = AF_UNIX;
  154. strlcpy(sun_path, path.data(), Min(sizeof(sun_path), path.size() + 1));
  155. }
  156. sockaddr* SockAddr() override {
  157. return (struct sockaddr*)(struct sockaddr_un*)this;
  158. }
  159. const sockaddr* SockAddr() const override {
  160. return (const struct sockaddr*)(const struct sockaddr_un*)this;
  161. }
  162. TString ToString() const override {
  163. return TString(sun_path);
  164. }
  165. TFsPath ToPath() const {
  166. return TFsPath(sun_path);
  167. }
  168. int Bind(SOCKET s, ui16 mode) const override {
  169. (void)unlink(sun_path);
  170. int ret = bind(s, SockAddr(), Len());
  171. if (ret < 0)
  172. return -errno;
  173. ret = Chmod(sun_path, mode);
  174. if (ret < 0)
  175. return -errno;
  176. return 0;
  177. }
  178. };
  179. #endif // _win_
  180. struct TSockAddrInet: public sockaddr_in, public ISockAddr {
  181. TSockAddrInet() {
  182. Clear();
  183. }
  184. TSockAddrInet(TIpHost ip, TIpPort port) {
  185. Set(ip, port);
  186. }
  187. TSockAddrInet(const char* ip, TIpPort port) {
  188. Set(IpFromString(ip), port);
  189. }
  190. socklen_t Size() const override {
  191. return sizeof(sockaddr_in);
  192. }
  193. socklen_t Len() const override {
  194. return Size();
  195. }
  196. inline void Clear() noexcept {
  197. Zero(*(sockaddr_in*)this);
  198. }
  199. inline void Set(TIpHost ip, TIpPort port) noexcept {
  200. Clear();
  201. sin_family = AF_INET;
  202. sin_addr.s_addr = ip;
  203. sin_port = HostToInet(port);
  204. }
  205. sockaddr* SockAddr() override {
  206. return (struct sockaddr*)(struct sockaddr_in*)this;
  207. }
  208. const sockaddr* SockAddr() const override {
  209. return (const struct sockaddr*)(const struct sockaddr_in*)this;
  210. }
  211. TString ToString() const override {
  212. return IpToString(sin_addr.s_addr) + ":" + ::ToString(InetToHost(sin_port));
  213. }
  214. int Bind(SOCKET s, ui16 mode) const override {
  215. Y_UNUSED(mode);
  216. int ret = bind(s, SockAddr(), Len());
  217. if (ret < 0)
  218. return -errno;
  219. socklen_t len = Len();
  220. if (getsockname(s, (struct sockaddr*)(SockAddr()), &len) < 0)
  221. return -WSAGetLastError();
  222. return 0;
  223. }
  224. TIpHost GetIp() const noexcept {
  225. return sin_addr.s_addr;
  226. }
  227. TIpPort GetPort() const noexcept {
  228. return InetToHost(sin_port);
  229. }
  230. void SetPort(TIpPort port) noexcept {
  231. sin_port = HostToInet(port);
  232. }
  233. };
  234. struct TSockAddrInet6: public sockaddr_in6, public ISockAddr {
  235. TSockAddrInet6() {
  236. Clear();
  237. }
  238. TSockAddrInet6(const char* ip6, const TIpPort port) {
  239. Set(ip6, port);
  240. }
  241. socklen_t Size() const override {
  242. return sizeof(sockaddr_in6);
  243. }
  244. socklen_t Len() const override {
  245. return Size();
  246. }
  247. inline void Clear() noexcept {
  248. Zero(*(sockaddr_in6*)this);
  249. }
  250. inline void Set(const char* ip6, const TIpPort port) noexcept {
  251. Clear();
  252. sin6_family = AF_INET6;
  253. inet_pton(AF_INET6, ip6, &sin6_addr);
  254. sin6_port = HostToInet(port);
  255. }
  256. sockaddr* SockAddr() override {
  257. return (struct sockaddr*)(struct sockaddr_in6*)this;
  258. }
  259. const sockaddr* SockAddr() const override {
  260. return (const struct sockaddr*)(const struct sockaddr_in6*)this;
  261. }
  262. TString ToString() const override {
  263. return "[" + GetIp() + "]:" + ::ToString(InetToHost(sin6_port));
  264. }
  265. int Bind(SOCKET s, ui16 mode) const override {
  266. Y_UNUSED(mode);
  267. int ret = bind(s, SockAddr(), Len());
  268. if (ret < 0) {
  269. return -errno;
  270. }
  271. socklen_t len = Len();
  272. if (getsockname(s, (struct sockaddr*)(SockAddr()), &len) < 0) {
  273. return -WSAGetLastError();
  274. }
  275. return 0;
  276. }
  277. TString GetIp() const noexcept {
  278. char ip6[INET6_ADDRSTRLEN];
  279. inet_ntop(AF_INET6, (void*)&sin6_addr, ip6, INET6_ADDRSTRLEN);
  280. return TString(ip6);
  281. }
  282. TIpPort GetPort() const noexcept {
  283. return InetToHost(sin6_port);
  284. }
  285. void SetPort(TIpPort port) noexcept {
  286. sin6_port = HostToInet(port);
  287. }
  288. };
  289. using TSockAddrLocalStream = TSockAddrLocal;
  290. using TSockAddrLocalDgram = TSockAddrLocal;
  291. using TSockAddrInetStream = TSockAddrInet;
  292. using TSockAddrInetDgram = TSockAddrInet;
  293. using TSockAddrInet6Stream = TSockAddrInet6;
  294. using TSockAddrInet6Dgram = TSockAddrInet6;
  295. class TBaseSocket: public TSocketHolder {
  296. protected:
  297. TBaseSocket(SOCKET fd)
  298. : TSocketHolder(fd)
  299. {
  300. }
  301. public:
  302. int Bind(const ISockAddr* addr, ui16 mode = DEF_LOCAL_SOCK_MODE) {
  303. return addr->Bind((SOCKET) * this, mode);
  304. }
  305. void CheckSock() {
  306. if ((SOCKET) * this == INVALID_SOCKET)
  307. ythrow TSystemError() << "no socket";
  308. }
  309. static ssize_t Check(ssize_t ret, const char* op = "") {
  310. if (ret < 0)
  311. ythrow TSystemError(-(int)ret) << "socket operation " << op;
  312. return ret;
  313. }
  314. };
  315. class TDgramSocket: public TBaseSocket {
  316. protected:
  317. TDgramSocket(SOCKET fd)
  318. : TBaseSocket(fd)
  319. {
  320. }
  321. public:
  322. ssize_t SendTo(const void* msg, size_t len, const ISockAddr* toAddr) {
  323. ssize_t ret = toAddr->ResolveAddr();
  324. if (ret < 0) {
  325. return -LastSystemError();
  326. }
  327. ret = sendto((SOCKET) * this, (const char*)msg, (int)len, 0, toAddr->SockAddr(), toAddr->Len());
  328. if (ret < 0) {
  329. return -LastSystemError();
  330. }
  331. return ret;
  332. }
  333. ssize_t RecvFrom(void* buf, size_t len, ISockAddr* fromAddr) {
  334. socklen_t fromSize = fromAddr->Size();
  335. const ssize_t ret = recvfrom((SOCKET) * this, (char*)buf, (int)len, 0, fromAddr->SockAddr(), &fromSize);
  336. if (ret < 0) {
  337. return -LastSystemError();
  338. }
  339. return ret;
  340. }
  341. };
  342. class TStreamSocket: public TBaseSocket {
  343. protected:
  344. explicit TStreamSocket(SOCKET fd)
  345. : TBaseSocket(fd)
  346. {
  347. }
  348. public:
  349. TStreamSocket()
  350. : TBaseSocket(INVALID_SOCKET)
  351. {
  352. }
  353. ssize_t Send(const void* msg, size_t len, int flags = 0) {
  354. const ssize_t ret = send((SOCKET) * this, (const char*)msg, (int)len, flags);
  355. if (ret < 0)
  356. return -errno;
  357. return ret;
  358. }
  359. ssize_t Recv(void* buf, size_t len, int flags = 0) {
  360. const ssize_t ret = recv((SOCKET) * this, (char*)buf, (int)len, flags);
  361. if (ret < 0)
  362. return -errno;
  363. return ret;
  364. }
  365. int Connect(const ISockAddr* addr) {
  366. int ret = addr->ResolveAddr();
  367. if (ret < 0)
  368. return -errno;
  369. ret = connect((SOCKET) * this, addr->SockAddr(), addr->Len());
  370. if (ret < 0)
  371. return -errno;
  372. return ret;
  373. }
  374. int Listen(int backlog) {
  375. int ret = listen((SOCKET) * this, backlog);
  376. if (ret < 0)
  377. return -errno;
  378. return ret;
  379. }
  380. int Accept(TStreamSocket* acceptedSock, ISockAddr* acceptedAddr = nullptr) {
  381. SOCKET s = INVALID_SOCKET;
  382. if (acceptedAddr) {
  383. socklen_t acceptedSize = acceptedAddr->Size();
  384. s = accept((SOCKET) * this, acceptedAddr->SockAddr(), &acceptedSize);
  385. } else {
  386. s = accept((SOCKET) * this, nullptr, nullptr);
  387. }
  388. if (s == INVALID_SOCKET)
  389. return -errno;
  390. TSocketHolder sock(s);
  391. acceptedSock->Swap(sock);
  392. return 0;
  393. }
  394. };
  395. class TLocalDgramSocket: public TDgramSocket {
  396. public:
  397. TLocalDgramSocket(SOCKET fd)
  398. : TDgramSocket(fd)
  399. {
  400. }
  401. TLocalDgramSocket()
  402. : TDgramSocket(socket(YAF_LOCAL, SOCK_DGRAM, 0))
  403. {
  404. }
  405. };
  406. class TInetDgramSocket: public TDgramSocket {
  407. public:
  408. TInetDgramSocket(SOCKET fd)
  409. : TDgramSocket(fd)
  410. {
  411. }
  412. TInetDgramSocket()
  413. : TDgramSocket(socket(AF_INET, SOCK_DGRAM, 0))
  414. {
  415. }
  416. };
  417. class TInet6DgramSocket: public TDgramSocket {
  418. public:
  419. TInet6DgramSocket(SOCKET fd)
  420. : TDgramSocket(fd)
  421. {
  422. }
  423. TInet6DgramSocket()
  424. : TDgramSocket(socket(AF_INET6, SOCK_DGRAM, 0))
  425. {
  426. }
  427. };
  428. class TLocalStreamSocket: public TStreamSocket {
  429. public:
  430. TLocalStreamSocket(SOCKET fd)
  431. : TStreamSocket(fd)
  432. {
  433. }
  434. TLocalStreamSocket()
  435. : TStreamSocket(socket(YAF_LOCAL, SOCK_STREAM, 0))
  436. {
  437. }
  438. };
  439. class TInetStreamSocket: public TStreamSocket {
  440. public:
  441. TInetStreamSocket(SOCKET fd)
  442. : TStreamSocket(fd)
  443. {
  444. }
  445. TInetStreamSocket()
  446. : TStreamSocket(socket(AF_INET, SOCK_STREAM, 0))
  447. {
  448. }
  449. };
  450. class TInet6StreamSocket: public TStreamSocket {
  451. public:
  452. TInet6StreamSocket(SOCKET fd)
  453. : TStreamSocket(fd)
  454. {
  455. }
  456. TInet6StreamSocket()
  457. : TStreamSocket(socket(AF_INET6, SOCK_STREAM, 0))
  458. {
  459. }
  460. };
  461. class TStreamSocketInput: public IInputStream {
  462. public:
  463. TStreamSocketInput(TStreamSocket* socket)
  464. : Socket(socket)
  465. {
  466. }
  467. void SetSocket(TStreamSocket* socket) {
  468. Socket = socket;
  469. }
  470. protected:
  471. TStreamSocket* Socket;
  472. size_t DoRead(void* buf, size_t len) override {
  473. Y_VERIFY(Socket, "TStreamSocketInput: socket isn't set");
  474. const ssize_t ret = Socket->Recv(buf, len);
  475. if (ret >= 0) {
  476. return (size_t)ret;
  477. }
  478. ythrow TSystemError(-(int)ret) << "can not read from socket input stream";
  479. }
  480. };
  481. class TStreamSocketOutput: public IOutputStream {
  482. public:
  483. TStreamSocketOutput(TStreamSocket* socket)
  484. : Socket(socket)
  485. {
  486. }
  487. void SetSocket(TStreamSocket* socket) {
  488. Socket = socket;
  489. }
  490. TStreamSocketOutput(TStreamSocketOutput&&) noexcept = default;
  491. TStreamSocketOutput& operator=(TStreamSocketOutput&&) noexcept = default;
  492. protected:
  493. TStreamSocket* Socket;
  494. void DoWrite(const void* buf, size_t len) override {
  495. Y_VERIFY(Socket, "TStreamSocketOutput: socket isn't set");
  496. const char* ptr = (const char*)buf;
  497. while (len) {
  498. const ssize_t ret = Socket->Send(ptr, len);
  499. if (ret < 0) {
  500. ythrow TSystemError(-(int)ret) << "can not write to socket output stream";
  501. }
  502. Y_ASSERT((size_t)ret <= len);
  503. len -= (size_t)ret;
  504. ptr += (size_t)ret;
  505. }
  506. }
  507. };