Coverage Report

Created: 2026-01-09 06:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/libfreerdp/core/tcp.c
Line
Count
Source
1
/**
2
 * FreeRDP: A Remote Desktop Protocol Implementation
3
 * Transmission Control Protocol (TCP)
4
 *
5
 * Copyright 2011 Vic Lee
6
 * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
21
#include <freerdp/config.h>
22
23
#include "settings.h"
24
25
#include <time.h>
26
#include <errno.h>
27
#include <fcntl.h>
28
29
#include <winpr/crt.h>
30
#include <winpr/platform.h>
31
#include <winpr/winsock.h>
32
33
#include "rdp.h"
34
#include "utils.h"
35
36
#if !defined(_WIN32)
37
38
#include <netdb.h>
39
#include <unistd.h>
40
#include <sys/ioctl.h>
41
#include <sys/socket.h>
42
#include <netinet/in.h>
43
#include <netinet/tcp.h>
44
#include <net/if.h>
45
#include <sys/types.h>
46
#include <arpa/inet.h>
47
48
#ifdef WINPR_HAVE_POLL_H
49
#include <poll.h>
50
#else
51
#include <time.h>
52
#include <sys/select.h>
53
#endif
54
55
#if defined(__FreeBSD__) || defined(__OpenBSD__)
56
#ifndef SOL_TCP
57
#define SOL_TCP IPPROTO_TCP
58
#endif
59
#endif
60
61
#ifdef __APPLE__
62
#ifndef SOL_TCP
63
#define SOL_TCP IPPROTO_TCP
64
#endif
65
#ifndef TCP_KEEPIDLE
66
#define TCP_KEEPIDLE TCP_KEEPALIVE
67
#endif
68
#endif
69
70
#else
71
72
#include <winpr/windows.h>
73
74
#include <winpr/crt.h>
75
76
#define SHUT_RDWR SD_BOTH
77
#define close(_fd) closesocket(_fd)
78
79
#endif
80
81
#include <freerdp/log.h>
82
83
#include <winpr/stream.h>
84
85
#include "tcp.h"
86
#include "../crypto/opensslcompat.h"
87
88
#if defined(HAVE_AF_VSOCK_H)
89
#include <ctype.h>
90
#include <linux/vm_sockets.h>
91
#endif
92
93
0
#define TAG FREERDP_TAG("core")
94
95
/* Simple Socket BIO */
96
97
typedef struct
98
{
99
  SOCKET socket;
100
  HANDLE hEvent;
101
} WINPR_BIO_SIMPLE_SOCKET;
102
103
static int transport_bio_simple_init(BIO* bio, SOCKET socket, int shutdown);
104
static int transport_bio_simple_uninit(BIO* bio);
105
106
static int transport_bio_simple_write(BIO* bio, const char* buf, int size)
107
104
{
108
104
  int error = 0;
109
104
  int status = 0;
110
104
  WINPR_BIO_SIMPLE_SOCKET* ptr = (WINPR_BIO_SIMPLE_SOCKET*)BIO_get_data(bio);
111
112
104
  if (!buf)
113
0
    return 0;
114
115
104
  BIO_clear_flags(bio, BIO_FLAGS_WRITE);
116
104
  status = _send(ptr->socket, buf, size, 0);
117
118
104
  if (status <= 0)
119
104
  {
120
104
    error = WSAGetLastError();
121
122
104
    if ((error == WSAEWOULDBLOCK) || (error == WSAEINTR) || (error == WSAEINPROGRESS) ||
123
104
        (error == WSAEALREADY))
124
0
    {
125
0
      BIO_set_flags(bio, (BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY));
126
0
    }
127
104
    else
128
104
    {
129
104
      BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
130
104
    }
131
104
  }
132
133
104
  return status;
134
104
}
135
136
static int transport_bio_simple_read(BIO* bio, char* buf, int size)
137
0
{
138
0
  int error = 0;
139
0
  int status = 0;
140
0
  WINPR_BIO_SIMPLE_SOCKET* ptr = (WINPR_BIO_SIMPLE_SOCKET*)BIO_get_data(bio);
141
142
0
  if (!buf)
143
0
    return 0;
144
145
0
  BIO_clear_flags(bio, BIO_FLAGS_READ);
146
0
  (void)WSAResetEvent(ptr->hEvent);
147
0
  status = _recv(ptr->socket, buf, size, 0);
148
149
0
  if (status > 0)
150
0
  {
151
0
    return status;
152
0
  }
153
154
0
  if (status == 0)
155
0
  {
156
0
    BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
157
0
    return 0;
158
0
  }
159
160
0
  error = WSAGetLastError();
161
162
0
  if ((error == WSAEWOULDBLOCK) || (error == WSAEINTR) || (error == WSAEINPROGRESS) ||
163
0
      (error == WSAEALREADY))
164
0
  {
165
0
    BIO_set_flags(bio, (BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY));
166
0
  }
167
0
  else
168
0
  {
169
0
    BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
170
0
  }
171
172
0
  return -1;
173
0
}
174
175
static int transport_bio_simple_puts(WINPR_ATTR_UNUSED BIO* bio, WINPR_ATTR_UNUSED const char* str)
176
0
{
177
0
  return -2;
178
0
}
179
180
static int transport_bio_simple_gets(WINPR_ATTR_UNUSED BIO* bio, WINPR_ATTR_UNUSED char* str,
181
                                     WINPR_ATTR_UNUSED int size)
182
0
{
183
0
  return 1;
184
0
}
185
186
static long transport_bio_simple_ctrl(BIO* bio, int cmd, long arg1, void* arg2)
187
24.5k
{
188
24.5k
  int status = -1;
189
24.5k
  WINPR_BIO_SIMPLE_SOCKET* ptr = (WINPR_BIO_SIMPLE_SOCKET*)BIO_get_data(bio);
190
191
24.5k
  switch (cmd)
192
24.5k
  {
193
0
    case BIO_C_SET_SOCKET:
194
0
      transport_bio_simple_uninit(bio);
195
0
      transport_bio_simple_init(bio, (SOCKET)arg2, (int)arg1);
196
0
      return 1;
197
0
    case BIO_C_GET_SOCKET:
198
0
      if (!BIO_get_init(bio) || !arg2)
199
0
        return 0;
200
201
0
      *((SOCKET*)arg2) = ptr->socket;
202
0
      return 1;
203
0
    case BIO_C_GET_EVENT:
204
0
      if (!BIO_get_init(bio) || !arg2)
205
0
        return 0;
206
207
0
      *((HANDLE*)arg2) = ptr->hEvent;
208
0
      return 1;
209
8.19k
    case BIO_C_SET_NONBLOCK:
210
8.19k
    {
211
8.19k
#ifndef _WIN32
212
8.19k
      int flags = 0;
213
8.19k
      flags = fcntl((int)ptr->socket, F_GETFL);
214
215
8.19k
      if (flags == -1)
216
0
        return 0;
217
218
8.19k
      if (arg1)
219
8.19k
        (void)fcntl((int)ptr->socket, F_SETFL, flags | O_NONBLOCK);
220
0
      else
221
0
        (void)fcntl((int)ptr->socket, F_SETFL, flags & ~(O_NONBLOCK));
222
223
#else
224
      /* the internal socket is always non-blocking */
225
#endif
226
8.19k
      return 1;
227
8.19k
    }
228
0
    case BIO_C_WAIT_READ:
229
0
    {
230
0
      int timeout = (int)arg1;
231
0
      int sockfd = (int)ptr->socket;
232
0
#ifdef WINPR_HAVE_POLL_H
233
0
      struct pollfd pollset;
234
0
      pollset.fd = sockfd;
235
0
      pollset.events = POLLIN;
236
0
      pollset.revents = 0;
237
238
0
      do
239
0
      {
240
0
        status = poll(&pollset, 1, timeout);
241
0
      } while ((status < 0) && (errno == EINTR));
242
243
#else
244
      fd_set rset = { 0 };
245
      struct timeval tv = { 0 };
246
      FD_ZERO(&rset);
247
      FD_SET(sockfd, &rset);
248
249
      if (timeout)
250
      {
251
        tv.tv_sec = timeout / 1000;
252
        tv.tv_usec = (timeout % 1000) * 1000;
253
      }
254
255
      do
256
      {
257
        status = select(sockfd + 1, &rset, NULL, NULL, timeout ? &tv : NULL);
258
      } while ((status < 0) && (errno == EINTR));
259
260
#endif
261
      /* Convert timeout to error return */
262
0
      if (status == 0)
263
0
        errno = ETIMEDOUT;
264
0
    }
265
0
    break;
266
267
0
    case BIO_C_WAIT_WRITE:
268
0
    {
269
0
      int timeout = (int)arg1;
270
0
      int sockfd = (int)ptr->socket;
271
0
#ifdef WINPR_HAVE_POLL_H
272
0
      struct pollfd pollset;
273
0
      pollset.fd = sockfd;
274
0
      pollset.events = POLLOUT;
275
0
      pollset.revents = 0;
276
277
0
      do
278
0
      {
279
0
        status = poll(&pollset, 1, timeout);
280
0
      } while ((status < 0) && (errno == EINTR));
281
282
#else
283
      fd_set rset = { 0 };
284
      struct timeval tv = { 0 };
285
      FD_ZERO(&rset);
286
      FD_SET(sockfd, &rset);
287
288
      if (timeout)
289
      {
290
        tv.tv_sec = timeout / 1000;
291
        tv.tv_usec = (timeout % 1000) * 1000;
292
      }
293
294
      do
295
      {
296
        status = select(sockfd + 1, NULL, &rset, NULL, timeout ? &tv : NULL);
297
      } while ((status < 0) && (errno == EINTR));
298
299
#endif
300
      /* Convert timeout to error return */
301
0
      if (status == 0)
302
0
        errno = ETIMEDOUT;
303
0
    }
304
0
    break;
305
306
8.19k
    case BIO_C_SET_FD:
307
8.19k
      if (arg2)
308
8.19k
      {
309
8.19k
        transport_bio_simple_uninit(bio);
310
8.19k
        transport_bio_simple_init(bio, (SOCKET) * ((int*)arg2), (int)arg1);
311
8.19k
        status = 1;
312
8.19k
      }
313
314
8.19k
      break;
315
316
0
    case BIO_C_GET_FD:
317
0
      if (BIO_get_init(bio))
318
0
      {
319
0
        if (arg2)
320
0
          *((int*)arg2) = (int)ptr->socket;
321
322
0
        status = (int)ptr->socket;
323
0
      }
324
325
0
      break;
326
327
0
    case BIO_CTRL_GET_CLOSE:
328
0
      status = BIO_get_shutdown(bio);
329
0
      break;
330
331
0
    case BIO_CTRL_SET_CLOSE:
332
0
      BIO_set_shutdown(bio, (int)arg1);
333
0
      status = 1;
334
0
      break;
335
336
0
    case BIO_CTRL_FLUSH:
337
0
    case BIO_CTRL_DUP:
338
0
      status = 1;
339
0
      break;
340
341
8.19k
    default:
342
8.19k
      status = 0;
343
8.19k
      break;
344
24.5k
  }
345
346
16.3k
  return status;
347
24.5k
}
348
349
static int transport_bio_simple_init(BIO* bio, SOCKET socket, int shutdown)
350
8.19k
{
351
8.19k
  WINPR_BIO_SIMPLE_SOCKET* ptr = (WINPR_BIO_SIMPLE_SOCKET*)BIO_get_data(bio);
352
8.19k
  ptr->socket = socket;
353
8.19k
  BIO_set_shutdown(bio, shutdown);
354
8.19k
  BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
355
8.19k
  BIO_set_init(bio, 1);
356
8.19k
  ptr->hEvent = WSACreateEvent();
357
358
8.19k
  if (!ptr->hEvent)
359
0
    return 0;
360
361
  /* WSAEventSelect automatically sets the socket in non-blocking mode */
362
8.19k
  if (WSAEventSelect(ptr->socket, ptr->hEvent, FD_READ | FD_ACCEPT | FD_CLOSE))
363
0
  {
364
0
    WLog_ERR(TAG, "WSAEventSelect returned 0x%08X", WSAGetLastError());
365
0
    return 0;
366
0
  }
367
368
8.19k
  return 1;
369
8.19k
}
370
371
static int transport_bio_simple_uninit(BIO* bio)
372
16.3k
{
373
16.3k
  WINPR_BIO_SIMPLE_SOCKET* ptr = (WINPR_BIO_SIMPLE_SOCKET*)BIO_get_data(bio);
374
375
16.3k
  if (BIO_get_shutdown(bio))
376
16.3k
  {
377
16.3k
    if (BIO_get_init(bio) && ptr)
378
8.19k
    {
379
8.19k
      _shutdown(ptr->socket, SD_BOTH);
380
8.19k
      closesocket(ptr->socket);
381
8.19k
      ptr->socket = 0;
382
8.19k
    }
383
16.3k
  }
384
385
16.3k
  if (ptr && ptr->hEvent)
386
8.19k
  {
387
8.19k
    (void)CloseHandle(ptr->hEvent);
388
8.19k
    ptr->hEvent = NULL;
389
8.19k
  }
390
391
16.3k
  BIO_set_init(bio, 0);
392
16.3k
  BIO_set_flags(bio, 0);
393
16.3k
  return 1;
394
16.3k
}
395
396
static int transport_bio_simple_new(BIO* bio)
397
8.19k
{
398
8.19k
  WINPR_BIO_SIMPLE_SOCKET* ptr = NULL;
399
8.19k
  BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
400
8.19k
  ptr = (WINPR_BIO_SIMPLE_SOCKET*)calloc(1, sizeof(WINPR_BIO_SIMPLE_SOCKET));
401
402
8.19k
  if (!ptr)
403
0
    return 0;
404
405
8.19k
  BIO_set_data(bio, ptr);
406
8.19k
  return 1;
407
8.19k
}
408
409
static int transport_bio_simple_free(BIO* bio)
410
8.19k
{
411
8.19k
  WINPR_BIO_SIMPLE_SOCKET* ptr = NULL;
412
413
8.19k
  if (!bio)
414
0
    return 0;
415
416
8.19k
  transport_bio_simple_uninit(bio);
417
8.19k
  ptr = (WINPR_BIO_SIMPLE_SOCKET*)BIO_get_data(bio);
418
419
8.19k
  if (ptr)
420
8.19k
  {
421
8.19k
    BIO_set_data(bio, NULL);
422
8.19k
    free(ptr);
423
8.19k
  }
424
425
8.19k
  return 1;
426
8.19k
}
427
428
BIO_METHOD* BIO_s_simple_socket(void)
429
8.19k
{
430
8.19k
  static BIO_METHOD* bio_methods = NULL;
431
432
8.19k
  if (bio_methods == NULL)
433
1
  {
434
1
    if (!(bio_methods = BIO_meth_new(BIO_TYPE_SIMPLE, "SimpleSocket")))
435
0
      return NULL;
436
437
1
    BIO_meth_set_write(bio_methods, transport_bio_simple_write);
438
1
    BIO_meth_set_read(bio_methods, transport_bio_simple_read);
439
1
    BIO_meth_set_puts(bio_methods, transport_bio_simple_puts);
440
1
    BIO_meth_set_gets(bio_methods, transport_bio_simple_gets);
441
1
    BIO_meth_set_ctrl(bio_methods, transport_bio_simple_ctrl);
442
1
    BIO_meth_set_create(bio_methods, transport_bio_simple_new);
443
1
    BIO_meth_set_destroy(bio_methods, transport_bio_simple_free);
444
1
  }
445
446
8.19k
  return bio_methods;
447
8.19k
}
448
449
/* Buffered Socket BIO */
450
451
typedef struct
452
{
453
  BIO* bufferedBio;
454
  BOOL readBlocked;
455
  BOOL writeBlocked;
456
  RingBuffer xmitBuffer;
457
} WINPR_BIO_BUFFERED_SOCKET;
458
459
static int transport_bio_buffered_write(BIO* bio, const char* buf, int num)
460
104
{
461
104
  int ret = num;
462
104
  int nchunks = 0;
463
104
  size_t committedBytes = 0;
464
104
  DataChunk chunks[2] = { 0 };
465
104
  WINPR_BIO_BUFFERED_SOCKET* ptr = (WINPR_BIO_BUFFERED_SOCKET*)BIO_get_data(bio);
466
104
  BIO* next_bio = NULL;
467
468
104
  WINPR_ASSERT(bio);
469
104
  WINPR_ASSERT(ptr);
470
104
  if (num < 0)
471
0
    return num;
472
473
104
  ptr->writeBlocked = FALSE;
474
104
  BIO_clear_flags(bio, BIO_FLAGS_WRITE);
475
476
  /* we directly append extra bytes in the xmit buffer, this could be prevented
477
   * but for now it makes the code more simple.
478
   */
479
104
  if (buf && (num > 0) && !ringbuffer_write(&ptr->xmitBuffer, (const BYTE*)buf, (size_t)num))
480
0
  {
481
0
    WLog_ERR(TAG, "an error occurred when writing (num: %d)", num);
482
0
    return -1;
483
0
  }
484
485
104
  nchunks = ringbuffer_peek(&ptr->xmitBuffer, chunks, ringbuffer_used(&ptr->xmitBuffer));
486
104
  next_bio = BIO_next(bio);
487
488
104
  for (int i = 0; i < nchunks; i++)
489
104
  {
490
104
    while (chunks[i].size)
491
104
    {
492
104
      ERR_clear_error();
493
494
104
      const size_t wr = MIN(INT32_MAX, chunks[i].size);
495
104
      const int status = BIO_write(next_bio, chunks[i].data, (int)wr);
496
497
104
      if (status <= 0)
498
104
      {
499
104
        if (!BIO_should_retry(next_bio))
500
104
        {
501
104
          BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
502
104
          ret = -1; /* fatal error */
503
104
          goto out;
504
104
        }
505
506
0
        if (BIO_should_write(next_bio))
507
0
        {
508
0
          BIO_set_flags(bio, BIO_FLAGS_WRITE);
509
0
          ptr->writeBlocked = TRUE;
510
0
          goto out; /* EWOULDBLOCK */
511
0
        }
512
0
      }
513
0
      else
514
0
      {
515
0
        committedBytes += (size_t)status;
516
0
        chunks[i].size -= (size_t)status;
517
0
        chunks[i].data += status;
518
0
      }
519
104
    }
520
104
  }
521
522
104
out:
523
104
  ringbuffer_commit_read_bytes(&ptr->xmitBuffer, committedBytes);
524
104
  return ret;
525
104
}
526
527
static int transport_bio_buffered_read(BIO* bio, char* buf, int size)
528
0
{
529
0
  int status = 0;
530
0
  WINPR_BIO_BUFFERED_SOCKET* ptr = (WINPR_BIO_BUFFERED_SOCKET*)BIO_get_data(bio);
531
0
  BIO* next_bio = BIO_next(bio);
532
0
  ptr->readBlocked = FALSE;
533
0
  BIO_clear_flags(bio, BIO_FLAGS_READ);
534
0
  ERR_clear_error();
535
0
  status = BIO_read(next_bio, buf, size);
536
537
0
  if (status <= 0)
538
0
  {
539
0
    if (!BIO_should_retry(next_bio))
540
0
    {
541
0
      BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
542
0
      goto out;
543
0
    }
544
545
0
    BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
546
547
0
    if (BIO_should_read(next_bio))
548
0
    {
549
0
      BIO_set_flags(bio, BIO_FLAGS_READ);
550
0
      ptr->readBlocked = TRUE;
551
0
      goto out;
552
0
    }
553
0
  }
554
555
0
out:
556
0
  return status;
557
0
}
558
559
static int transport_bio_buffered_puts(WINPR_ATTR_UNUSED BIO* bio,
560
                                       WINPR_ATTR_UNUSED const char* str)
561
0
{
562
0
  return 1;
563
0
}
564
565
static int transport_bio_buffered_gets(WINPR_ATTR_UNUSED BIO* bio, WINPR_ATTR_UNUSED char* str,
566
                                       WINPR_ATTR_UNUSED int size)
567
0
{
568
0
  return 1;
569
0
}
570
571
static long transport_bio_buffered_ctrl(BIO* bio, int cmd, long arg1, void* arg2)
572
16.3k
{
573
16.3k
  long status = -1;
574
16.3k
  WINPR_BIO_BUFFERED_SOCKET* ptr = (WINPR_BIO_BUFFERED_SOCKET*)BIO_get_data(bio);
575
576
16.3k
  switch (cmd)
577
16.3k
  {
578
0
    case BIO_CTRL_FLUSH:
579
0
      if (!ringbuffer_used(&ptr->xmitBuffer))
580
0
        status = 1;
581
0
      else
582
0
        status = (transport_bio_buffered_write(bio, NULL, 0) >= 0) ? 1 : -1;
583
584
0
      break;
585
586
0
    case BIO_CTRL_WPENDING:
587
0
      status = WINPR_ASSERTING_INT_CAST(long, ringbuffer_used(&ptr->xmitBuffer));
588
0
      break;
589
590
0
    case BIO_CTRL_PENDING:
591
0
      status = 0;
592
0
      break;
593
594
0
    case BIO_C_READ_BLOCKED:
595
0
      status = (int)ptr->readBlocked;
596
0
      break;
597
598
0
    case BIO_C_WRITE_BLOCKED:
599
0
      status = (int)ptr->writeBlocked;
600
0
      break;
601
602
16.3k
    default:
603
16.3k
      status = BIO_ctrl(BIO_next(bio), cmd, arg1, arg2);
604
16.3k
      break;
605
16.3k
  }
606
607
16.3k
  return status;
608
16.3k
}
609
610
static int transport_bio_buffered_new(BIO* bio)
611
8.19k
{
612
8.19k
  WINPR_BIO_BUFFERED_SOCKET* ptr = NULL;
613
8.19k
  BIO_set_init(bio, 1);
614
8.19k
  BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
615
8.19k
  ptr = (WINPR_BIO_BUFFERED_SOCKET*)calloc(1, sizeof(WINPR_BIO_BUFFERED_SOCKET));
616
617
8.19k
  if (!ptr)
618
0
    return -1;
619
620
8.19k
  BIO_set_data(bio, (void*)ptr);
621
622
8.19k
  if (!ringbuffer_init(&ptr->xmitBuffer, 0x10000))
623
0
    return -1;
624
625
8.19k
  return 1;
626
8.19k
}
627
628
/* Free the buffered BIO.
629
 * Do not free other elements in the BIO stack,
630
 * let BIO_free_all handle that. */
631
static int transport_bio_buffered_free(BIO* bio)
632
8.19k
{
633
8.19k
  WINPR_BIO_BUFFERED_SOCKET* ptr = (WINPR_BIO_BUFFERED_SOCKET*)BIO_get_data(bio);
634
635
8.19k
  if (!ptr)
636
0
    return 0;
637
638
8.19k
  ringbuffer_destroy(&ptr->xmitBuffer);
639
8.19k
  free(ptr);
640
8.19k
  return 1;
641
8.19k
}
642
643
BIO_METHOD* BIO_s_buffered_socket(void)
644
8.19k
{
645
8.19k
  static BIO_METHOD* bio_methods = NULL;
646
647
8.19k
  if (bio_methods == NULL)
648
1
  {
649
1
    if (!(bio_methods = BIO_meth_new(BIO_TYPE_BUFFERED, "BufferedSocket")))
650
0
      return NULL;
651
652
1
    BIO_meth_set_write(bio_methods, transport_bio_buffered_write);
653
1
    BIO_meth_set_read(bio_methods, transport_bio_buffered_read);
654
1
    BIO_meth_set_puts(bio_methods, transport_bio_buffered_puts);
655
1
    BIO_meth_set_gets(bio_methods, transport_bio_buffered_gets);
656
1
    BIO_meth_set_ctrl(bio_methods, transport_bio_buffered_ctrl);
657
1
    BIO_meth_set_create(bio_methods, transport_bio_buffered_new);
658
1
    BIO_meth_set_destroy(bio_methods, transport_bio_buffered_free);
659
1
  }
660
661
8.19k
  return bio_methods;
662
8.19k
}
663
664
char* freerdp_tcp_address_to_string(const struct sockaddr_storage* addr, BOOL* pIPv6)
665
0
{
666
0
  char ipAddress[INET6_ADDRSTRLEN + 1] = { 0 };
667
0
  const struct sockaddr_in6* sockaddr_ipv6 = (const struct sockaddr_in6*)addr;
668
0
  const struct sockaddr_in* sockaddr_ipv4 = (const struct sockaddr_in*)addr;
669
670
0
  if (addr == NULL)
671
0
  {
672
0
    return NULL;
673
0
  }
674
675
0
  switch (sockaddr_ipv4->sin_family)
676
0
  {
677
0
    case AF_INET:
678
0
      if (!inet_ntop(sockaddr_ipv4->sin_family, &sockaddr_ipv4->sin_addr, ipAddress,
679
0
                     sizeof(ipAddress)))
680
0
        return NULL;
681
682
0
      break;
683
684
0
    case AF_INET6:
685
0
      if (!inet_ntop(sockaddr_ipv6->sin6_family, &sockaddr_ipv6->sin6_addr, ipAddress,
686
0
                     sizeof(ipAddress)))
687
0
        return NULL;
688
689
0
      break;
690
691
0
    case AF_UNIX:
692
0
      (void)sprintf_s(ipAddress, ARRAYSIZE(ipAddress), "127.0.0.1");
693
0
      break;
694
695
0
    default:
696
0
      return NULL;
697
0
  }
698
699
0
  if (pIPv6 != NULL)
700
0
  {
701
0
    *pIPv6 = (sockaddr_ipv4->sin_family == AF_INET6);
702
0
  }
703
704
0
  return _strdup(ipAddress);
705
0
}
706
707
static bool freerdp_tcp_get_ip_address(rdpSettings* settings, int sockfd)
708
0
{
709
0
  WINPR_ASSERT(settings);
710
711
0
  struct sockaddr_storage saddr = { 0 };
712
0
  socklen_t length = sizeof(struct sockaddr_storage);
713
714
0
  if (!freerdp_settings_set_string(settings, FreeRDP_ClientAddress, NULL))
715
0
    return false;
716
0
  if (sockfd < 0)
717
0
    return false;
718
0
  if (getsockname(sockfd, (struct sockaddr*)&saddr, &length) != 0)
719
0
    return false;
720
0
  settings->ClientAddress = freerdp_tcp_address_to_string(&saddr, &settings->IPv6Enabled);
721
0
  return settings->ClientAddress != NULL;
722
0
}
723
724
char* freerdp_tcp_get_peer_address(SOCKET sockfd)
725
0
{
726
0
  struct sockaddr_storage saddr = { 0 };
727
0
  socklen_t length = sizeof(struct sockaddr_storage);
728
729
0
  if (getpeername((int)sockfd, (struct sockaddr*)&saddr, &length) != 0)
730
0
  {
731
0
    return NULL;
732
0
  }
733
734
0
  return freerdp_tcp_address_to_string(&saddr, NULL);
735
0
}
736
737
static int freerdp_uds_connect(const char* path)
738
0
{
739
0
#ifndef _WIN32
740
0
  int status = 0;
741
0
  int sockfd = 0;
742
0
  struct sockaddr_un addr = { 0 };
743
0
  sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
744
745
0
  if (sockfd == -1)
746
0
  {
747
0
    WLog_ERR(TAG, "socket");
748
0
    return -1;
749
0
  }
750
751
0
  addr.sun_family = AF_UNIX;
752
0
  strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
753
0
  status = connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));
754
755
0
  if (status < 0)
756
0
  {
757
0
    WLog_ERR(TAG, "connect");
758
0
    close(sockfd);
759
0
    return -1;
760
0
  }
761
762
0
  return sockfd;
763
#else /* ifndef _WIN32 */
764
  return -1;
765
#endif
766
0
}
767
768
struct addrinfo* freerdp_tcp_resolve_host(const char* hostname, int port, int ai_flags)
769
0
{
770
0
  char* service = NULL;
771
0
  char port_str[16];
772
0
  int status = 0;
773
0
  struct addrinfo hints = { 0 };
774
0
  struct addrinfo* result = NULL;
775
0
  hints.ai_family = AF_UNSPEC;
776
0
  hints.ai_socktype = SOCK_STREAM;
777
0
  hints.ai_flags = ai_flags;
778
779
0
  if (port >= 0)
780
0
  {
781
0
    (void)sprintf_s(port_str, sizeof(port_str) - 1, "%d", port);
782
0
    service = port_str;
783
0
  }
784
785
0
  status = getaddrinfo(hostname, service, &hints, &result);
786
787
0
  if (status)
788
0
    return NULL;
789
790
0
  return result;
791
0
}
792
793
static BOOL freerdp_tcp_is_hostname_resolvable(rdpContext* context, const char* hostname)
794
0
{
795
0
  struct addrinfo* result = freerdp_tcp_resolve_host(hostname, -1, 0);
796
797
0
  if (!result)
798
0
  {
799
0
    freerdp_set_last_error_if_not(context, FREERDP_ERROR_DNS_NAME_NOT_FOUND);
800
801
0
    return FALSE;
802
0
  }
803
804
0
  freerdp_set_last_error_log(context, 0);
805
0
  freeaddrinfo(result);
806
0
  return TRUE;
807
0
}
808
809
static BOOL freerdp_tcp_connect_timeout(rdpContext* context, int sockfd, struct sockaddr* addr,
810
                                        socklen_t addrlen, UINT32 timeout)
811
0
{
812
0
  BOOL rc = FALSE;
813
0
  HANDLE handles[2] = { 0 };
814
0
  DWORD count = 0;
815
0
  u_long arg = 0;
816
0
  DWORD tout = (timeout > 0) ? timeout : INFINITE;
817
818
0
  handles[count] = CreateEvent(NULL, TRUE, FALSE, NULL);
819
820
0
  if (!handles[count])
821
0
    return FALSE;
822
823
0
  const int wsastatus = WSAEventSelect((SOCKET)sockfd, handles[count++],
824
0
                                       FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE);
825
826
0
  if (wsastatus < 0)
827
0
  {
828
0
    WLog_ERR(TAG, "WSAEventSelect failed with %d", WSAGetLastError());
829
0
    goto fail;
830
0
  }
831
832
0
  handles[count++] = utils_get_abort_event(context->rdp);
833
834
0
  {
835
0
    const int constatus =
836
0
        _connect((SOCKET)sockfd, addr, WINPR_ASSERTING_INT_CAST(int, addrlen));
837
0
    if (constatus < 0)
838
0
    {
839
0
      const int estatus = WSAGetLastError();
840
841
0
      switch (estatus)
842
0
      {
843
0
        case WSAEINPROGRESS:
844
0
        case WSAEWOULDBLOCK:
845
0
          break;
846
847
0
        default:
848
0
          goto fail;
849
0
      }
850
0
    }
851
0
  }
852
853
0
  {
854
0
    const DWORD wstatus = WaitForMultipleObjects(count, handles, FALSE, tout);
855
0
    if (WAIT_OBJECT_0 != wstatus)
856
0
      goto fail;
857
0
  }
858
859
0
  {
860
0
    INT32 optval = 0;
861
0
    socklen_t optlen = sizeof(optval);
862
0
    if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) < 0)
863
0
      goto fail;
864
865
0
    if (optval != 0)
866
0
    {
867
0
      char ebuffer[256] = { 0 };
868
0
      WLog_DBG(TAG, "connect failed with error: %s [%" PRIu32 "]",
869
0
               winpr_strerror(optval, ebuffer, sizeof(ebuffer)), optval);
870
0
      goto fail;
871
0
    }
872
0
  }
873
874
0
  {
875
0
    const int status = WSAEventSelect((SOCKET)sockfd, handles[0], 0);
876
0
    if (status < 0)
877
0
    {
878
0
      WLog_ERR(TAG, "WSAEventSelect failed with %d", WSAGetLastError());
879
0
      goto fail;
880
0
    }
881
0
  }
882
883
0
  if (_ioctlsocket((SOCKET)sockfd, FIONBIO, &arg) != 0)
884
0
    goto fail;
885
886
0
  rc = TRUE;
887
0
fail:
888
0
  (void)CloseHandle(handles[0]);
889
0
  return rc;
890
0
}
891
892
typedef struct
893
{
894
  SOCKET s;
895
  struct addrinfo* addr;
896
  struct addrinfo* result;
897
} t_peer;
898
899
static void peer_free(t_peer* peer)
900
0
{
901
0
  if (peer->s != INVALID_SOCKET)
902
0
    closesocket(peer->s);
903
904
0
  freeaddrinfo(peer->addr);
905
0
  memset(peer, 0, sizeof(t_peer));
906
0
  peer->s = INVALID_SOCKET;
907
0
}
908
909
static int freerdp_tcp_connect_multi(rdpContext* context, char** hostnames, const UINT32* ports,
910
                                     UINT32 count, UINT16 port, WINPR_ATTR_UNUSED UINT32 timeout)
911
0
{
912
0
  UINT32 sindex = count;
913
0
  SOCKET sockfd = INVALID_SOCKET;
914
0
  struct addrinfo* addr = NULL;
915
0
  struct addrinfo* result = NULL;
916
917
0
  HANDLE* events = (HANDLE*)calloc(count + 1, sizeof(HANDLE));
918
0
  t_peer* peers = (t_peer*)calloc(count, sizeof(t_peer));
919
920
0
  if (!peers || !events || (count < 1))
921
0
  {
922
0
    free(peers);
923
0
    free((void*)events);
924
0
    return -1;
925
0
  }
926
927
0
  for (UINT32 index = 0; index < count; index++)
928
0
  {
929
0
    int curPort = port;
930
931
0
    if (ports)
932
0
      curPort = WINPR_ASSERTING_INT_CAST(int, ports[index]);
933
934
0
    result = freerdp_tcp_resolve_host(hostnames[index], curPort, 0);
935
936
0
    if (!result)
937
0
      continue;
938
939
0
    addr = result;
940
941
0
    if ((addr->ai_family == AF_INET6) && (addr->ai_next != 0))
942
0
    {
943
0
      while ((addr = addr->ai_next))
944
0
      {
945
0
        if (addr->ai_family == AF_INET)
946
0
          break;
947
0
      }
948
949
0
      if (!addr)
950
0
        addr = result;
951
0
    }
952
953
0
    peers[index].s = _socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
954
955
0
    if (peers[index].s == INVALID_SOCKET)
956
0
    {
957
0
      freeaddrinfo(result);
958
0
      continue;
959
0
    }
960
961
0
    peers[index].addr = addr;
962
0
    peers[index].result = result;
963
0
  }
964
965
0
  for (UINT32 index = 0; index < count; index++)
966
0
  {
967
0
    sockfd = peers[index].s;
968
0
    addr = peers[index].addr;
969
970
0
    if ((sockfd == INVALID_SOCKET) || (!addr))
971
0
      continue;
972
973
    /* blocking tcp connect */
974
0
    const int rc =
975
0
        _connect(sockfd, addr->ai_addr, WINPR_ASSERTING_INT_CAST(int, addr->ai_addrlen));
976
977
0
    if (rc >= 0)
978
0
    {
979
      /* connection success */
980
0
      sindex = index;
981
0
      break;
982
0
    }
983
0
  }
984
985
0
  if (sindex < count)
986
0
  {
987
0
    sockfd = peers[sindex].s;
988
0
    peers[sindex].s = INVALID_SOCKET;
989
0
  }
990
0
  else
991
0
    freerdp_set_last_error_log(context, FREERDP_ERROR_CONNECT_CANCELLED);
992
993
0
  for (UINT32 index = 0; index < count; index++)
994
0
    peer_free(&peers[index]);
995
996
0
  free(peers);
997
0
  free((void*)events);
998
0
  return (int)sockfd;
999
0
}
1000
1001
BOOL freerdp_tcp_set_keep_alive_mode(const rdpSettings* settings, int sockfd)
1002
8.19k
{
1003
8.19k
  const BOOL keepalive = (freerdp_settings_get_bool(settings, FreeRDP_TcpKeepAlive));
1004
8.19k
  UINT32 optval = 0;
1005
8.19k
  socklen_t optlen = 0;
1006
8.19k
  optval = keepalive ? 1 : 0;
1007
8.19k
  optlen = sizeof(optval);
1008
1009
8.19k
  if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, (void*)&optval, optlen) < 0)
1010
8.19k
  {
1011
8.19k
    WLog_WARN(TAG, "setsockopt() SOL_SOCKET, SO_KEEPALIVE");
1012
8.19k
  }
1013
1014
8.19k
#ifndef _WIN32
1015
8.19k
#ifdef TCP_KEEPIDLE
1016
8.19k
  optval = keepalive ? freerdp_settings_get_uint32(settings, FreeRDP_TcpKeepAliveDelay) : 0;
1017
8.19k
  optlen = sizeof(optval);
1018
1019
8.19k
  if (setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, (void*)&optval, optlen) < 0)
1020
8.19k
  {
1021
8.19k
    WLog_WARN(TAG, "setsockopt() IPPROTO_TCP, TCP_KEEPIDLE");
1022
8.19k
  }
1023
1024
8.19k
#endif
1025
#ifndef SOL_TCP
1026
  /* "tcp" from /etc/protocols as getprotobyname(3C) */
1027
#define SOL_TCP 6
1028
#endif
1029
8.19k
#ifdef TCP_KEEPCNT
1030
8.19k
  optval = keepalive ? freerdp_settings_get_uint32(settings, FreeRDP_TcpKeepAliveRetries) : 0;
1031
8.19k
  optlen = sizeof(optval);
1032
1033
8.19k
  if (setsockopt(sockfd, SOL_TCP, TCP_KEEPCNT, (void*)&optval, optlen) < 0)
1034
8.19k
  {
1035
8.19k
    WLog_WARN(TAG, "setsockopt() SOL_TCP, TCP_KEEPCNT");
1036
8.19k
  }
1037
1038
8.19k
#endif
1039
8.19k
#ifdef TCP_KEEPINTVL
1040
8.19k
  optval = keepalive ? freerdp_settings_get_uint32(settings, FreeRDP_TcpKeepAliveInterval) : 0;
1041
8.19k
  optlen = sizeof(optval);
1042
1043
8.19k
  if (setsockopt(sockfd, SOL_TCP, TCP_KEEPINTVL, (void*)&optval, optlen) < 0)
1044
8.19k
  {
1045
8.19k
    WLog_WARN(TAG, "setsockopt() SOL_TCP, TCP_KEEPINTVL");
1046
8.19k
  }
1047
1048
8.19k
#endif
1049
8.19k
#endif
1050
#if defined(__MACOSX__) || defined(__IOS__)
1051
  optval = 1;
1052
  optlen = sizeof(optval);
1053
1054
  if (setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&optval, optlen) < 0)
1055
  {
1056
    WLog_WARN(TAG, "setsockopt() SOL_SOCKET, SO_NOSIGPIPE");
1057
  }
1058
1059
#endif
1060
8.19k
#ifdef TCP_USER_TIMEOUT
1061
8.19k
  optval = freerdp_settings_get_uint32(settings, FreeRDP_TcpAckTimeout);
1062
8.19k
  optlen = sizeof(optval);
1063
1064
8.19k
  if (setsockopt(sockfd, SOL_TCP, TCP_USER_TIMEOUT, (void*)&optval, optlen) < 0)
1065
8.19k
  {
1066
8.19k
    WLog_WARN(TAG, "setsockopt() SOL_TCP, TCP_USER_TIMEOUT");
1067
8.19k
  }
1068
1069
8.19k
#endif
1070
8.19k
  return TRUE;
1071
8.19k
}
1072
1073
int freerdp_tcp_connect(rdpContext* context, const char* hostname, int port, DWORD timeout)
1074
0
{
1075
0
  rdpTransport* transport = NULL;
1076
0
  if (!context || !context->rdp)
1077
0
    return -1;
1078
0
  transport = context->rdp->transport;
1079
0
  if (!transport)
1080
0
    return -1;
1081
0
  return transport_tcp_connect(context->rdp->transport, hostname, port, timeout);
1082
0
}
1083
1084
static struct addrinfo* reorder_addrinfo_by_preference(rdpContext* context, struct addrinfo* addr)
1085
0
{
1086
0
  WINPR_ASSERT(context);
1087
0
  WINPR_ASSERT(addr);
1088
1089
0
  const BOOL preferIPv6 =
1090
0
      freerdp_settings_get_bool(context->settings, FreeRDP_PreferIPv6OverIPv4);
1091
0
  if (!preferIPv6)
1092
0
    return addr;
1093
1094
0
  struct addrinfo* ipv6Head = NULL;
1095
0
  struct addrinfo* ipv6Tail = NULL;
1096
0
  struct addrinfo* otherHead = NULL;
1097
0
  struct addrinfo* otherTail = NULL;
1098
1099
  /* Partition the list into IPv6 and other addresses */
1100
0
  while (addr)
1101
0
  {
1102
0
    struct addrinfo* next = addr->ai_next;
1103
0
    addr->ai_next = NULL;
1104
1105
0
    if (addr->ai_family == AF_INET6)
1106
0
    {
1107
0
      if (!ipv6Head)
1108
0
        ipv6Head = addr;
1109
0
      else
1110
0
        ipv6Tail->ai_next = addr;
1111
0
      ipv6Tail = addr;
1112
0
    }
1113
0
    else
1114
0
    {
1115
0
      if (!otherHead)
1116
0
        otherHead = addr;
1117
0
      else
1118
0
        otherTail->ai_next = addr;
1119
0
      otherTail = addr;
1120
0
    }
1121
0
    addr = next;
1122
0
  }
1123
1124
  /* Concatenate the lists */
1125
0
  if (ipv6Tail)
1126
0
    ipv6Tail->ai_next = otherHead;
1127
1128
0
  return ipv6Head ? ipv6Head : otherHead;
1129
0
}
1130
1131
static int get_next_addrinfo(rdpContext* context, struct addrinfo* input, struct addrinfo** result,
1132
                             UINT32 errorCode)
1133
0
{
1134
0
  WINPR_ASSERT(context);
1135
0
  WINPR_ASSERT(result);
1136
1137
0
  struct addrinfo* addr = input;
1138
0
  if (!addr)
1139
0
    goto fail;
1140
1141
  /* We want to force IPvX, abort if not detected */
1142
0
  {
1143
0
    const UINT32 IPvX = freerdp_settings_get_uint32(context->settings, FreeRDP_ForceIPvX);
1144
0
    switch (IPvX)
1145
0
    {
1146
0
      case 4:
1147
0
      case 6:
1148
0
      {
1149
0
        const int family = (IPvX == 4) ? AF_INET : AF_INET6;
1150
0
        while (addr && (addr->ai_family != family))
1151
0
          addr = addr->ai_next;
1152
0
      }
1153
0
      break;
1154
0
      default:
1155
0
        break;
1156
0
    }
1157
0
  }
1158
1159
0
  if (!addr)
1160
0
    goto fail;
1161
1162
0
  *result = addr;
1163
0
  return 0;
1164
1165
0
fail:
1166
0
  freerdp_set_last_error_if_not(context, errorCode);
1167
0
  freeaddrinfo(input);
1168
0
  *result = NULL;
1169
0
  return -1;
1170
0
}
1171
1172
static int freerdp_vsock_connect(rdpContext* context, const char* hostname, int port)
1173
0
{
1174
#if defined(HAVE_AF_VSOCK_H)
1175
  int sockfd = socket(AF_VSOCK, SOCK_STREAM, 0);
1176
  if (sockfd < 0)
1177
  {
1178
    char buffer[256] = { 0 };
1179
    WLog_WARN(TAG, "socket(AF_VSOCK, SOCK_STREAM, 0) failed with %s [%d]",
1180
              winpr_strerror(errno, buffer, sizeof(buffer)));
1181
    freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_FAILED);
1182
    return -1;
1183
  }
1184
1185
  struct sockaddr_vm addr = { 0 };
1186
1187
  addr.svm_family = AF_VSOCK;
1188
  addr.svm_port = WINPR_ASSERTING_INT_CAST(typeof(addr.svm_port), port);
1189
1190
  errno = 0;
1191
  char* ptr = NULL;
1192
  unsigned long val = strtoul(hostname, &ptr, 10);
1193
  if (errno || (val > UINT32_MAX))
1194
  {
1195
    char ebuffer[256] = { 0 };
1196
    WLog_ERR(TAG, "could not extract port from '%s', value=%ul, error=%s", hostname, val,
1197
             winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
1198
    return -1;
1199
  }
1200
  addr.svm_cid = WINPR_ASSERTING_INT_CAST(typeof(addr.svm_cid), val);
1201
  if (addr.svm_cid == 2)
1202
  {
1203
    addr.svm_flags = VMADDR_FLAG_TO_HOST;
1204
  }
1205
  if ((connect(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_vm))) == -1)
1206
  {
1207
    WLog_ERR(TAG, "failed to connect to %s", hostname);
1208
    return -1;
1209
  }
1210
  return sockfd;
1211
#else
1212
0
  WLog_ERR(TAG, "Compiled without AF_VSOCK, '%s' not supported", hostname);
1213
0
  return -1;
1214
0
#endif
1215
0
}
1216
1217
static void log_connection_address(const char* hostname, struct addrinfo* addr)
1218
0
{
1219
0
  WINPR_ASSERT(addr);
1220
1221
0
  char* peerAddress =
1222
0
      freerdp_tcp_address_to_string((const struct sockaddr_storage*)addr->ai_addr, NULL);
1223
0
  if (peerAddress)
1224
0
    WLog_DBG(TAG, "resolved %s: try to connect to %s", hostname, peerAddress);
1225
0
  free(peerAddress);
1226
0
}
1227
1228
static int freerdp_host_connect(rdpContext* context, const char* hostname, int port, DWORD timeout)
1229
0
{
1230
0
  int sockfd = -1;
1231
0
  struct addrinfo* addr = NULL;
1232
0
  struct addrinfo* result = freerdp_tcp_resolve_host(hostname, port, 0);
1233
1234
0
  if (!result)
1235
0
  {
1236
0
    freerdp_set_last_error_if_not(context, FREERDP_ERROR_DNS_NAME_NOT_FOUND);
1237
0
    return -1;
1238
0
  }
1239
0
  freerdp_set_last_error_log(context, 0);
1240
1241
  /* By default we take the first returned entry.
1242
   * If PreferIPv6OverIPv4 = TRUE we reorder addresses by preference:
1243
   * IPv6 addresses come first, then other addresses.
1244
   */
1245
0
  result = reorder_addrinfo_by_preference(context, result);
1246
1247
0
  const int rc = get_next_addrinfo(context, result, &addr, FREERDP_ERROR_DNS_NAME_NOT_FOUND);
1248
0
  if (rc < 0)
1249
0
    goto fail;
1250
1251
0
  do
1252
0
  {
1253
0
    sockfd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
1254
0
    if (sockfd >= 0)
1255
0
    {
1256
0
      log_connection_address(hostname, addr);
1257
1258
0
      if (!freerdp_tcp_connect_timeout(context, sockfd, addr->ai_addr, addr->ai_addrlen,
1259
0
                                       timeout))
1260
0
      {
1261
0
        close(sockfd);
1262
0
        sockfd = -1;
1263
0
      }
1264
0
    }
1265
1266
0
    if (sockfd < 0)
1267
0
    {
1268
0
      const int lrc =
1269
0
          get_next_addrinfo(context, addr->ai_next, &addr, FREERDP_ERROR_CONNECT_FAILED);
1270
0
      if (lrc < 0)
1271
0
        goto fail;
1272
0
    }
1273
0
  } while (sockfd < 0);
1274
1275
0
fail:
1276
0
  freeaddrinfo(result);
1277
0
  return sockfd;
1278
0
}
1279
1280
int freerdp_tcp_default_connect(rdpContext* context, rdpSettings* settings, const char* hostname,
1281
                                int port, DWORD timeout)
1282
0
{
1283
0
  int sockfd = -1;
1284
0
  BOOL ipcSocket = FALSE;
1285
0
  BOOL useExternalDefinedSocket = FALSE;
1286
1287
0
  if (!hostname)
1288
0
  {
1289
0
    freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_FAILED);
1290
1291
0
    return -1;
1292
0
  }
1293
1294
0
  if (hostname[0] == '/')
1295
0
    ipcSocket = TRUE;
1296
1297
0
  if (hostname[0] == '|')
1298
0
    useExternalDefinedSocket = TRUE;
1299
1300
0
  const char* vsock = utils_is_vsock(hostname);
1301
0
  if (ipcSocket)
1302
0
  {
1303
0
    sockfd = freerdp_uds_connect(hostname);
1304
1305
0
    if (sockfd < 0)
1306
0
    {
1307
0
      freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_FAILED);
1308
0
      return -1;
1309
0
    }
1310
0
  }
1311
0
  else if (useExternalDefinedSocket)
1312
0
    sockfd = port;
1313
0
  else if (vsock)
1314
0
    sockfd = freerdp_vsock_connect(context, vsock, port);
1315
0
  else
1316
0
  {
1317
0
    if (!settings->GatewayEnabled)
1318
0
    {
1319
0
      if (!freerdp_tcp_is_hostname_resolvable(context, hostname) ||
1320
0
          settings->RemoteAssistanceMode)
1321
0
      {
1322
0
        if (settings->TargetNetAddressCount > 0)
1323
0
        {
1324
0
          WINPR_ASSERT(port <= UINT16_MAX);
1325
0
          sockfd = freerdp_tcp_connect_multi(
1326
0
              context, settings->TargetNetAddresses, settings->TargetNetPorts,
1327
0
              settings->TargetNetAddressCount, (UINT16)port, timeout);
1328
0
        }
1329
0
      }
1330
0
    }
1331
1332
0
    if (sockfd <= 0)
1333
0
      sockfd = freerdp_host_connect(context, hostname, port, timeout);
1334
0
  }
1335
1336
0
  if (!vsock)
1337
0
  {
1338
0
    if (!freerdp_tcp_get_ip_address(settings, sockfd))
1339
0
    {
1340
0
      if (!useExternalDefinedSocket)
1341
0
        close(sockfd);
1342
1343
0
      freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_FAILED);
1344
1345
0
      WLog_ERR(TAG, "Couldn't get socket ip address");
1346
0
      return -1;
1347
0
    }
1348
0
  }
1349
1350
0
  if (!ipcSocket && !useExternalDefinedSocket)
1351
0
  {
1352
0
    (void)freerdp_tcp_set_nodelay(WLog_Get(TAG), WLOG_ERROR, sockfd);
1353
0
  }
1354
1355
  /* receive buffer must be a least 32 K */
1356
0
  UINT32 optval = 1;
1357
0
  socklen_t optlen = sizeof(optval);
1358
0
  if (getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (void*)&optval, &optlen) == 0)
1359
0
  {
1360
0
    if (optval < (1024 * 32))
1361
0
    {
1362
0
      optval = 1024 * 32;
1363
0
      optlen = sizeof(optval);
1364
1365
0
      if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (void*)&optval, optlen) < 0)
1366
0
      {
1367
0
        close(sockfd);
1368
1369
0
        freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_FAILED);
1370
1371
0
        WLog_ERR(TAG, "unable to set receive buffer len");
1372
0
        return -1;
1373
0
      }
1374
0
    }
1375
0
  }
1376
1377
0
  if (!ipcSocket && !useExternalDefinedSocket)
1378
0
  {
1379
0
    if (!freerdp_tcp_set_keep_alive_mode(settings, sockfd))
1380
0
    {
1381
0
      close(sockfd);
1382
1383
0
      freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_FAILED);
1384
1385
0
      WLog_ERR(TAG, "Couldn't set keep alive mode.");
1386
0
      return -1;
1387
0
    }
1388
0
  }
1389
1390
0
  if (WaitForSingleObject(utils_get_abort_event(context->rdp), 0) == WAIT_OBJECT_0)
1391
0
  {
1392
0
    close(sockfd);
1393
0
    return -1;
1394
0
  }
1395
1396
0
  return sockfd;
1397
0
}
1398
1399
struct rdp_tcp_layer
1400
{
1401
  int sockfd;
1402
  HANDLE hEvent;
1403
};
1404
typedef struct rdp_tcp_layer rdpTcpLayer;
1405
1406
static int freerdp_tcp_layer_read(void* userContext, void* data, int bytes)
1407
0
{
1408
0
  if (!userContext)
1409
0
    return -1;
1410
0
  if (!data || !bytes)
1411
0
    return 0;
1412
1413
0
  rdpTcpLayer* tcpLayer = (rdpTcpLayer*)userContext;
1414
1415
0
  (void)WSAResetEvent(tcpLayer->hEvent);
1416
0
  const int status = _recv((SOCKET)tcpLayer->sockfd, data, bytes, 0);
1417
1418
0
  if (status > 0)
1419
0
    return status;
1420
1421
0
  const int error = WSAGetLastError();
1422
1423
0
  if ((error == WSAEWOULDBLOCK) || (error == WSAEINTR) || (error == WSAEINPROGRESS) ||
1424
0
      (error == WSAEALREADY))
1425
0
    errno = EAGAIN;
1426
1427
0
  return status;
1428
0
}
1429
1430
static int freerdp_tcp_layer_write(void* userContext, const void* data, int bytes)
1431
0
{
1432
0
  if (!userContext)
1433
0
    return -1;
1434
0
  if (!data || !bytes)
1435
0
    return 0;
1436
1437
0
  rdpTcpLayer* tcpLayer = (rdpTcpLayer*)userContext;
1438
1439
0
  const int status = _send((SOCKET)tcpLayer->sockfd, data, bytes, 0);
1440
0
  if (status > 0)
1441
0
    return status;
1442
1443
0
  const int error = WSAGetLastError();
1444
1445
0
  if ((error == WSAEWOULDBLOCK) || (error == WSAEINTR) || (error == WSAEINPROGRESS) ||
1446
0
      (error == WSAEALREADY))
1447
0
    errno = EAGAIN;
1448
1449
0
  return status;
1450
0
}
1451
1452
static BOOL freerdp_tcp_layer_close(void* userContext)
1453
0
{
1454
0
  if (!userContext)
1455
0
    return FALSE;
1456
1457
0
  rdpTcpLayer* tcpLayer = (rdpTcpLayer*)userContext;
1458
1459
0
  if (tcpLayer->sockfd >= 0)
1460
0
    closesocket((SOCKET)tcpLayer->sockfd);
1461
0
  if (tcpLayer->hEvent)
1462
0
    (void)CloseHandle(tcpLayer->hEvent);
1463
1464
0
  return TRUE;
1465
0
}
1466
1467
static BOOL freerdp_tcp_layer_wait(void* userContext, BOOL waitWrite, DWORD timeout)
1468
0
{
1469
0
  if (!userContext)
1470
0
    return FALSE;
1471
1472
0
  rdpTcpLayer* tcpLayer = (rdpTcpLayer*)userContext;
1473
1474
0
  int status = -1;
1475
0
  int sockfd = tcpLayer->sockfd;
1476
0
#ifdef WINPR_HAVE_POLL_H
1477
0
  struct pollfd pollset = { 0 };
1478
0
  pollset.fd = sockfd;
1479
0
  pollset.events = waitWrite ? POLLOUT : POLLIN;
1480
1481
0
  do
1482
0
  {
1483
0
    status = poll(&pollset, 1, (int)timeout);
1484
0
  } while ((status < 0) && (errno == EINTR));
1485
1486
#else
1487
  fd_set rset = { 0 };
1488
  struct timeval tv = { 0 };
1489
  FD_ZERO(&rset);
1490
  FD_SET(sockfd, &rset);
1491
1492
  if (timeout)
1493
  {
1494
    tv.tv_sec = timeout / 1000;
1495
    tv.tv_usec = (timeout % 1000) * 1000;
1496
  }
1497
1498
  do
1499
  {
1500
    if (waitWrite)
1501
      status = select(sockfd + 1, NULL, &rset, NULL, timeout ? &tv : NULL);
1502
    else
1503
      status = select(sockfd + 1, &rset, NULL, NULL, timeout ? &tv : NULL);
1504
  } while ((status < 0) && (errno == EINTR));
1505
1506
#endif
1507
1508
0
  return status != 0;
1509
0
}
1510
1511
static HANDLE freerdp_tcp_layer_get_event(void* userContext)
1512
0
{
1513
0
  if (!userContext)
1514
0
    return NULL;
1515
1516
0
  rdpTcpLayer* tcpLayer = (rdpTcpLayer*)userContext;
1517
1518
0
  return tcpLayer->hEvent;
1519
0
}
1520
1521
rdpTransportLayer* freerdp_tcp_connect_layer(rdpContext* context, const char* hostname, int port,
1522
                                             DWORD timeout)
1523
0
{
1524
0
  WINPR_ASSERT(context);
1525
1526
0
  const rdpSettings* settings = context->settings;
1527
0
  WINPR_ASSERT(settings);
1528
1529
0
  rdpTransportLayer* layer = NULL;
1530
0
  rdpTcpLayer* tcpLayer = NULL;
1531
1532
0
  int sockfd = freerdp_tcp_connect(context, hostname, port, timeout);
1533
0
  if (sockfd < 0)
1534
0
    goto fail;
1535
0
  if (!freerdp_tcp_set_keep_alive_mode(settings, sockfd))
1536
0
    goto fail;
1537
1538
0
  layer = transport_layer_new(freerdp_get_transport(context), sizeof(rdpTcpLayer));
1539
0
  if (!layer)
1540
0
    goto fail;
1541
1542
0
  layer->Read = freerdp_tcp_layer_read;
1543
0
  layer->Write = freerdp_tcp_layer_write;
1544
0
  layer->Close = freerdp_tcp_layer_close;
1545
0
  layer->Wait = freerdp_tcp_layer_wait;
1546
0
  layer->GetEvent = freerdp_tcp_layer_get_event;
1547
1548
0
  tcpLayer = (rdpTcpLayer*)layer->userContext;
1549
0
  WINPR_ASSERT(tcpLayer);
1550
1551
0
  tcpLayer->sockfd = -1;
1552
0
  tcpLayer->hEvent = WSACreateEvent();
1553
0
  if (!tcpLayer->hEvent)
1554
0
    goto fail;
1555
1556
  /* WSAEventSelect automatically sets the socket in non-blocking mode */
1557
0
  if (WSAEventSelect((SOCKET)sockfd, tcpLayer->hEvent, FD_READ | FD_ACCEPT | FD_CLOSE))
1558
0
  {
1559
0
    WLog_ERR(TAG, "WSAEventSelect returned 0x%08X", WSAGetLastError());
1560
0
    goto fail;
1561
0
  }
1562
1563
0
  tcpLayer->sockfd = sockfd;
1564
1565
0
  return layer;
1566
1567
0
fail:
1568
0
  if (sockfd >= 0)
1569
0
    closesocket((SOCKET)sockfd);
1570
0
  transport_layer_free(layer);
1571
0
  return NULL;
1572
0
}
1573
1574
BOOL freerdp_tcp_set_nodelay(wLog* log, DWORD level, int sockfd)
1575
0
{
1576
0
  WINPR_ASSERT(log);
1577
1578
0
  int type = -1;
1579
0
  socklen_t typelen = sizeof(type);
1580
0
  char* ptype = (char*)&type;
1581
0
  const int rc = getsockopt(sockfd, SOL_SOCKET, SO_TYPE, ptype, &typelen);
1582
0
  if (rc < 0)
1583
0
  {
1584
0
    char buffer[128] = { 0 };
1585
0
    WLog_Print(log, level, "can't get SOL_SOCKET|SO_TYPE (%s)",
1586
0
               winpr_strerror(errno, buffer, sizeof(buffer)));
1587
0
    return FALSE;
1588
0
  }
1589
0
  else if (type == SOCK_STREAM)
1590
0
  {
1591
0
    int option_value = -1;
1592
0
    const socklen_t option_len = sizeof(option_value);
1593
0
    const int sr =
1594
0
        setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (void*)&option_value, option_len);
1595
0
    if (sr < 0)
1596
0
    {
1597
      /* local unix sockets don't have the TCP_NODELAY implemented, so don't make this
1598
       * error fatal */
1599
0
      char buffer[128] = { 0 };
1600
0
      WLog_Print(log, level, "can't set TCP_NODELAY (%s)",
1601
0
                 winpr_strerror(errno, buffer, sizeof(buffer)));
1602
0
      return FALSE;
1603
0
    }
1604
0
  }
1605
0
  else
1606
0
  {
1607
0
    WLog_Print(log, level, "Socket SOL_SOCKET|SO_TYPE %d unsupported", type);
1608
0
    return FALSE;
1609
0
  }
1610
0
  return TRUE;
1611
0
}