• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

taosdata / TDengine / #3768

28 Mar 2025 10:15AM UTC coverage: 33.726% (-0.3%) from 33.993%
#3768

push

travis-ci

happyguoxy
test:alter lcov result

144891 of 592084 branches covered (24.47%)

Branch coverage included in aggregate %.

218795 of 486283 relevant lines covered (44.99%)

765715.29 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

71.49
/source/os/src/osSocket.c
1
/*
2
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
3
 *
4
 * This program is free software: you can use, redistribute, and/or modify
5
 * it under the terms of the GNU Affero General Public License, version 3
6
 * or later ("AGPL"), as published by the Free Software Foundation.
7
 *
8
 * This program is distributed in the hope that it will be useful, but WITHOUT
9
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
 * FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * You should have received a copy of the GNU Affero General Public License
13
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14
 */
15

16
#define _DEFAULT_SOURCE
17
#define ALLOW_FORBID_FUNC
18
#include "os.h"
19

20
#if defined(WINDOWS)
21
#include <IPHlpApi.h>
22
#include <WS2tcpip.h>
23
#include <Winsock2.h>
24
#include <stdio.h>
25
#include <string.h>
26
#include <tchar.h>
27
#include <winbase.h>
28
#else
29
#include <arpa/inet.h>
30
#include <fcntl.h>
31
#include <net/if.h>
32
#include <netdb.h>
33
#include <netinet/in.h>
34
#include <netinet/ip.h>
35
#include <netinet/tcp.h>
36
#include <netinet/udp.h>
37
#include <sys/socket.h>
38
#include <unistd.h>
39

40
#if defined(DARWIN)
41
#include <dispatch/dispatch.h>
42
#include "osEok.h"
43
#elif !defined(TD_ASTRA)
44
#include <sys/epoll.h>
45
#endif
46
#endif
47

48
#ifdef TD_ASTRA
49
#ifndef __BYTE_ORDER
50
#define __BYTE_ORDER _BYTE_ORDER
51
#endif
52

53
#ifndef __BIG_ENDIAN
54
#define __BIG_ENDIAN _BIG_ENDIAN
55
#endif
56

57
#ifndef __LITTLE_ENDIAN
58
#define __LITTLE_ENDIAN _LITTLE_ENDIAN
59
#endif
60
#endif // TD_ASTRA
61

62
#ifndef INVALID_SOCKET
63
#define INVALID_SOCKET -1
64
#endif
65

66
typedef struct TdSocket {
67
#if SOCKET_WITH_LOCK
68
  TdThreadRwlock rwlock;
69
#endif
70
  int      refId;
71
  SocketFd fd;
72
} * TdSocketPtr, TdSocket;
73

74
typedef struct TdSocketServer {
75
#if SOCKET_WITH_LOCK
76
  TdThreadRwlock rwlock;
77
#endif
78
  int      refId;
79
  SocketFd fd;
80
} * TdSocketServerPtr, TdSocketServer;
81

82
typedef struct TdEpoll {
83
#if SOCKET_WITH_LOCK
84
  TdThreadRwlock rwlock;
85
#endif
86
  int     refId;
87
  EpollFd fd;
88
} * TdEpollPtr, TdEpoll;
89

90
int32_t taosCloseSocketNoCheck1(SocketFd fd) {
133✔
91
#ifdef WINDOWS
92
  int ret = closesocket(fd);
93
  if (ret == SOCKET_ERROR) {
94
    int errorCode = WSAGetLastError();
95
    return terrno = TAOS_SYSTEM_WINSOCKET_ERROR(errorCode);
96
  }
97
  return 0;
98
#else
99
  int32_t code = close(fd);
133✔
100
  if (-1 == code) {
133!
101
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
102
    return terrno;
×
103
  }
104
  return code;
133✔
105
#endif
106
}
107

108
int32_t taosCloseSocket(TdSocketPtr *ppSocket) {
134✔
109
  int32_t code;
110
  if (ppSocket == NULL || *ppSocket == NULL || (*ppSocket)->fd < 0) {
134!
111
    terrno = TSDB_CODE_INVALID_PARA;
1✔
112
    return terrno;
1✔
113
  }
114
  code = taosCloseSocketNoCheck1((*ppSocket)->fd);
133✔
115
  (*ppSocket)->fd = -1;
133✔
116
  taosMemoryFree(*ppSocket);
133!
117

118
  return code;
133✔
119
}
120

121
int32_t taosSetSockOpt(TdSocketPtr pSocket, int32_t level, int32_t optname, void *optval, int32_t optlen) {
134✔
122
  if (pSocket == NULL || pSocket->fd < 0) {
134!
123
    terrno = TSDB_CODE_INVALID_PARA;
1✔
124
    return terrno;
1✔
125
  }
126

127
#ifdef WINDOWS
128
#ifdef TCP_KEEPCNT
129
  if (level == SOL_SOCKET && optname == TCP_KEEPCNT) {
130
    return 0;
131
  }
132
#endif
133

134
#ifdef TCP_KEEPIDLE
135
  if (level == SOL_TCP && optname == TCP_KEEPIDLE) {
136
    return 0;
137
  }
138
#endif
139

140
#ifdef TCP_KEEPINTVL
141
  if (level == SOL_TCP && optname == TCP_KEEPINTVL) {
142
    return 0;
143
  }
144
#endif
145

146
#ifdef TCP_KEEPCNT
147
  if (level == SOL_TCP && optname == TCP_KEEPCNT) {
148
    return 0;
149
  }
150
#endif
151

152
  int ret = setsockopt(pSocket->fd, level, optname, optval, optlen);
153
  if (ret == SOCKET_ERROR) {
154
    int errorCode = WSAGetLastError();
155
    return terrno = TAOS_SYSTEM_WINSOCKET_ERROR(errorCode);
156
  }
157
#else
158
  int32_t code = setsockopt(pSocket->fd, level, optname, optval, (int)optlen);
133✔
159
  if (-1 == code) {
133!
160
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
161
    return terrno;
×
162
  }
163
  return 0;
133✔
164
#endif
165
}
166

167
const char *taosInetNtop(struct in_addr ipInt, char *dstStr, int32_t len) {
1✔
168
  const char *r = inet_ntop(AF_INET, &ipInt, dstStr, len);
1✔
169
  if (NULL == r) {
1!
170
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
171
  }
172

173
  return r;
1✔
174
}
175

176
#ifndef SIGPIPE
177
#define SIGPIPE EPIPE
178
#endif
179

180
#define TCP_CONN_TIMEOUT 3000  // conn timeout
181

182
bool taosValidIpAndPort(uint32_t ip, uint16_t port) {
133✔
183
  struct sockaddr_in serverAdd;
184
  SocketFd           fd;
185
  int32_t            reuse;
186
  int32_t            code = 0;
133✔
187

188
  // printf("open tcp server socket:0x%x:%hu", ip, port);
189

190
  bzero((char *)&serverAdd, sizeof(serverAdd));
133✔
191
  serverAdd.sin_family = AF_INET;
133✔
192
#ifdef WINDOWS
193
  serverAdd.sin_addr.s_addr = INADDR_ANY;
194
#else
195
  serverAdd.sin_addr.s_addr = ip;
133✔
196
#endif
197
  serverAdd.sin_port = (uint16_t)htons(port);
133✔
198

199
  fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
133✔
200
  if (-1 == fd) {  // exception
133!
201
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
202
    return false;
×
203
  }
204

205
  TdSocketPtr pSocket = (TdSocketPtr)taosMemoryMalloc(sizeof(TdSocket));
133!
206
  if (pSocket == NULL) {
133!
207
    TAOS_SKIP_ERROR(taosCloseSocketNoCheck1(fd));
×
208
    return false;
×
209
  }
210
  pSocket->refId = 0;
133✔
211
  pSocket->fd = fd;
133✔
212

213
  /* set REUSEADDR option, so the portnumber can be re-used */
214
  reuse = 1;
133✔
215
  if (taosSetSockOpt(pSocket, SOL_SOCKET, SO_REUSEADDR, (void *)&reuse, sizeof(reuse)) < 0) {
133!
216
    TAOS_SKIP_ERROR(taosCloseSocket(&pSocket));
×
217
    return false;
×
218
  }
219

220
  /* bind socket to server address */
221
  if (-1 == bind(pSocket->fd, (struct sockaddr *)&serverAdd, sizeof(serverAdd))) {
133✔
222
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
1✔
223
    TAOS_SKIP_ERROR(taosCloseSocket(&pSocket));
1✔
224
    return false;
1✔
225
  }
226

227
  TAOS_SKIP_ERROR(taosCloseSocket(&pSocket));
132✔
228

229
  return true;
132✔
230
}
231

232
int32_t taosBlockSIGPIPE() {
43,306✔
233
#ifdef WINDOWS
234
  return 0;
235
#else
236
  sigset_t signal_mask;
237
  (void)sigemptyset(&signal_mask);
43,306✔
238
  (void)sigaddset(&signal_mask, SIGPIPE);
43,278✔
239
  int32_t rc = pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);
43,314✔
240
  if (rc != 0) {
43,365!
241
    terrno = TAOS_SYSTEM_ERROR(rc);
×
242
    return terrno;
×
243
  }
244

245
  return 0;
43,365✔
246
#endif
247
}
248

249
int32_t taosGetIpv4FromFqdn(const char *fqdn, uint32_t *ip) {
16,202✔
250
  int32_t code = 0;
16,202✔
251
  OS_PARAM_CHECK(fqdn);
16,202✔
252
  OS_PARAM_CHECK(ip);
16,201✔
253
  int64_t limitMs = 1000;
16,200✔
254
  int64_t st = taosGetTimestampMs(), cost = 0;
16,198✔
255
#ifdef WINDOWS
256
  // Initialize Winsock
257
  WSADATA wsaData;
258
  int     iResult;
259
  iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
260
  if (iResult != 0) {
261
    code = TAOS_SYSTEM_WINSOCKET_ERROR(WSAGetLastError());
262
    goto _err;
263
  }
264
#endif
265

266
#if defined(LINUX)
267
  struct addrinfo hints = {0};
16,198✔
268
  hints.ai_family = AF_INET;
16,198✔
269
  hints.ai_socktype = SOCK_STREAM;
16,198✔
270

271
  struct addrinfo *result = NULL;
16,198✔
272
  bool             inRetry = false;
16,198✔
273

274
  while (true) {
×
275
    int32_t ret = getaddrinfo(fqdn, NULL, &hints, &result);
16,198✔
276
    if (ret) {
16,201✔
277
      if (EAI_AGAIN == ret && !inRetry) {
2!
278
        inRetry = true;
×
279
        continue;
×
280
      } else if (EAI_SYSTEM == ret) {
2!
281
        code = TAOS_SYSTEM_ERROR(ERRNO);
×
282
        goto _err;
16,202✔
283
      }
284

285
      code = TAOS_SYSTEM_ERROR(ERRNO);
2✔
286
      goto _err;
2✔
287
    }
288

289
    struct sockaddr    *sa = result->ai_addr;
16,199✔
290
    struct sockaddr_in *si = (struct sockaddr_in *)sa;
16,199✔
291
    struct in_addr      ia = si->sin_addr;
16,199✔
292

293
    *ip = ia.s_addr;
16,199✔
294

295
    freeaddrinfo(result);
16,199✔
296
    goto _err;
16,200✔
297
  }
298
#else
299
  struct addrinfo hints = {0};
300
  hints.ai_family = AF_INET;
301
  hints.ai_socktype = SOCK_STREAM;
302

303
  struct addrinfo *result = NULL;
304

305
  int32_t ret = getaddrinfo(fqdn, NULL, &hints, &result);
306
  if (result) {
307
    struct sockaddr    *sa = result->ai_addr;
308
    struct sockaddr_in *si = (struct sockaddr_in *)sa;
309
    struct in_addr      ia = si->sin_addr;
310
    *ip = ia.s_addr;
311
    freeaddrinfo(result);
312
    goto _err;
313
  } else {
314
#ifdef EAI_SYSTEM
315
    if (ret == EAI_SYSTEM) {
316
      // printf("failed to get the ip address, fqdn:%s, errno:%d, since:%s", fqdn, ERRNO, strerror(ERRNO));
317
    } else {
318
      // printf("failed to get the ip address, fqdn:%s, ret:%d, since:%s", fqdn, ret, gai_strerror(ret));
319
    }
320
#else
321
    // printf("failed to get the ip address, fqdn:%s, ret:%d, since:%s", fqdn, ret, gai_strerror(ret));
322
#endif
323

324
    *ip = 0xFFFFFFFF;
325
    code = TSDB_CODE_RPC_FQDN_ERROR;
326
    goto _err;
327
  }
328
#endif
329
_err:
16,202✔
330
  cost = taosGetTimestampMs() - st;
16,202✔
331
  if (cost >= limitMs) {
16,202✔
332
    uWarn("get ip from fqdn:%s, cost:%" PRId64 "ms", fqdn, cost);
3!
333
  }
334
  return code;
16,201✔
335
}
336

337
int32_t taosGetFqdn(char *fqdn) {
2,250✔
338
  OS_PARAM_CHECK(fqdn);
2,250!
339
#ifdef WINDOWS
340
  // Initialize Winsock
341
  WSADATA wsaData;
342
  int     iResult;
343
  iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
344
  if (iResult != 0) {
345
    // printf("WSAStartup failed: %d\n", iResult);
346
    return TAOS_SYSTEM_WINSOCKET_ERROR(WSAGetLastError());
347
  }
348
#endif
349
  char hostname[1024];
350
  hostname[1023] = '\0';
2,250✔
351
  int32_t code = taosGetlocalhostname(hostname, 1023);
2,250✔
352
  if (code) {
2,250!
353
    return code;
×
354
  }
355

356
#ifdef __APPLE__
357
  // on macosx, hostname -f has the form of xxx.local
358
  // which will block getaddrinfo for a few seconds if AI_CANONNAME is set
359
  // thus, we choose AF_INET (ipv4 for the moment) to make getaddrinfo return
360
  // immediately
361
  // hints.ai_family = AF_INET;
362
  tstrncpy(fqdn, hostname, TD_FQDN_LEN);
363
  tstrncpy(fqdn + strlen(hostname), ".local", TD_FQDN_LEN - strlen(hostname));
364
#else  // linux
365

366
#endif  // linux
367
#if defined(TD_ASTRA)
368
  tstrncpy(fqdn, hostname, TD_FQDN_LEN);  
369
#elif defined(LINUX)
370

371
  struct addrinfo  hints = {0};
2,250✔
372
  struct addrinfo *result = NULL;
2,250✔
373
  hints.ai_flags = AI_CANONNAME;
2,250✔
374

375
  while (true) {
×
376
    int32_t ret = getaddrinfo(hostname, NULL, &hints, &result);
2,250✔
377
    if (ret) {
2,250!
378
      if (EAI_AGAIN == ret) {
×
379
        continue;
×
380
      } else if (EAI_SYSTEM == ret) {
×
381
        terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
382
        return terrno;
×
383
      }
384

385
      terrno = TAOS_SYSTEM_ERROR(ret);
×
386
      return terrno;
×
387
    }
388

389
    break;
2,250✔
390
  }
391

392
  tstrncpy(fqdn, result->ai_canonname, TD_FQDN_LEN);
2,250✔
393

394
  freeaddrinfo(result);
2,250✔
395

396
#elif WINDOWS
397
  struct addrinfo  hints = {0};
398
  struct addrinfo *result = NULL;
399
  hints.ai_flags = AI_CANONNAME;
400

401
  int32_t ret = getaddrinfo(hostname, NULL, &hints, &result);
402
  if (!result) {
403
    // fprintf(stderr, "failed to get fqdn, code:%d, hostname:%s, reason:%s\n", ret, hostname, gai_strerror(ret));
404
    return TAOS_SYSTEM_WINSOCKET_ERROR(WSAGetLastError());
405
  }
406
  tstrncpy(fqdn, result->ai_canonname, TD_FQDN_LEN);
407
  freeaddrinfo(result);
408

409
#endif
410

411
  return 0;
2,250✔
412
}
413

414
void taosInetNtoa(char *ipstr, uint32_t ip) {
1,343✔
415
  if (ipstr == NULL) {
1,343✔
416
    return;
1✔
417
  }
418
  unsigned char *bytes = (unsigned char *) &ip;
1,342✔
419
  (void)snprintf(ipstr, TD_IP_LEN, "%d.%d.%d.%d", bytes[0], bytes[1], bytes[2], bytes[3]);
1,342✔
420
}
421

422
uint32_t taosInetAddr(const char *ipstr){
6✔
423
  if (ipstr == NULL) {
6✔
424
    return 0;
1✔
425
  }
426
  return inet_addr(ipstr);
5✔
427
}
428

429
int32_t taosIgnSIGPIPE() {
134✔
430
  sighandler_t h = signal(SIGPIPE, SIG_IGN);
134✔
431
  if (SIG_ERR == h) {
134!
432
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
433
    return terrno;
×
434
  }
435
  return 0;
134✔
436
}
437

438
/*
439
 * Set TCP connection timeout per-socket level.
440
 * ref [https://github.com/libuv/help/issues/54]
441
 */
442
int32_t taosCreateSocketWithTimeout(uint32_t timeout) {
14,029✔
443
#if defined(WINDOWS)
444
  SOCKET fd;
445
#else
446
  int fd;
447
#endif
448

449
  if ((fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {
14,029!
450
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
451
    return terrno;
×
452
  }
453

454
#if defined(WINDOWS)
455
  if (0 != setsockopt(fd, IPPROTO_TCP, TCP_MAXRT, (char *)&timeout, sizeof(timeout))) {
456
    taosCloseSocketNoCheck1(fd);
457
    return TAOS_SYSTEM_WINSOCKET_ERROR(WSAGetLastError());
458
  }
459
#elif defined(_TD_DARWIN_64)
460
  // invalid config
461
  // uint32_t conn_timeout_ms = timeout * 1000;
462
  // if (0 != setsockopt(fd, IPPROTO_TCP, TCP_CONNECTIONTIMEOUT, (char *)&conn_timeout_ms, sizeof(conn_timeout_ms))) {
463
  //  taosCloseSocketNoCheck1(fd);
464
  //  return -1;
465
  //}
466
#elif defined(TD_ASTRA) // TD_ASTRA_TODO
467
  uint32_t conn_timeout_ms = timeout;
468
  if (0 != setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&conn_timeout_ms, sizeof(conn_timeout_ms)) || 
469
      0 != setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&conn_timeout_ms, sizeof(conn_timeout_ms))) {
470
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
471
    TAOS_SKIP_ERROR(taosCloseSocketNoCheck1(fd));
472
    return terrno;
473
  }
474
#else  // Linux like systems
475
  uint32_t conn_timeout_ms = timeout;
14,031✔
476
  if (-1 == setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, (char *)&conn_timeout_ms, sizeof(conn_timeout_ms))) {
14,031!
477
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
478
    TAOS_SKIP_ERROR(taosCloseSocketNoCheck1(fd));
×
479
    return terrno;
×
480
  }
481
#endif
482

483
  return (int)fd;
14,029✔
484
}
485

486
int32_t taosWinSocketInit() {
1✔
487
#ifdef WINDOWS
488
  static int8_t flag = 0;
489
  if (atomic_val_compare_exchange_8(&flag, 0, 1) == 0) {
490
    WORD    wVersionRequested;
491
    WSADATA wsaData;
492
    wVersionRequested = MAKEWORD(1, 1);
493
    if (WSAStartup(wVersionRequested, &wsaData) != 0) {
494
      atomic_store_8(&flag, 0);
495
      int errorCode = WSAGetLastError();
496
      return terrno = TAOS_SYSTEM_WINSOCKET_ERROR(errorCode);
497
    }
498
  }
499
  return 0;
500
#else
501
#endif
502
  return 0;
1✔
503
}
504

505
uint64_t taosHton64(uint64_t val) {
2,347,066✔
506
#if defined(WINDOWS) || defined(DARWIN)
507
  return ((val & 0x00000000000000ff) << 7 * 8) | ((val & 0x000000000000ff00) << 5 * 8) |
508
         ((val & 0x0000000000ff0000) << 3 * 8) | ((val & 0x00000000ff000000) << 1 * 8) |
509
         ((val & 0x000000ff00000000) >> 1 * 8) | ((val & 0x0000ff0000000000) >> 3 * 8) |
510
         ((val & 0x00ff000000000000) >> 5 * 8) | ((val & 0xff00000000000000) >> 7 * 8);
511
#else
512
  if (__BYTE_ORDER == __LITTLE_ENDIAN) {
513
    return (((uint64_t)htonl((int)((val << 32) >> 32))) << 32) | (unsigned int)htonl((int)(val >> 32));
2,347,066✔
514
  } else if (__BYTE_ORDER == __BIG_ENDIAN) {
515
    return val;
516
  }
517
#endif
518
}
519

520
uint64_t taosNtoh64(uint64_t val) {
217,183✔
521
#if defined(WINDOWS) || defined(DARWIN)
522
  return taosHton64(val);
523
#else
524
  if (__BYTE_ORDER == __LITTLE_ENDIAN) {
525
    return (((uint64_t)htonl((int)((val << 32) >> 32))) << 32) | (unsigned int)htonl((int)(val >> 32));
217,183✔
526
  } else if (__BYTE_ORDER == __BIG_ENDIAN) {
527
    return val;
528
  }
529
#endif
530
}
531

532
int32_t taosSetSockOpt2(int32_t fd) {
424,084✔
533
#if defined(WINDOWS) || defined(DARWIN) || defined(TD_ASTRA)
534
  return 0;
535
#else
536
  int32_t ret = setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, (int[]){1}, sizeof(int));
424,084✔
537
  if (ret < 0) {
424,161!
538
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
539
    return terrno;
×
540
  } else {
541
    return 0;
424,175✔
542
  }
543
#endif
544
  return 0;
545
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc