Coverage Report

Created: 2026-01-10 06:35

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
110
{
108
110
  int error = 0;
109
110
  int status = 0;
110
110
  WINPR_BIO_SIMPLE_SOCKET* ptr = (WINPR_BIO_SIMPLE_SOCKET*)BIO_get_data(bio);
111
112
110
  if (!buf)
113
0
    return 0;
114
115
110
  BIO_clear_flags(bio, BIO_FLAGS_WRITE);
116
110
  status = _send(ptr->socket, buf, size, 0);
117
118
110
  if (status <= 0)
119
110
  {
120
110
    error = WSAGetLastError();
121
122
110
    if ((error == WSAEWOULDBLOCK) || (error == WSAEINTR) || (error == WSAEINPROGRESS) ||
123
110
        (error == WSAEALREADY))
124
0
    {
125
0
      BIO_set_flags(bio, (BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY));
126
0
    }
127
110
    else
128
110
    {
129
110
      BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
130
110
    }
131
110
  }
132
133
110
  return status;
134
110
}
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
25.0k
{
188
25.0k
  int status = -1;
189
25.0k
  WINPR_BIO_SIMPLE_SOCKET* ptr = (WINPR_BIO_SIMPLE_SOCKET*)BIO_get_data(bio);
190
191
25.0k
  switch (cmd)
192
25.0k
  {
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.33k
    case BIO_C_SET_NONBLOCK:
210
8.33k
    {
211
8.33k
#ifndef _WIN32
212
8.33k
      int flags = 0;
213
8.33k
      flags = fcntl((int)ptr->socket, F_GETFL);
214
215
8.33k
      if (flags == -1)
216
0
        return 0;
217
218
8.33k
      if (arg1)
219
8.33k
        (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.33k
      return 1;
227
8.33k
    }
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.33k
    case BIO_C_SET_FD:
307
8.33k
      if (arg2)
308
8.33k
      {
309
8.33k
        transport_bio_simple_uninit(bio);
310
8.33k
        transport_bio_simple_init(bio, (SOCKET) * ((int*)arg2), (int)arg1);
311
8.33k
        status = 1;
312
8.33k
      }
313
314
8.33k
      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.33k
    default:
342
8.33k
      status = 0;
343
8.33k
      break;
344
25.0k
  }
345
346
16.6k
  return status;
347
25.0k
}
348
349
static int transport_bio_simple_init(BIO* bio, SOCKET socket, int shutdown)
350
8.33k
{
351
8.33k
  WINPR_BIO_SIMPLE_SOCKET* ptr = (WINPR_BIO_SIMPLE_SOCKET*)BIO_get_data(bio);
352
8.33k
  ptr->socket = socket;
353
8.33k
  BIO_set_shutdown(bio, shutdown);
354
8.33k
  BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
355
8.33k
  BIO_set_init(bio, 1);
356
8.33k
  ptr->hEvent = WSACreateEvent();
357
358
8.33k
  if (!ptr->hEvent)
359
0
    return 0;
360
361
  /* WSAEventSelect automatically sets the socket in non-blocking mode */
362
8.33k
  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.33k
  return 1;
369
8.33k
}
370
371
static int transport_bio_simple_uninit(BIO* bio)
372
16.6k
{
373
16.6k
  WINPR_BIO_SIMPLE_SOCKET* ptr = (WINPR_BIO_SIMPLE_SOCKET*)BIO_get_data(bio);
374
375
16.6k
  if (BIO_get_shutdown(bio))
376
16.6k
  {
377
16.6k
    if (BIO_get_init(bio) && ptr)
378
8.33k
    {
379
8.33k
      _shutdown(ptr->socket, SD_BOTH);
380
8.33k
      closesocket(ptr->socket);
381
8.33k
      ptr->socket = 0;
382
8.33k
    }
383
16.6k
  }
384
385
16.6k
  if (ptr && ptr->hEvent)
386
8.33k
  {
387
8.33k
    (void)CloseHandle(ptr->hEvent);
388
8.33k
    ptr->hEvent = NULL;
389
8.33k
  }
390
391
16.6k
  BIO_set_init(bio, 0);
392
16.6k
  BIO_set_flags(bio, 0);
393
16.6k
  return 1;
394
16.6k
}
395
396
static int transport_bio_simple_new(BIO* bio)
397
8.33k
{
398
8.33k
  WINPR_BIO_SIMPLE_SOCKET* ptr = NULL;
399
8.33k
  BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
400
8.33k
  ptr = (WINPR_BIO_SIMPLE_SOCKET*)calloc(1, sizeof(WINPR_BIO_SIMPLE_SOCKET));
401
402
8.33k
  if (!ptr)
403
0
    return 0;
404
405
8.33k
  BIO_set_data(bio, ptr);
406
8.33k
  return 1;
407
8.33k
}
408
409
static int transport_bio_simple_free(BIO* bio)
410
8.33k
{
411
8.33k
  WINPR_BIO_SIMPLE_SOCKET* ptr = NULL;
412
413
8.33k
  if (!bio)
414
0
    return 0;
415
416
8.33k
  transport_bio_simple_uninit(bio);
417
8.33k
  ptr = (WINPR_BIO_SIMPLE_SOCKET*)BIO_get_data(bio);
418
419
8.33k
  if (ptr)
420
8.33k
  {
421
8.33k
    BIO_set_data(bio, NULL);
422
8.33k
    free(ptr);
423
8.33k
  }
424
425
8.33k
  return 1;
426
8.33k
}
427
428
BIO_METHOD* BIO_s_simple_socket(void)
429
8.33k
{
430
8.33k
  static BIO_METHOD* bio_methods = NULL;
431
432
8.33k
  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.33k
  return bio_methods;
447
8.33k
}
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
110
{
461
110
  int ret = num;
462
110
  int nchunks = 0;
463
110
  size_t committedBytes = 0;
464
110
  DataChunk chunks[2] = { 0 };
465
110
  WINPR_BIO_BUFFERED_SOCKET* ptr = (WINPR_BIO_BUFFERED_SOCKET*)BIO_get_data(bio);
466
110
  BIO* next_bio = NULL;
467
468
110
  WINPR_ASSERT(bio);
469
110
  WINPR_ASSERT(ptr);
470
110
  if (num < 0)
471
0
    return num;
472
473
110
  ptr->writeBlocked = FALSE;
474
110
  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
110
  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
110
  nchunks = ringbuffer_peek(&ptr->xmitBuffer, chunks, ringbuffer_used(&ptr->xmitBuffer));
486
110
  next_bio = BIO_next(bio);
487
488
110
  for (int i = 0; i < nchunks; i++)
489
110
  {
490
110
    while (chunks[i].size)
491
110
    {
492
110
      ERR_clear_error();
493
494
110
      const size_t wr = MIN(INT32_MAX, chunks[i].size);
495
110
      const int status = BIO_write(next_bio, chunks[i].data, (int)wr);
496
497
110
      if (status <= 0)
498
110
      {
499
110
        if (!BIO_should_retry(next_bio))
500
110
        {
501
110
          BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
502
110
          ret = -1; /* fatal error */
503
110
          goto out;
504
110
        }
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
110
    }
520
110
  }
521
522
110
out:
523
110
  ringbuffer_commit_read_bytes(&ptr->xmitBuffer, committedBytes);
524
110
  return ret;
525
110
}
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.6k
{
573
16.6k
  long status = -1;
574
16.6k
  WINPR_BIO_BUFFERED_SOCKET* ptr = (WINPR_BIO_BUFFERED_SOCKET*)BIO_get_data(bio);
575
576
16.6k
  switch (cmd)
577
16.6k
  {
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.6k
    default:
603
16.6k
      status = BIO_ctrl(BIO_next(bio), cmd, arg1, arg2);
604
16.6k
      break;
605
16.6k
  }
606
607
16.6k
  return status;
608
16.6k
}
609
610
static int transport_bio_buffered_new(BIO* bio)
611
8.33k
{
612
8.33k
  WINPR_BIO_BUFFERED_SOCKET* ptr = NULL;
613
8.33k
  BIO_set_init(bio, 1);
614
8.33k
  BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
615
8.33k
  ptr = (WINPR_BIO_BUFFERED_SOCKET*)calloc(1, sizeof(WINPR_BIO_BUFFERED_SOCKET));
616
617
8.33k
  if (!ptr)
618
0
    return -1;
619
620
8.33k
  BIO_set_data(bio, (void*)ptr);
621
622
8.33k
  if (!ringbuffer_init(&ptr->xmitBuffer, 0x10000))
623
0
    return -1;
624
625
8.33k
  return 1;
626
8.33k
}
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.33k
{
633
8.33k
  WINPR_BIO_BUFFERED_SOCKET* ptr = (WINPR_BIO_BUFFERED_SOCKET*)BIO_get_data(bio);
634
635
8.33k
  if (!ptr)
636
0
    return 0;
637
638
8.33k
  ringbuffer_destroy(&ptr->xmitBuffer);
639
8.33k
  free(ptr);
640
8.33k
  return 1;
641
8.33k
}
642
643
BIO_METHOD* BIO_s_buffered_socket(void)
644
8.33k
{
645
8.33k
  static BIO_METHOD* bio_methods = NULL;
646
647
8.33k
  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.33k
  return bio_methods;
662
8.33k
}
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.33k
{
1003
8.33k
  const BOOL keepalive = (freerdp_settings_get_bool(settings, FreeRDP_TcpKeepAlive));
1004
8.33k
  UINT32 optval = 0;
1005
8.33k
  socklen_t optlen = 0;
1006
8.33k
  optval = keepalive ? 1 : 0;
1007
8.33k
  optlen = sizeof(optval);
1008
1009
8.33k
  if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, (void*)&optval, optlen) < 0)
1010
8.33k
  {
1011
8.33k
    WLog_WARN(TAG, "setsockopt() SOL_SOCKET, SO_KEEPALIVE");
1012
8.33k
  }
1013
1014
8.33k
#ifndef _WIN32
1015
8.33k
#ifdef TCP_KEEPIDLE
1016
8.33k
  optval = keepalive ? freerdp_settings_get_uint32(settings, FreeRDP_TcpKeepAliveDelay) : 0;
1017
8.33k
  optlen = sizeof(optval);
1018
1019
8.33k
  if (setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, (void*)&optval, optlen) < 0)
1020
8.33k
  {
1021
8.33k
    WLog_WARN(TAG, "setsockopt() IPPROTO_TCP, TCP_KEEPIDLE");
1022
8.33k
  }
1023
1024
8.33k
#endif
1025
#ifndef SOL_TCP
1026
  /* "tcp" from /etc/protocols as getprotobyname(3C) */
1027
#define SOL_TCP 6
1028
#endif
1029
8.33k
#ifdef TCP_KEEPCNT
1030
8.33k
  optval = keepalive ? freerdp_settings_get_uint32(settings, FreeRDP_TcpKeepAliveRetries) : 0;
1031
8.33k
  optlen = sizeof(optval);
1032
1033
8.33k
  if (setsockopt(sockfd, SOL_TCP, TCP_KEEPCNT, (void*)&optval, optlen) < 0)
1034
8.33k
  {
1035
8.33k
    WLog_WARN(TAG, "setsockopt() SOL_TCP, TCP_KEEPCNT");
1036
8.33k
  }
1037
1038
8.33k
#endif
1039
8.33k
#ifdef TCP_KEEPINTVL
1040
8.33k
  optval = keepalive ? freerdp_settings_get_uint32(settings, FreeRDP_TcpKeepAliveInterval) : 0;
1041
8.33k
  optlen = sizeof(optval);
1042
1043
8.33k
  if (setsockopt(sockfd, SOL_TCP, TCP_KEEPINTVL, (void*)&optval, optlen) < 0)
1044
8.33k
  {
1045
8.33k
    WLog_WARN(TAG, "setsockopt() SOL_TCP, TCP_KEEPINTVL");
1046
8.33k
  }
1047
1048
8.33k
#endif
1049
8.33k
#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.33k
#ifdef TCP_USER_TIMEOUT
1061
8.33k
  optval = freerdp_settings_get_uint32(settings, FreeRDP_TcpAckTimeout);
1062
8.33k
  optlen = sizeof(optval);
1063
1064
8.33k
  if (setsockopt(sockfd, SOL_TCP, TCP_USER_TIMEOUT, (void*)&optval, optlen) < 0)
1065
8.33k
  {
1066
8.33k
    WLog_WARN(TAG, "setsockopt() SOL_TCP, TCP_USER_TIMEOUT");
1067
8.33k
  }
1068
1069
8.33k
#endif
1070
8.33k
  return TRUE;
1071
8.33k
}
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
  *result = NULL;
1168
0
  return -1;
1169
0
}
1170
1171
static int freerdp_vsock_connect(rdpContext* context, const char* hostname, int port)
1172
0
{
1173
#if defined(HAVE_AF_VSOCK_H)
1174
  int sockfd = socket(AF_VSOCK, SOCK_STREAM, 0);
1175
  if (sockfd < 0)
1176
  {
1177
    char buffer[256] = { 0 };
1178
    WLog_WARN(TAG, "socket(AF_VSOCK, SOCK_STREAM, 0) failed with %s [%d]",
1179
              winpr_strerror(errno, buffer, sizeof(buffer)));
1180
    freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_FAILED);
1181
    return -1;
1182
  }
1183
1184
  struct sockaddr_vm addr = { 0 };
1185
1186
  addr.svm_family = AF_VSOCK;
1187
  addr.svm_port = WINPR_ASSERTING_INT_CAST(typeof(addr.svm_port), port);
1188
1189
  errno = 0;
1190
  char* ptr = NULL;
1191
  unsigned long val = strtoul(hostname, &ptr, 10);
1192
  if (errno || (val > UINT32_MAX))
1193
  {
1194
    char ebuffer[256] = { 0 };
1195
    WLog_ERR(TAG, "could not extract port from '%s', value=%ul, error=%s", hostname, val,
1196
             winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
1197
    close(sockfd);
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
    close(sockfd);
1209
    return -1;
1210
  }
1211
  return sockfd;
1212
#else
1213
0
  WLog_ERR(TAG, "Compiled without AF_VSOCK, '%s' not supported", hostname);
1214
0
  return -1;
1215
0
#endif
1216
0
}
1217
1218
static void log_connection_address(const char* hostname, struct addrinfo* addr)
1219
0
{
1220
0
  WINPR_ASSERT(addr);
1221
1222
0
  char* peerAddress =
1223
0
      freerdp_tcp_address_to_string((const struct sockaddr_storage*)addr->ai_addr, NULL);
1224
0
  if (peerAddress)
1225
0
    WLog_DBG(TAG, "resolved %s: try to connect to %s", hostname, peerAddress);
1226
0
  free(peerAddress);
1227
0
}
1228
1229
static int freerdp_host_connect(rdpContext* context, const char* hostname, int port, DWORD timeout)
1230
0
{
1231
0
  int sockfd = -1;
1232
0
  struct addrinfo* addr = NULL;
1233
0
  struct addrinfo* result = freerdp_tcp_resolve_host(hostname, port, 0);
1234
1235
0
  if (!result)
1236
0
  {
1237
0
    freerdp_set_last_error_if_not(context, FREERDP_ERROR_DNS_NAME_NOT_FOUND);
1238
0
    return -1;
1239
0
  }
1240
0
  freerdp_set_last_error_log(context, 0);
1241
1242
  /* By default we take the first returned entry.
1243
   * If PreferIPv6OverIPv4 = TRUE we reorder addresses by preference:
1244
   * IPv6 addresses come first, then other addresses.
1245
   */
1246
0
  result = reorder_addrinfo_by_preference(context, result);
1247
1248
0
  const int rc = get_next_addrinfo(context, result, &addr, FREERDP_ERROR_DNS_NAME_NOT_FOUND);
1249
0
  if (rc < 0)
1250
0
    goto fail;
1251
1252
0
  do
1253
0
  {
1254
0
    sockfd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
1255
0
    if (sockfd >= 0)
1256
0
    {
1257
0
      log_connection_address(hostname, addr);
1258
1259
0
      if (!freerdp_tcp_connect_timeout(context, sockfd, addr->ai_addr, addr->ai_addrlen,
1260
0
                                       timeout))
1261
0
      {
1262
0
        close(sockfd);
1263
0
        sockfd = -1;
1264
0
      }
1265
0
    }
1266
1267
0
    if (sockfd < 0)
1268
0
    {
1269
0
      const int lrc =
1270
0
          get_next_addrinfo(context, addr->ai_next, &addr, FREERDP_ERROR_CONNECT_FAILED);
1271
0
      if (lrc < 0)
1272
0
        goto fail;
1273
0
    }
1274
0
  } while (sockfd < 0);
1275
1276
0
fail:
1277
0
  freeaddrinfo(result);
1278
0
  return sockfd;
1279
0
}
1280
1281
int freerdp_tcp_default_connect(rdpContext* context, rdpSettings* settings, const char* hostname,
1282
                                int port, DWORD timeout)
1283
0
{
1284
0
  int sockfd = -1;
1285
0
  BOOL ipcSocket = FALSE;
1286
0
  BOOL useExternalDefinedSocket = FALSE;
1287
1288
0
  if (!hostname)
1289
0
  {
1290
0
    freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_FAILED);
1291
1292
0
    return -1;
1293
0
  }
1294
1295
0
  if (hostname[0] == '/')
1296
0
    ipcSocket = TRUE;
1297
1298
0
  if (hostname[0] == '|')
1299
0
    useExternalDefinedSocket = TRUE;
1300
1301
0
  const char* vsock = utils_is_vsock(hostname);
1302
0
  if (ipcSocket)
1303
0
  {
1304
0
    sockfd = freerdp_uds_connect(hostname);
1305
1306
0
    if (sockfd < 0)
1307
0
    {
1308
0
      freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_FAILED);
1309
0
      return -1;
1310
0
    }
1311
0
  }
1312
0
  else if (useExternalDefinedSocket)
1313
0
    sockfd = port;
1314
0
  else if (vsock)
1315
0
    sockfd = freerdp_vsock_connect(context, vsock, port);
1316
0
  else
1317
0
  {
1318
0
    if (!settings->GatewayEnabled)
1319
0
    {
1320
0
      if (!freerdp_tcp_is_hostname_resolvable(context, hostname) ||
1321
0
          settings->RemoteAssistanceMode)
1322
0
      {
1323
0
        if (settings->TargetNetAddressCount > 0)
1324
0
        {
1325
0
          WINPR_ASSERT(port <= UINT16_MAX);
1326
0
          sockfd = freerdp_tcp_connect_multi(
1327
0
              context, settings->TargetNetAddresses, settings->TargetNetPorts,
1328
0
              settings->TargetNetAddressCount, (UINT16)port, timeout);
1329
0
        }
1330
0
      }
1331
0
    }
1332
1333
0
    if (sockfd <= 0)
1334
0
      sockfd = freerdp_host_connect(context, hostname, port, timeout);
1335
0
  }
1336
1337
0
  if (!vsock)
1338
0
  {
1339
0
    if (!freerdp_tcp_get_ip_address(settings, sockfd))
1340
0
    {
1341
0
      if (!useExternalDefinedSocket)
1342
0
        close(sockfd);
1343
1344
0
      freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_FAILED);
1345
1346
0
      WLog_ERR(TAG, "Couldn't get socket ip address");
1347
0
      return -1;
1348
0
    }
1349
0
  }
1350
1351
0
  if (!ipcSocket && !useExternalDefinedSocket)
1352
0
  {
1353
0
    (void)freerdp_tcp_set_nodelay(WLog_Get(TAG), WLOG_ERROR, sockfd);
1354
0
  }
1355
1356
  /* receive buffer must be a least 32 K */
1357
0
  UINT32 optval = 1;
1358
0
  socklen_t optlen = sizeof(optval);
1359
0
  if (getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (void*)&optval, &optlen) == 0)
1360
0
  {
1361
0
    if (optval < (1024 * 32))
1362
0
    {
1363
0
      optval = 1024 * 32;
1364
0
      optlen = sizeof(optval);
1365
1366
0
      if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (void*)&optval, optlen) < 0)
1367
0
      {
1368
0
        close(sockfd);
1369
1370
0
        freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_FAILED);
1371
1372
0
        WLog_ERR(TAG, "unable to set receive buffer len");
1373
0
        return -1;
1374
0
      }
1375
0
    }
1376
0
  }
1377
1378
0
  if (!ipcSocket && !useExternalDefinedSocket)
1379
0
  {
1380
0
    if (!freerdp_tcp_set_keep_alive_mode(settings, sockfd))
1381
0
    {
1382
0
      close(sockfd);
1383
1384
0
      freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_FAILED);
1385
1386
0
      WLog_ERR(TAG, "Couldn't set keep alive mode.");
1387
0
      return -1;
1388
0
    }
1389
0
  }
1390
1391
0
  if (WaitForSingleObject(utils_get_abort_event(context->rdp), 0) == WAIT_OBJECT_0)
1392
0
  {
1393
0
    close(sockfd);
1394
0
    return -1;
1395
0
  }
1396
1397
0
  return sockfd;
1398
0
}
1399
1400
struct rdp_tcp_layer
1401
{
1402
  int sockfd;
1403
  HANDLE hEvent;
1404
};
1405
typedef struct rdp_tcp_layer rdpTcpLayer;
1406
1407
static int freerdp_tcp_layer_read(void* userContext, void* data, int bytes)
1408
0
{
1409
0
  if (!userContext)
1410
0
    return -1;
1411
0
  if (!data || !bytes)
1412
0
    return 0;
1413
1414
0
  rdpTcpLayer* tcpLayer = (rdpTcpLayer*)userContext;
1415
1416
0
  (void)WSAResetEvent(tcpLayer->hEvent);
1417
0
  const int status = _recv((SOCKET)tcpLayer->sockfd, data, bytes, 0);
1418
1419
0
  if (status > 0)
1420
0
    return status;
1421
1422
0
  const int error = WSAGetLastError();
1423
1424
0
  if ((error == WSAEWOULDBLOCK) || (error == WSAEINTR) || (error == WSAEINPROGRESS) ||
1425
0
      (error == WSAEALREADY))
1426
0
    errno = EAGAIN;
1427
1428
0
  return status;
1429
0
}
1430
1431
static int freerdp_tcp_layer_write(void* userContext, const void* data, int bytes)
1432
0
{
1433
0
  if (!userContext)
1434
0
    return -1;
1435
0
  if (!data || !bytes)
1436
0
    return 0;
1437
1438
0
  rdpTcpLayer* tcpLayer = (rdpTcpLayer*)userContext;
1439
1440
0
  const int status = _send((SOCKET)tcpLayer->sockfd, data, bytes, 0);
1441
0
  if (status > 0)
1442
0
    return status;
1443
1444
0
  const int error = WSAGetLastError();
1445
1446
0
  if ((error == WSAEWOULDBLOCK) || (error == WSAEINTR) || (error == WSAEINPROGRESS) ||
1447
0
      (error == WSAEALREADY))
1448
0
    errno = EAGAIN;
1449
1450
0
  return status;
1451
0
}
1452
1453
static BOOL freerdp_tcp_layer_close(void* userContext)
1454
0
{
1455
0
  if (!userContext)
1456
0
    return FALSE;
1457
1458
0
  rdpTcpLayer* tcpLayer = (rdpTcpLayer*)userContext;
1459
1460
0
  if (tcpLayer->sockfd >= 0)
1461
0
    closesocket((SOCKET)tcpLayer->sockfd);
1462
0
  if (tcpLayer->hEvent)
1463
0
    (void)CloseHandle(tcpLayer->hEvent);
1464
1465
0
  return TRUE;
1466
0
}
1467
1468
static BOOL freerdp_tcp_layer_wait(void* userContext, BOOL waitWrite, DWORD timeout)
1469
0
{
1470
0
  if (!userContext)
1471
0
    return FALSE;
1472
1473
0
  rdpTcpLayer* tcpLayer = (rdpTcpLayer*)userContext;
1474
1475
0
  int status = -1;
1476
0
  int sockfd = tcpLayer->sockfd;
1477
0
#ifdef WINPR_HAVE_POLL_H
1478
0
  struct pollfd pollset = { 0 };
1479
0
  pollset.fd = sockfd;
1480
0
  pollset.events = waitWrite ? POLLOUT : POLLIN;
1481
1482
0
  do
1483
0
  {
1484
0
    status = poll(&pollset, 1, (int)timeout);
1485
0
  } while ((status < 0) && (errno == EINTR));
1486
1487
#else
1488
  fd_set rset = { 0 };
1489
  struct timeval tv = { 0 };
1490
  FD_ZERO(&rset);
1491
  FD_SET(sockfd, &rset);
1492
1493
  if (timeout)
1494
  {
1495
    tv.tv_sec = timeout / 1000;
1496
    tv.tv_usec = (timeout % 1000) * 1000;
1497
  }
1498
1499
  do
1500
  {
1501
    if (waitWrite)
1502
      status = select(sockfd + 1, NULL, &rset, NULL, timeout ? &tv : NULL);
1503
    else
1504
      status = select(sockfd + 1, &rset, NULL, NULL, timeout ? &tv : NULL);
1505
  } while ((status < 0) && (errno == EINTR));
1506
1507
#endif
1508
1509
0
  return status != 0;
1510
0
}
1511
1512
static HANDLE freerdp_tcp_layer_get_event(void* userContext)
1513
0
{
1514
0
  if (!userContext)
1515
0
    return NULL;
1516
1517
0
  rdpTcpLayer* tcpLayer = (rdpTcpLayer*)userContext;
1518
1519
0
  return tcpLayer->hEvent;
1520
0
}
1521
1522
rdpTransportLayer* freerdp_tcp_connect_layer(rdpContext* context, const char* hostname, int port,
1523
                                             DWORD timeout)
1524
0
{
1525
0
  WINPR_ASSERT(context);
1526
1527
0
  const rdpSettings* settings = context->settings;
1528
0
  WINPR_ASSERT(settings);
1529
1530
0
  rdpTransportLayer* layer = NULL;
1531
0
  rdpTcpLayer* tcpLayer = NULL;
1532
1533
0
  int sockfd = freerdp_tcp_connect(context, hostname, port, timeout);
1534
0
  if (sockfd < 0)
1535
0
    goto fail;
1536
0
  if (!freerdp_tcp_set_keep_alive_mode(settings, sockfd))
1537
0
    goto fail;
1538
1539
0
  layer = transport_layer_new(freerdp_get_transport(context), sizeof(rdpTcpLayer));
1540
0
  if (!layer)
1541
0
    goto fail;
1542
1543
0
  layer->Read = freerdp_tcp_layer_read;
1544
0
  layer->Write = freerdp_tcp_layer_write;
1545
0
  layer->Close = freerdp_tcp_layer_close;
1546
0
  layer->Wait = freerdp_tcp_layer_wait;
1547
0
  layer->GetEvent = freerdp_tcp_layer_get_event;
1548
1549
0
  tcpLayer = (rdpTcpLayer*)layer->userContext;
1550
0
  WINPR_ASSERT(tcpLayer);
1551
1552
0
  tcpLayer->sockfd = -1;
1553
0
  tcpLayer->hEvent = WSACreateEvent();
1554
0
  if (!tcpLayer->hEvent)
1555
0
    goto fail;
1556
1557
  /* WSAEventSelect automatically sets the socket in non-blocking mode */
1558
0
  if (WSAEventSelect((SOCKET)sockfd, tcpLayer->hEvent, FD_READ | FD_ACCEPT | FD_CLOSE))
1559
0
  {
1560
0
    WLog_ERR(TAG, "WSAEventSelect returned 0x%08X", WSAGetLastError());
1561
0
    goto fail;
1562
0
  }
1563
1564
0
  tcpLayer->sockfd = sockfd;
1565
1566
0
  return layer;
1567
1568
0
fail:
1569
0
  if (sockfd >= 0)
1570
0
    closesocket((SOCKET)sockfd);
1571
0
  transport_layer_free(layer);
1572
0
  return NULL;
1573
0
}
1574
1575
BOOL freerdp_tcp_set_nodelay(wLog* log, DWORD level, int sockfd)
1576
0
{
1577
0
  WINPR_ASSERT(log);
1578
1579
0
  int type = -1;
1580
0
  socklen_t typelen = sizeof(type);
1581
0
  char* ptype = (char*)&type;
1582
0
  const int rc = getsockopt(sockfd, SOL_SOCKET, SO_TYPE, ptype, &typelen);
1583
0
  if (rc < 0)
1584
0
  {
1585
0
    char buffer[128] = { 0 };
1586
0
    WLog_Print(log, level, "can't get SOL_SOCKET|SO_TYPE (%s)",
1587
0
               winpr_strerror(errno, buffer, sizeof(buffer)));
1588
0
    return FALSE;
1589
0
  }
1590
0
  else if (type == SOCK_STREAM)
1591
0
  {
1592
0
    int option_value = -1;
1593
0
    const socklen_t option_len = sizeof(option_value);
1594
0
    const int sr =
1595
0
        setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (void*)&option_value, option_len);
1596
0
    if (sr < 0)
1597
0
    {
1598
      /* local unix sockets don't have the TCP_NODELAY implemented, so don't make this
1599
       * error fatal */
1600
0
      char buffer[128] = { 0 };
1601
0
      WLog_Print(log, level, "can't set TCP_NODELAY (%s)",
1602
0
                 winpr_strerror(errno, buffer, sizeof(buffer)));
1603
0
      return FALSE;
1604
0
    }
1605
0
  }
1606
0
  else
1607
0
  {
1608
0
    WLog_Print(log, level, "Socket SOL_SOCKET|SO_TYPE %d unsupported", type);
1609
0
    return FALSE;
1610
0
  }
1611
0
  return TRUE;
1612
0
}