-
Notifications
You must be signed in to change notification settings - Fork 39
/
Socket.h
executable file
·587 lines (520 loc) · 17.1 KB
/
Socket.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
/**************************************************************
* Copyright (c) 201-2017, Dynamic Network Services, Inc.
* Jake Montgomery ([email protected]) & Tom Daly ([email protected])
* Distributed under the FreeBSD License - see LICENSE
***************************************************************/
#pragma once
#include "common.h"
#include "SockAddr.h"
#include "SmartPointer.h"
#include <sys/socket.h>
/**
* Class for socket. It can perform some basic socket tasks as well. All
* functions will log to Log::Error on failure.
* It has optional ::close() semantics.
* Call UtilsInit() before using.
* This can be an RAII class, but it has some 'specialized' ownership semantics
* that allow it to be used in a container class. Care must be taken to ensure
* that ownership is handled correctly when using this class.
*/
class Socket
{
public:
Socket();
/**
* If family is AF_UNSPEC is used, then some operations may fail.
*
* @param sock
* @param family [in] - The address family that the socket uses
* @param owned [in] - Should the socket be closed when this is destroyed.
*
*/
Socket(int sock, Addr::Type family, bool owned = false);
/**
* Copies socket. The Log, LogName and Quiet values are not copied.
*
* @note The new socket is NOT owned.
*/
Socket(const Socket &src);
~Socket();
/**
* Attempts to create a socket.
* Will be owned by default.
*
* @note Use GetLastError() for error code on failure.
*
* @param family [in] - The address family that the socket uses
* @param type
* @param protocol
*
* @return bool - false on failure.
*/
bool Open(Addr::Type family, int type, int protocol);
/**
* Same as open, with (family, SOCK_DGRAM, IPPROTO_UDP)
*
* @note Use GetLastError() for error code on failure.
*
* @param family [in] - The address family that the socket uses
*
* @return bool - false on failure.
*/
bool OpenUDP(Addr::Type family);
/**
* Same as open, with (family, SOCK_STREAM, IPPROTO_TCP)
*
* @note Use GetLastError() for error code on failure.
*
* @param family [in] - The address family that the socket uses
*
* @return bool - false on failure.
*/
bool OpenTCP(Addr::Type family);
/**
* Attach an existing socket.
* There will be no associated address.
* If family is AF_UNSPEC is used, then some operations may fail.
*
*
* @param sock
* @param family [in] - The address family that the socket uses
* @param owned [in] - Should the socket be closed when this is destroyed.
*/
void Attach(int sock, Addr::Type family, bool owned = false);
/**
* Attach an existing socket.
* Associate the given address and address family.
*
* @param owned [in] - Should the socket be closed when this is destroyed.
*
* @param sock
* @param addr
*/
void Attach(int sock, const sockaddr *addr, socklen_t addrlen, bool owned = false);
/**
* Detach and return the socket.
*
* This will no longer be responsible for closing the socket.
*
* @return int
*/
Socket& Detach() { m_owned = false; return *this;}
/**
* If this is a valid socket, then it will be owned. That is it will be closed
* when the destructor is called, or Close() is called
*/
void TakeOwnership() { m_owned = true;}
/**
* Makes this a copy of src. This will own the socket if src did, and src will
* loose ownership (if it had it)
* The Log, LogName and Quiet values are not copied.
*/
void Transfer(Socket &src);
/**
* Sets the name used for logging of errors.
*
* This setting is not copied when the socket is copied.
*
*
* @param str [in] - NULL or empty for no name.
*/
void SetLogName(const char *str);
/**
* Gets the log name.
*
* @return const char* - Do not store. Never NULL.
*/
const char* LogName() { return m_logName.c_str();}
/**
* Disables logging of errors.
* This setting is not copied when the socket is copied.
*
* @param quiet
*
* @return bool - The old quiet value.
*/
bool SetQuiet(bool quiet);
/**
* By default, most errors (other than 'expected' errors, are logged at the
* Log::Error level. Setting verbosity will log these at the level given. If
* logging is disabled for this socket (see SetQuiet() ), then these messages
* will not be logged.
*
* This setting is not copied when the socket is copied.
*
* @param type [in] - The log level to use for logging these 'errors'. Use
* Log::TypeCount to disable logging of these.
*
* @return Log::Type - The old verbose value.
*/
Log::Type SetVerbosity(Log::Type type);
/**
* By default, certain 'expected' errors, such as EAGAIN and EINTR are logged at
* the Log::Debug level. Setting verbose will log these at the level given. If
* logging is disabled for this socket (see SetQuiet() ), then these messages
* will not be logged.
*
* This setting is not copied when the socket is copied.
*
* @param type [in] - The log level to use for logging these 'errors'. Use
* Log::TypeCount to disable logging of these.
*
* @return Log::Type - The old verbose value.
*/
Log::Type SetExpectedVerbosity(Log::Type type);
/**
* Returns the socket.
*
* @return int
*/
int GetSocket() { return m_socket;}
/**
* @return - The error from the last call. 0 if it succeeded.
* @note only calls that specifically state that they set the error are
* guaranteed to do so. Others may, or may not.
*
*/
int GetLastError() { return m_error;}
/**
*
* Close the socket only if owned.
* Otherwise, it simply clears the socket.
*/
void Close();
/**
* Closes the socket.
* This will close the socket even if it is not owned.
*
*/
void AlwaysClose();
/**
* Is there a socket attached.
*
* @return bool - true if there is o socket
*/
bool empty() { return m_socket == -1;}
/**
* Sets the socket to be blocking or non-blocking.
* See O_NONBLOCK.
* @note Use GetLastError() for error code on failure.
*/
bool SetBlocking(bool block);
/**
* Sets whether port can be reused.
* See SO_REUSEADDR.
* @note Use GetLastError() for error code on failure.
*/
bool SetReusePort(bool reuse);
/**
* Sets whether receive timestamp is included.
* See SO_TIMESTAMP.
* @note Use GetLastError() for error code on failure.
*/
bool SetUseTimestamp(bool timestamp);
/**
* Sets send buffer size.
* See SO_SNDBUF.
* @note Use GetLastError() for error code on failure.
*/
bool SetSendBufferSize(int bufsize);
/**
* Gets send buffer size.
* See SO_SNDBUF.
* @note Use GetLastError() for error code on failure.
*/
bool GetSendBufferSize(int &out_bufsize);
/**
* Sets receive buffer size.
* See SO_RCVBUF.
* @note Use GetLastError() for error code on failure.
*/
bool SetReceiveBufferSize(int bufsize);
/**
* Gets receive buffer size.
* See SO_RCVBUF.
* @note Use GetLastError() for error code on failure.
*/
bool GetReceiveBufferSize(int &out_bufsize);
/**
* Sets socket option IP_TTL or IPV6_UNICAST_HOPS depending on the type.
* @note Use GetLastError() for error code on failure.
*/
bool SetTTLOrHops(int hops);
/**
* Sets IP_RECVTTL, or IPV6_RECVHOPLIMIT depending on the type.
* @note Use GetLastError() for error code on failure.
*/
bool SetReceiveTTLOrHops(bool receive);
/**
* @return size_t - Maximum needed control size when using SetReceiveTTLOrHops
*/
static size_t GetMaxControlSizeReceiveTTLOrHops();
/**
* Sets IPPROTO_IPV6::IPV6_V6ONLY
*
* @note Use GetLastError() for error code on failure.
*
* @param ipv6Only
*
* @return bool
*/
bool SetIPv6Only(bool ipv6Only);
/**
* Will attempt to enable (or disable) receiving of destination packet address.
*
* @note Use GetLastError() for error code on failure.
*
* @param receive
*
* @return bool
*/
bool SetReceiveDestinationAddress(bool receive);
/**
* @return size_t - Maximum needed control size when using SetReceiveTTLOrHops
*/
static size_t GetMaxControlSizeReceiveDestinationAddress();
/**
* Gets information about socket error status.
* See getsockopt() SO_ERROR.
* @note Use GetLastError() for error code on failure.
*
* @param ouError [out] - On success, this is the SO_ERROR value.
*
* @return bool - false if getsockopt() fails.
*/
bool GetPendingError(int &ouError);
/**
* See socket bind().
*
* @note Use GetLastError() for error code on failure.
*
* @return bool - False on failure
*/
bool Bind(const SockAddr &address);
/**
* See socket ::connect().
*
* @note Use GetLastError() for error code on failure.
*
* @return bool - False on failure
*/
bool Connect(const SockAddr &address);
/**
* See socket listen()
*
* @note Use GetLastError() for error code on failure.
*
* @param backlog
*
* @return bool - False on failure.
*/
bool Listen(int backlog);
/**
* Like sendto().
*
* @note - a 'partial send' is possible on stream based protocols, like TCP.
* In that case, this function will return true, but not all data is sent. for
* this reason, this is not recommended for stream based protocols. Use
* SendToStream() instead.
*
*
* @note Use GetLastError() for error code on failure.
*
* @param buffer
* @param bufferLen
* @param toAddress
* @param flags
*
* @return bool - False on failure. A partial write is NOT failure.
*/
bool SendTo(const void *buffer, size_t bufferLen, const SockAddr &toAddress, int flags = 0);
/**
* Like sendto(), for stream based protocols.
*
* This function can have one of three results. If the write completes
* successfully, and completely, then 'buffer' will be set to NULL, and
* 'bufferLen' will be set to 0. If the write completes partially, then 'buffer'
* and 'bufferLen' will be modified to reflect the unwritten data location and
* length. In this case the function returns true. If there is some other
* failure, then 'buffer' and 'bufferLen' will remain unchanged, and false will
* be returned.
*
* @note Use GetLastError() for error code on failure.
*
* @param buffer [in/out] - The buffer containing the data to be written. See
* description for value on return.
* @param bufferLen [in/out] - The number of bytes to write. See
* description for value on return.
* @param toAddress
* @param flags
*
* @return bool - False on failure. A partial write is NOT failure.
*/
bool SendToStream(const void **buffer, size_t *bufferLen, const SockAddr &toAddress, int flags = 0);
bool SendToStream(void **buffer, size_t *bufferLen, const SockAddr &toAddress, int flags = 0);
/**
* Like send().
*
* @note - a 'partial send' is possible on stream based protocols, like TCP.
* In that case, this function will return true, but not all data is sent. for
* this reason, this is not recommended for stream based protocols. Use
* SendStream,() instead.
*
* @note Use GetLastError() for error code on failure.
*
* @param buffer
* @param bufferLen
* @param flags
*
* @return bool - False on failure. A partial write is NOT failure.
*/
bool Send(const void *buffer, size_t bufferLen, int flags = 0);
/**
* Like send(), for stream based protocols.
*
* This function can have one of three results. If the write completes
* successfully, and completely, then 'buffer' will be set to NULL, and
* 'bufferLen' will be set to 0. If the write completes partially, then 'buffer'
* and 'bufferLen' will be modified to reflect the unwritten data location and
* length. In this case the function returns true. If there is some other
* failure, then 'buffer' and 'bufferLen' will remain unchanged, and false will
* be returned.
*
* @note Use GetLastError() for error code on failure.
*
* @param buffer [in/out] - The buffer containing the data to be written. See
* description for value on return.
* @param bufferLen [in/out] - The number of bytes to write. See
* description for value on return.
*
* @return bool - False on failure. A partial write is NOT failure.
*/
bool SendStream(const void **buffer, size_t *bufferLen, int flags = 0);
bool SendStream(void **buffer, size_t *bufferLen, int flags = 0);
/**
* Like sendmsg(), for stream based protocols.
*
* This function can have one of three results:
*
* 1 - If the write completes successfully, and completely, then
* message->msg_iov is set to NULL and message->msg_iovlen is set to 0. true is
* returned.
* 2 - If the write completes partially, message->msg_iov and
* message->msg_iovlen will be modified to reflect the unwritten data location
* and length. In this case the function returns true.
* 3 - If there is some other failure, then message->msg_iov and
* message->msg_iovlen will remain unchanged, and false will be returned.
*
* @note Use GetLastError() for error code on failure. LastErrorWasSendFatal()
* may be helpful when deciding whether to try again.
*
* @param message [in/out] - The message containing the data to be written.
* May no be NULL. See description for value on return.
*
* @return bool - False on failure. A partial write is NOT failure.
*/
bool SendMsgStream(struct msghdr *message, int flags = 0);
/**
* After a call to SendMsgStream, SendTo(), SendToStream(), Send() or
* SendStream() returns false, this will check if the error was fatal, or if it
* is reasonable to try sending again.
*
*
* @return bool - false if it may be reasonable to try sending again.
*/
bool LastErrorWasSendFatal();
/**
* Like recv()
*
* @param buffer [out] - Filled with received data on success.
* @param inOutBufferLen [in/out] - Should be to size of buffer on calling. Will
* be set to the bytes received on return. Set to 0 on
* error.
* @param flags
*
* @return bool - False on error.
*/
bool Receive(void *buffer, size_t *inOutBufferLen, int flags = 0);
/**
* Like recv(). This is like Receive(), but may be easier to use when
* programming based protocols like TCP.
*
* @param buffer [in/out] - The buffer to hold the data. On success, this points
* to the next unused buffer position. May point to one past the
* end of the buffer if bufferRemain is 0 on return. Not changed
* on failure.
* @param bufferRemain [in/out] - The available size of buffer. On return this
* will be the new available size of the new buffer value.
* @param written [in/out] - This value will be incremented by the number of
* bytes written. This may be NULL. This mirrors bufferRemain,
* and is provided for convenance.
* @param flags
*
* @return bool - False on failure.
*/
bool ReceiveStream(void **buffer, size_t *bufferRemain, size_t *written = NULL, int flags = 0);
/**
* After a call to Receive(), or ReceiveStream() returns
* false, this will check if the error was fatal, or if it is reasonable to try
* receiving again.
*
* @return bool - false if it may be reasonable to try receiving again.
*/
bool LastErrorWasReceiveFatal();
/**
* See socket accept().
* On success, use GetAddress() on source to check source address.
*
* outResult will be owned by default.
*
* @note Use GetLastError() for error code on failure.
*
* @param outResult [out] - On success, this is the socket. On failure, this is
* Closed.
*
* @return bool
*/
bool Accept(Socket &outResult);
/**
* For a socket created with Bind or Connect(), this is the bound address.
* For sockets created from Accept, this is the source address.
*
* May be an invalid address if the socket was attached or is empty.
*
* @return uint32_t
*/
const SockAddr& GetAddress() { return m_address;}
/**
* Auto conversion to int to allow it to be treated like a socket value.
*
*
* @return int
*/
operator int() const { return m_socket;}
/**
* Copies socket.
* The Log, LogName and Quiet values are not copied.
*
* @note The new socket is NOT owned.
*/
Socket &operator=(const Socket &src);
private:
bool setIntSockOpt(int level, int optname, const char *name, int value);
bool getIntSockOpt(int level, int optname, const char *name, int &out_value);
void clear();
void copy(const Socket &src);
bool ensureSocket();
void doErrorLog(Log::Type type, const char *format, va_list args);
bool setErrorAndLog(int error, const char *format, ...) ATTR_FORMAT(printf, 3, 4);
bool setErrorAndLogAsExpected(bool isExpected, int error, const char* format, ...)ATTR_FORMAT(printf, 4, 5);
bool logError(const char* format, ...)ATTR_FORMAT(printf, 2, 3);
bool shouldLog(bool expected);
int m_socket;
SockAddr m_address;
int m_owned; // Close when destroyed.
int m_error;
std::string m_logName;
bool m_quiet;
Log::Type m_verboseErrorLogType; // for non-expected errors
Log::Type m_verboseExpectedLogType; // for non-expected errors
};