-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathtcpmux.c
1407 lines (1239 loc) · 46 KB
/
tcpmux.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: GPL-3.0-only
/*
* Copyright (c) 2023 Dengfeng Liu <[email protected]>
*/
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include "client.h"
#include "common.h"
#include "config.h"
#include "control.h"
#include "debug.h"
#include "proxy.h"
#include "tcpmux.h"
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
/**
* @brief Protocol and state management variables
*/
static uint8_t proto_version = 0; /* Protocol version number */
static uint8_t remote_go_away = 0; /* Flag indicating remote end wants to close */
static uint8_t local_go_away = 0; /* Flag indicating local end wants to close */
/**
* @brief Session management variables
*/
static uint32_t g_session_id = 1; /* Global session ID counter (starts at 1) */
/**
* @brief Stream management variables
*/
static struct tmux_stream *cur_stream = NULL; /* Currently active stream */
static struct tmux_stream *all_stream = NULL; /* Hash table of all streams */
/**
* @brief Adds a stream to the hash table of all streams.
*
* This function adds the given stream to the global hash table `all_stream`
* using the stream's `id` as the key.
*
* @param stream A pointer to the `tmux_stream` structure to be added.
*/
void add_stream(struct tmux_stream *stream) {
// Validate input parameter
if (!stream) {
debug(LOG_ERR, "Cannot add NULL stream");
return;
}
// Check if stream already exists
struct tmux_stream *existing = NULL;
HASH_FIND_INT(all_stream, &stream->id, existing);
if (existing) {
debug(LOG_WARNING, "Stream %u already exists in hash table", stream->id);
return;
}
// Add stream to hash table
HASH_ADD_INT(all_stream, id, stream);
debug(LOG_DEBUG, "Added stream %u to hash table", stream->id);
}
/**
* @brief Deletes a stream with the specified ID from the hash table.
*
* This function removes a stream identified by the given ID from the global
* hash table `all_stream`. If the stream is found, it is deleted from the
* hash table. Note that the stream itself is not freed in this function; it
* will be freed when the associated proxy client is freed.
*
* @param id The ID of the stream to be deleted.
*/
void del_stream(uint32_t id) {
// Early return if hash table is not initialized
if (!all_stream) {
debug(LOG_DEBUG, "Stream hash table not initialized");
return;
}
// Find stream in hash table
struct tmux_stream *stream = NULL;
HASH_FIND_INT(all_stream, &id, stream);
// Delete stream if found
if (stream) {
HASH_DEL(all_stream, stream);
debug(LOG_DEBUG, "Stream %u removed from hash table", id);
} else {
debug(LOG_DEBUG, "Stream %u not found in hash table", id);
}
// Note: Stream memory is freed when associated proxy client is freed
}
/**
* @brief Clears all streams from the global hash table.
*
* This function performs a complete cleanup of the global stream hash table.
* It safely handles the case where the hash table is already empty.
* After clearing, the global pointer is set to NULL to prevent dangling references.
*
* @note This function should be called during shutdown or when a complete reset is needed.
* @note This is a destructive operation - all stream entries will be removed.
*/
void clear_stream(void) {
if (all_stream) {
HASH_CLEAR(hh, all_stream);
all_stream = NULL;
debug(LOG_DEBUG, "Cleared all streams from hash table");
}
}
/**
* @brief Retrieves a stream from the global hash table by its ID.
*
* @param id The unique identifier of the stream to find
* @return struct tmux_stream* Pointer to the found stream, or NULL if not found
*
* @note This function is thread-safe since the hash table operations are atomic
* @note Returns NULL if the global hash table is not initialized
*/
struct tmux_stream *get_stream_by_id(uint32_t id) {
// Early return if hash table is not initialized
if (!all_stream) {
debug(LOG_DEBUG, "Stream hash table not initialized");
return NULL;
}
// Look up stream in hash table
struct tmux_stream *stream = NULL;
HASH_FIND_INT(all_stream, &id, stream);
if (!stream) {
debug(LOG_DEBUG, "Stream %u not found", id);
}
return stream;
}
/**
* @brief Retrieves the current tmux stream.
*
* Returns a pointer to the current multiplexed TCP stream that is being processed.
* This stream represents the active connection being handled by the TCP multiplexer.
*
* @return Pointer to the current tmux_stream structure, or NULL if no stream is active
*/
struct tmux_stream *get_cur_stream() {
return cur_stream;
}
/**
* @brief Sets the current tmux stream.
*
* Sets the global current stream pointer. This function performs validation
* to ensure we don't set an invalid stream pointer.
*
* @param stream Pointer to the tmux stream to set as current. Can be NULL to clear.
*/
void set_cur_stream(struct tmux_stream *stream) {
// No validation needed since NULL is valid to clear current stream
cur_stream = stream;
debug(LOG_DEBUG, "Current stream %s",
stream ? "updated" : "cleared");
}
/**
* @brief Initializes a tmux stream with the given parameters.
*
* This function sets up a tmux stream by initializing its ID, state,
* receive window, send window, and ring buffers. It also adds the stream
* to the stream management system.
*
* @param stream Pointer to the tmux_stream structure to be initialized.
* @param id The unique identifier for the stream.
* @param state The initial state of the stream, specified by the tcp_mux_state enum.
*/
void init_tmux_stream(struct tmux_stream *stream, uint32_t id, enum tcp_mux_state state) {
// Validate input parameters
if (!stream) {
debug(LOG_ERR, "Invalid stream pointer");
return;
}
if (state > RESET) {
debug(LOG_ERR, "Invalid stream state: %d", state);
return;
}
// Initialize stream properties
stream->id = id;
stream->state = state;
stream->recv_window = MAX_STREAM_WINDOW_SIZE;
stream->send_window = MAX_STREAM_WINDOW_SIZE;
// Clear ring buffers
memset(&stream->tx_ring, 0, sizeof(struct ring_buffer));
memset(&stream->rx_ring, 0, sizeof(struct ring_buffer));
// Add stream to global tracking
add_stream(stream);
debug(LOG_DEBUG, "Initialized stream %u with state %d", id, state);
}
/**
* @brief Validates the TCP MUX protocol header.
*
* This function checks if the provided TCP MUX header has a valid version
* and type. The header is considered valid if its version matches the
* expected protocol version and its type does not exceed the maximum
* allowed type (GO_AWAY).
*
* @param tmux_hdr Pointer to the TCP MUX header to be validated.
* @return Returns 1 if the header is valid, 0 otherwise.
*/
int validate_tcp_mux_protocol(struct tcp_mux_header *tmux_hdr) {
if (tmux_hdr->version != proto_version)
return 0;
if (tmux_hdr->type > GO_AWAY)
return 0;
return 1;
}
/**
* @brief Encodes a TCP multiplexer header with the specified parameters
*
* This function fills a TCP multiplexer header structure with the provided values,
* performing necessary network byte order conversions for cross-platform compatibility.
*
* @param type The type of TCP multiplexer message (e.g., DATA, WINDOW_UPDATE)
* @param flags Control flags for the message
* @param stream_id Identifier for the stream this message belongs to
* @param length Length of the message payload
* @param tmux_hdr Pointer to header structure to be filled
*
* @pre tmux_hdr must not be NULL
* @pre type must be a valid tcp_mux_type enum value
*/
void tcp_mux_encode(enum tcp_mux_type type, enum tcp_mux_flag flags,
uint32_t stream_id, uint32_t length,
struct tcp_mux_header *tmux_hdr) {
// Validate input parameters
if (!tmux_hdr) {
debug(LOG_ERR, "NULL header pointer provided");
return;
}
if (type > GO_AWAY) {
debug(LOG_ERR, "Invalid TCP MUX type: %d", type);
return;
}
// Fill header fields with provided values
tmux_hdr->version = proto_version;
tmux_hdr->type = type;
// Convert multi-byte fields to network byte order
tmux_hdr->flags = htons(flags);
tmux_hdr->stream_id = htonl(stream_id);
tmux_hdr->length = length ? htonl(length) : 0;
}
/**
* @brief Gets the TCP multiplexing configuration flag.
*
* Retrieves the TCP multiplexing flag from the common configuration.
* This flag determines whether TCP multiplexing is enabled for the
* current session.
*
* @return The TCP multiplexing flag value from configuration
* Returns 0 if configuration is not available
*/
static uint32_t tcp_mux_flag() {
struct common_conf *c_conf = get_common_config();
if (!c_conf) {
debug(LOG_ERR, "Failed to get common configuration");
return 0;
}
return c_conf->tcp_mux;
}
/**
* @brief Resets the global session ID to its initial value.
*
* This function sets the global session ID (g_session_id) to 1.
* It is typically used to reinitialize the session ID counter.
*/
void reset_session_id() {
__atomic_store_n(&g_session_id, 1, __ATOMIC_SEQ_CST);
}
/**
* @brief Generates the next unique session ID.
*
* This function generates a monotonically increasing session ID by incrementing
* the global session ID counter by 2. This ensures each new session gets a unique
* odd-numbered ID, while even numbers are reserved for other purposes.
*
* @return The newly generated session ID
*
* @note The function increments by 2 to maintain odd-numbered IDs
*/
uint32_t get_next_session_id() {
uint32_t current_id = __atomic_fetch_add(&g_session_id, 2, __ATOMIC_SEQ_CST);
return current_id;
}
/**
* @brief Sends a TCP multiplexer window update message
*
* Constructs and sends a window update message through the specified bufferevent.
* The message includes flags, stream ID and window size delta information.
*
* @param bout The bufferevent to write the window update to
* @param flags Control flags for the window update
* @param stream_id ID of the stream being updated
* @param delta Change in window size
*
* @note Function silently returns if bufferevent is invalid
*/
static void tcp_mux_send_win_update(struct bufferevent *bout,
enum tcp_mux_flag flags,
uint32_t stream_id,
uint32_t delta) {
// Validate bufferevent
if (!bout) {
debug(LOG_ERR, "Invalid bufferevent for window update");
return;
}
// Prepare header
struct tcp_mux_header tmux_hdr;
memset(&tmux_hdr, 0, sizeof(tmux_hdr));
tcp_mux_encode(WINDOW_UPDATE, flags, stream_id, delta, &tmux_hdr);
// Send window update
if (bufferevent_write(bout, &tmux_hdr, sizeof(tmux_hdr)) < 0) {
debug(LOG_ERR, "Failed to send window update for stream %u", stream_id);
return;
}
debug(LOG_DEBUG, "Sent window update: stream=%u, delta=%u, flags=%u",
stream_id, delta, flags);
}
/**
* @brief Sends a window update with SYN flag for a TCP multiplexed stream.
*
* This function sends a window update message with the SYN flag set for
* a specified stream. The message is only sent if TCP multiplexing is enabled.
*
* @param bout The bufferevent to write the window update to
* @param stream_id The ID of the stream to send the update for
*
* @note Function silently returns if TCP multiplexing is disabled
* or if bufferevent is invalid
*/
void tcp_mux_send_win_update_syn(struct bufferevent *bout, uint32_t stream_id) {
// Early return if TCP multiplexing is disabled
if (!tcp_mux_flag()) {
debug(LOG_DEBUG, "TCP multiplexing is disabled");
return;
}
// Validate bufferevent
if (!bout) {
debug(LOG_ERR, "Invalid bufferevent for SYN");
return;
}
// Send window update with SYN flag
tcp_mux_send_win_update(bout, SYN, stream_id, 0);
debug(LOG_DEBUG, "Sent SYN for stream %u", stream_id);
}
/**
* @brief Sends a window update acknowledgment for a TCP multiplexed stream.
*
* This function sends a window update acknowledgment message for a specified stream
* if TCP multiplexing is enabled. It includes validation checks and proper error handling.
*
* @param bout Pointer to the bufferevent structure to send the acknowledgment through
* @param stream_id The ID of the stream being acknowledged
* @param delta The window size delta (currently unused, kept for API compatibility)
*
* @note Function silently returns if TCP multiplexing is disabled or if bufferevent is invalid
*/
void tcp_mux_send_win_update_ack(struct bufferevent *bout, uint32_t stream_id,
uint32_t delta) {
// Early return if TCP multiplexing is disabled
if (!tcp_mux_flag()) {
debug(LOG_DEBUG, "TCP multiplexing is disabled");
return;
}
// Validate bufferevent
if (!bout) {
debug(LOG_ERR, "Invalid bufferevent for ACK");
return;
}
// Send window update with ACK flag
tcp_mux_send_win_update(bout, ACK, stream_id, 0);
debug(LOG_DEBUG, "Sent ACK for stream %u", stream_id);
}
/**
* Sends a window update with a FIN flag for a given stream.
*
* This function checks if the TCP multiplexing flag is enabled. If it is,
* it sends a window update with the FIN flag for the specified stream ID.
*
* @param bout A pointer to the bufferevent structure where the window update will be sent.
* @param stream_id The ID of the stream for which the window update with FIN flag is sent.
*/
void tcp_mux_send_win_update_fin(struct bufferevent *bout, uint32_t stream_id) {
// Early return if TCP multiplexing is disabled
if (!tcp_mux_flag()) {
debug(LOG_DEBUG, "TCP multiplexing is disabled");
return;
}
// Validate bufferevent
if (!bout) {
debug(LOG_ERR, "Invalid bufferevent for FIN");
return;
}
// Send window update with FIN flag
tcp_mux_send_win_update(bout, FIN, stream_id, 0);
debug(LOG_DEBUG, "Sent FIN for stream %u", stream_id);
}
/**
* @brief Sends a window update with RST flag for a TCP multiplexed stream
*
* This function sends a window update message with the RST (reset) flag set for
* the specified stream ID. The message is only sent if TCP multiplexing is enabled.
*
* @param bout The bufferevent to write the window update to
* @param stream_id The ID of the stream to reset
*
* @note Function silently returns if TCP multiplexing is disabled
* or if bufferevent is invalid
*/
void tcp_mux_send_win_update_rst(struct bufferevent *bout, uint32_t stream_id) {
// Early return if TCP multiplexing is disabled
if (!tcp_mux_flag()) {
debug(LOG_DEBUG, "TCP multiplexing is disabled");
return;
}
// Validate bufferevent
if (!bout) {
debug(LOG_ERR, "Invalid bufferevent for RST");
return;
}
// Send window update with RST flag
tcp_mux_send_win_update(bout, RST, stream_id, 0);
debug(LOG_DEBUG, "Sent RST for stream %u", stream_id);
}
/**
* @brief Sends data over a TCP multiplexed connection.
*
* This function sends data over a TCP multiplexed connection using the provided
* bufferevent. It first checks if the TCP multiplexing flag is set. If not, it
* returns immediately. Otherwise, it prepares a TCP multiplexing header, encodes
* the provided data into the header, and writes the header to the bufferevent.
*
* @param bout The bufferevent to write the data to.
* @param flags Flags indicating the status or type of the data.
* @param stream_id The ID of the stream to which the data belongs.
* @param length The length of the data to be sent.
*/
void tcp_mux_send_data(struct bufferevent *bout, uint16_t flags,
uint32_t stream_id, uint32_t length) {
// Early return if TCP multiplexing is disabled
if (!tcp_mux_flag()) {
debug(LOG_DEBUG, "TCP multiplexing is disabled");
return;
}
// Validate input parameters
if (!bout) {
debug(LOG_ERR, "Invalid bufferevent for sending data");
return;
}
// Prepare and send header
struct tcp_mux_header tmux_hdr;
memset(&tmux_hdr, 0, sizeof(tmux_hdr));
tcp_mux_encode(DATA, flags, stream_id, length, &tmux_hdr);
if (bufferevent_write(bout, &tmux_hdr, sizeof(tmux_hdr)) < 0) {
debug(LOG_ERR, "Failed to send data header for stream %u", stream_id);
}
}
/**
* @brief Sends a ping message over a TCP multiplexed connection
*
* This function constructs and sends a ping message with the SYN flag set
* if TCP multiplexing is enabled. The ping message includes a unique ping ID
* for tracking responses.
*
* @param bout The bufferevent to send the ping through
* @param ping_id Unique identifier for this ping message
*
* @note Function silently returns if TCP multiplexing is disabled
* or if bufferevent is invalid
*/
void tcp_mux_send_ping(struct bufferevent *bout, uint32_t ping_id) {
// Early return if TCP multiplexing is disabled
if (!tcp_mux_flag()) {
debug(LOG_DEBUG, "TCP multiplexing is disabled");
return;
}
// Validate bufferevent
if (!bout) {
debug(LOG_ERR, "Invalid bufferevent for ping");
return;
}
// Prepare and send ping message
struct tcp_mux_header tmux_hdr;
memset(&tmux_hdr, 0, sizeof(tmux_hdr));
tcp_mux_encode(PING, SYN, 0, ping_id, &tmux_hdr);
if (bufferevent_write(bout, &tmux_hdr, sizeof(tmux_hdr)) < 0) {
debug(LOG_ERR, "Failed to send ping message");
}
}
/**
* @brief Handles TCP multiplexer ping messages by sending an acknowledgment.
*
* This function responds to ping messages with a ping acknowledgment (ACK).
* It validates input parameters and TCP multiplexing status before sending
* the response.
*
* @param bout The bufferevent to write the ping acknowledgment to
* @param ping_id The ID of the ping message to acknowledge
*
* @note The function will silently return if TCP multiplexing is disabled
* or if the bufferevent is invalid
*/
static void tcp_mux_handle_ping(struct bufferevent *bout, uint32_t ping_id) {
// Early return if TCP multiplexing is disabled
if (!tcp_mux_flag()) {
debug(LOG_DEBUG, "TCP multiplexing is disabled");
return;
}
// Validate bufferevent
if (!bout) {
debug(LOG_ERR, "Invalid bufferevent for ping response");
return;
}
// Prepare and send ping acknowledgment
struct tcp_mux_header tmux_hdr;
memset(&tmux_hdr, 0, sizeof(tmux_hdr));
tcp_mux_encode(PING, ACK, 0, ping_id, &tmux_hdr);
if (bufferevent_write(bout, &tmux_hdr, sizeof(tmux_hdr)) < 0) {
debug(LOG_ERR, "Failed to send ping acknowledgment");
}
}
/**
* @brief Sends a GO_AWAY message using the provided bufferevent.
*
* This function constructs a GO_AWAY message and sends it through the specified
* bufferevent. The message is sent only if the tcp_mux_flag() returns true.
*
* @param bout The bufferevent through which the GO_AWAY message will be sent.
* @param reason The reason code to be included in the GO_AWAY message.
*/
static void tcp_mux_send_go_away(struct bufferevent *bout, uint32_t reason) {
// Early return if TCP multiplexing is disabled or buffer event is invalid
if (!tcp_mux_flag() || !bout) {
debug(LOG_ERR, "Cannot send GO_AWAY: invalid state or parameters");
return;
}
// Validate reason code
if (reason > INTERNAL_ERR) {
debug(LOG_WARNING, "Invalid GO_AWAY reason code: %u", reason);
reason = INTERNAL_ERR;
}
// Prepare and send header
struct tcp_mux_header tmux_hdr;
memset(&tmux_hdr, 0, sizeof(tmux_hdr));
tcp_mux_encode(GO_AWAY, 0, 0, reason, &tmux_hdr);
if (bufferevent_write(bout, &tmux_hdr, sizeof(tmux_hdr)) < 0) {
debug(LOG_ERR, "Failed to send GO_AWAY message");
}
}
/**
* @brief Processes the given flags and updates the state of the tmux stream accordingly.
*
* This function handles the ACK, FIN, and RST flags and transitions the state of the
* tmux stream based on the current state and the received flags. It also handles the
* closing of the stream if necessary.
*
* @param flags The flags to process.
* @param stream The tmux stream to update.
* @return Returns 1 on success, 0 on failure.
*/
static int process_flags(uint16_t flags, struct tmux_stream *stream) {
bool should_close = false;
if (flags & ACK) {
if (stream->state == SYN_SEND) {
stream->state = ESTABLISHED;
}
}
if (flags & FIN) {
switch (stream->state) {
case SYN_SEND:
case SYN_RECEIVED:
case ESTABLISHED:
stream->state = REMOTE_CLOSE;
break;
case LOCAL_CLOSE:
stream->state = CLOSED;
should_close = true;
break;
default:
debug(LOG_ERR, "unexpected FIN flag in state %d", stream->state);
return 0;
}
}
if (flags & RST) {
stream->state = RESET;
should_close = true;
}
if (should_close) {
debug(LOG_DEBUG, "free stream %d", stream->id);
del_proxy_client_by_stream_id(stream->id);
}
return 1;
}
/**
* @brief Get the flags to be sent based on the current state of the stream.
*
* This function determines the appropriate flags to be sent based on the
* current state of the given tmux_stream. It also updates the state of the
* stream accordingly.
*
* @param stream A pointer to the tmux_stream structure.
* @return A uint16_t value representing the flags to be sent.
*/
static uint16_t get_send_flags(struct tmux_stream *stream) {
uint16_t flags = 0;
if (!stream) {
return flags;
}
switch (stream->state) {
case INIT:
flags |= SYN;
stream->state = SYN_SEND;
break;
case SYN_RECEIVED:
flags |= ACK;
stream->state = ESTABLISHED;
break;
default:
break;
}
return flags;
}
/**
* @brief Sends a window update message for stream flow control.
*
* Updates the receive window for a stream and sends a window update message
* if the delta exceeds half of the maximum window size or if there are flags to send.
*
* @param bout Buffered output event for sending data.
* @param stream Pointer to the tmux stream to update.
* @param length Current receive buffer length.
*/
void send_window_update(struct bufferevent *bout, struct tmux_stream *stream, uint32_t length) {
const uint32_t max_window = MAX_STREAM_WINDOW_SIZE;
const uint32_t half_max_window = max_window / 2;
uint32_t delta = max_window > (length + stream->recv_window)
? max_window - length - stream->recv_window
: 0;
uint16_t flags = get_send_flags(stream);
if (delta < half_max_window && flags == 0) {
return;
}
stream->recv_window = MIN(stream->recv_window + delta, max_window);
tcp_mux_send_win_update(bout, flags, stream->id, delta);
}
/**
* Pops data from a ring buffer.
*
* @param ring Pointer to the ring buffer structure to pop from
* @param data Pointer to buffer where popped data will be stored
* @param len Number of bytes to pop from the ring buffer
*
* @pre ring->sz must be >= len
* @pre data pointer must not be NULL
*
* @return The number of bytes popped from the buffer (equal to len)
*
* This function removes len bytes from the ring buffer and copies them
* to the provided data buffer. The ring buffer's current position and size
* are updated accordingly. When reaching the end of the buffer, it wraps
* around to the beginning.
*/
int rx_ring_buffer_pop(struct ring_buffer *ring, uint8_t *data, uint32_t len) {
assert(ring->sz >= len);
assert(data);
uint32_t remaining = len;
uint8_t *dst = data;
while (remaining > 0) {
uint32_t chunk = MIN(remaining, RBUF_SIZE - ring->cur);
memcpy(dst, &ring->data[ring->cur], chunk);
dst += chunk;
ring->cur = (ring->cur + chunk) % RBUF_SIZE;
ring->sz -= chunk;
remaining -= chunk;
}
return len;
}
/**
* @brief Processes data received from a tmux stream
*
* This function handles data received from a multiplexed stream, managing window size
* and forwarding data to appropriate handlers based on proxy type.
*
* @param stream Pointer to the tmux_stream structure containing stream information
* @param length Length of data to be processed
* @param flags Stream control flags
* @param fn Callback function to handle processed data
* @param param Additional parameters (typically proxy client structure)
*
* @return Returns length of processed data on success, 0 on failure
*
* The function performs the following operations:
* - Validates stream and flags
* - Checks receive window capacity
* - Updates receive window size
* - Handles data forwarding based on proxy type:
* - Regular proxy: Uses provided callback function
* - SOCKS5 proxy: Forwards to SOCKS5 client
* - Local proxy: Writes to local proxy bufferevent
* - Sends window update after processing
*/
static int process_data(struct tmux_stream *stream, uint32_t length,
uint16_t flags, void (*handle_fn)(uint8_t *, int, void *),
void *param) {
if (!stream || !handle_fn) {
debug(LOG_ERR, "Invalid parameters in process_data");
return 0;
}
uint32_t stream_id = stream->id;
if (!process_flags(flags, stream)) {
debug(LOG_ERR, "Failed to process flags for stream %d", stream_id);
return 0;
}
if (!get_stream_by_id(stream_id)) {
debug(LOG_DEBUG, "Stream %d no longer exists", stream_id);
return length;
}
if (length > stream->recv_window) {
debug(LOG_ERR, "Receive window exceeded (available: %u, requested: %u)",
stream->recv_window, length);
return 0;
}
stream->recv_window -= length;
struct proxy_client *pc = (struct proxy_client *)param;
uint32_t bytes_processed = 0;
if (!pc || (!pc->local_proxy_bev && !is_socks5_proxy(pc->ps))) {
uint8_t *data = calloc(length, sizeof(uint8_t));
if (!data) {
debug(LOG_ERR, "Memory allocation failed for data buffer");
return 0;
}
bytes_processed = rx_ring_buffer_pop(&stream->rx_ring, data, length);
handle_fn(data, bytes_processed, pc);
free(data);
}
else if (is_socks5_proxy(pc->ps)) {
bytes_processed = handle_ss5(pc, &stream->rx_ring, length);
}
else {
bytes_processed = tx_ring_buffer_write(pc->local_proxy_bev,
&stream->rx_ring,
length);
}
if (bytes_processed != length) {
debug(LOG_INFO, "Incomplete data transfer - processed: %u, expected: %u",
bytes_processed, length);
}
struct bufferevent *bout = get_main_control()->connect_bev;
send_window_update(bout, stream, bytes_processed);
return length;
}
/**
* @brief Increases the send window of a multiplexed TCP stream.
*
* This function handles the send window increment for a TCP multiplexed stream.
* It processes the flags, validates the stream exists, and updates its send window.
* When the send window transitions from 0, it re-enables read events on the buffer.
*
* @param bev The bufferevent associated with the connection
* @param tmux_hdr Pointer to the TCP multiplexer header containing length info
* @param flags The flags from the TCP multiplexer header
* @param stream Pointer to the stream to update
*
* @return 1 on successful window increment, 0 on invalid stream or failed flag processing
*/
static int incr_send_window(struct bufferevent *bev,
struct tcp_mux_header *tmux_hdr, uint16_t flags,
struct tmux_stream *stream) {
// Validate input parameters
if (!bev || !tmux_hdr || !stream) {
debug(LOG_ERR, "Invalid parameters in incr_send_window");
return 0;
}
// Save stream ID for later use
uint32_t stream_id = stream->id;
// Process control flags first
if (!process_flags(flags, stream)) {
debug(LOG_ERR, "Failed to process flags for stream %d", stream_id);
return 0;
}
// Verify stream still exists after flag processing
if (!get_stream_by_id(stream_id)) {
debug(LOG_DEBUG, "Stream %d no longer exists", stream_id);
return 1;
}
// Get window increment size
uint32_t increment = ntohl(tmux_hdr->length);
// Enable read events if window was previously full
if (stream->send_window == 0) {
debug(LOG_DEBUG, "Enabling read events for stream %d", stream_id);
bufferevent_enable(bev, EV_READ);
}
// Update send window
stream->send_window += increment;
debug(LOG_DEBUG, "Stream %d send window increased by %u to %u",
stream_id, increment, stream->send_window);
return 1;
}
/**
* @brief Handles incoming stream requests
*
* Processes new incoming stream requests identified by stream_id. If local_go_away
* is set, sends a window update reset message and rejects the stream. Otherwise,
* creates a new stream (TODO implementation).
*
* @param stream_id The unique identifier for the incoming stream
* @return 0 if stream is rejected due to local_go_away, 1 if stream should be created
*/
static int incoming_stream(uint32_t stream_id) {
if (local_go_away) {
struct bufferevent *bout = get_main_control()->connect_bev;
tcp_mux_send_win_update_rst(bout, stream_id);
return 0;
}
// TODO
// create new stream
return 1;
}
/**
* @brief Handles TCP multiplexer ping messages
*
* This function processes incoming TCP multiplexer ping headers. If the SYN flag
* is set in the header flags, it retrieves the main control connection's bufferevent
* and handles the ping with the specified ping ID.
*
* @param tmux_hdr Pointer to the TCP multiplexer header structure containing
* the ping message information
*
* @note The ping_id and flags are converted from network to host byte order
* before processing
*/
/**
* @brief Handles TCP multiplexer ping messages
*
* Processes incoming TCP multiplexer ping messages and sends appropriate responses.
* When a SYN flag is received in the ping message, it sends back a ping acknowledgment
* to maintain connection liveliness.
*
* @param tmux_hdr Pointer to the TCP multiplexer header containing ping information
*
* @note Only responds to pings with SYN flag set
* @note Ping ID is converted from network byte order before processing
*/
void handle_tcp_mux_ping(struct tcp_mux_header *tmux_hdr) {
if (!tmux_hdr) {
debug(LOG_ERR, "Invalid TCP MUX header");
return;
}
struct bufferevent *bout = NULL;
uint16_t flags = ntohs(tmux_hdr->flags);
uint32_t ping_id = ntohl(tmux_hdr->length);
// Only handle ping messages with SYN flag
if ((flags & SYN) == SYN) {
if (!(bout = get_main_control()->connect_bev)) {
debug(LOG_ERR, "No valid bufferevent for ping response");
return;
}
tcp_mux_handle_ping(bout, ping_id);
}
}
/**
* @brief Handles TCP multiplexer "go away" messages.
*
* Processes "go away" messages received from the remote TCP multiplexer based on
* provided error codes. Sets appropriate flags and logs error messages depending
* on the specific error code received.
*
* @param tmux_hdr Pointer to the TCP multiplexer header structure containing
* the "go away" message details
*
* Error codes handled:
* - NORMAL: Sets remote_go_away flag
* - PROTO_ERR: Logs protocol error
* - INTERNAL_ERR: Logs internal error
* - Other codes: Logs unexpected error
*/
void handle_tcp_mux_go_away(struct tcp_mux_header *tmux_hdr) {
if (!tmux_hdr) {
debug(LOG_ERR, "Invalid TCP MUX header");
return;
}
uint32_t code = ntohl(tmux_hdr->length);
const char *error_msg = NULL;
// Map error codes to messages
switch (code) {
case NORMAL:
remote_go_away = 1;
error_msg = "Normal shutdown requested";
break;
case PROTO_ERR:
error_msg = "Protocol error detected";