-
Notifications
You must be signed in to change notification settings - Fork 92
/
control.c
2104 lines (1865 loc) · 58.3 KB
/
control.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 <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <assert.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <json-c/json.h>
#include <syslog.h>
#include <unistd.h>
#include <time.h>
#include <stdbool.h>
#include "debug.h"
#include "client.h"
#include "uthash.h"
#include "config.h"
#include "msg.h"
#include "control.h"
#include "crypto.h"
#include "utils.h"
#include "common.h"
#include "login.h"
#include "tcpmux.h"
#include "proxy.h"
static struct control *main_ctl;
static bool xfrpc_status;
static int is_login;
static time_t pong_time;
static void new_work_connection(struct bufferevent *bev, struct tmux_stream *stream);
static void recv_cb(struct bufferevent *bev, void *ctx);
static void clear_main_control(void);
static void start_base_connect(void);
static void keep_control_alive(void);
static void client_start_event_cb(struct bufferevent *bev, short what, void *ctx);
/**
* Check if xfrpc client is connected to server
*
* @return true if connected, false otherwise
*/
static bool is_xfrpc_connected(void)
{
return xfrpc_status;
}
/**
* Updates the global connection status flag for xfrpc.
*
* @param is_connected Boolean flag indicating whether xfrpc is connected (true) or disconnected (false)
*
* Sets the global xfrpc_status variable and logs the new connection state at debug level.
*/
static void set_xfrpc_status(bool is_connected)
{
// Set global connection status flag
xfrpc_status = is_connected;
debug(LOG_DEBUG, "xfrpc connection status set to: %s", is_connected ? "connected" : "disconnected");
}
/**
* Sets the work status of a proxy client.
*
* @param client The proxy client structure to modify
* @param is_start_work Non-zero value to start work, zero to stop
* @return Returns 1 if client is set to work, 0 if client is set to stop or if invalid parameters
*
* This function updates the work_started flag of a proxy client. It performs validation
* to ensure the client and its proxy service exist before modifying the status.
*/
static int set_client_work_start(struct proxy_client *client, int is_start_work)
{
if (!client || !client->ps) {
debug(LOG_ERR, "Invalid client or proxy service");
return 0;
}
client->work_started = (is_start_work != 0);
return client->work_started;
}
/**
* @brief Handles errors for proxy client connections
*
* This function handles errors that occur on the control connection to the server.
* It performs cleanup by:
* 1. Verifying and freeing mismatched control bufferevents
* 2. Logging the connection error details
* 3. Freeing the bufferevent
* 4. Removing the proxy client from tracking
*
* @param client The proxy client structure containing connection state
* @param bev The bufferevent that encountered an error
* @param c_conf Common configuration containing server connection details
*/
static void handle_client_error(struct proxy_client *client, struct bufferevent *bev,
const struct common_conf *c_conf)
{
// Verify control bufferevent matches
if (client->ctl_bev != bev) {
debug(LOG_ERR, "Bufferevent mismatch - freeing existing control bufferevent");
bufferevent_free(client->ctl_bev);
client->ctl_bev = NULL;
}
debug(LOG_ERR, "Connection error to server [%s:%d]: %s",
c_conf->server_addr, c_conf->server_port, strerror(errno));
// Cleanup
bufferevent_free(bev);
del_proxy_client_by_stream_id(client->stream_id);
}
/**
* @brief Handles the setup of a newly connected proxy client
*
* This function configures the bufferevent callbacks and initializes
* the work connection for a newly connected proxy client. It:
* - Sets up read/write event callbacks for the bufferevent
* - Initializes a new work connection with the given bufferevent
* - Enables the proxy service status
*
* @param client Pointer to the proxy client structure
* @param bev Pointer to the bufferevent structure for this connection
*/
static void handle_client_connected(struct proxy_client *client, struct bufferevent *bev)
{
// Setup callbacks and enable events
bufferevent_setcb(bev, recv_cb, NULL, client_start_event_cb, client);
bufferevent_enable(bev, EV_READ|EV_WRITE);
// Initialize work connection
new_work_connection(bev, &main_ctl->stream);
set_xfrpc_status(true);
debug(LOG_INFO, "Proxy service started successfully");
}
/**
* @brief Callback function for handling client connection events
*
* This callback is triggered for connection-related events of a bufferevent. It handles:
* - Connection errors
* - EOF (End of File) conditions
* - Successful connections
*
* The function performs validation of input parameters and retrieves common configuration
* before processing any events. If errors occur, appropriate error handling is performed.
*
* @param bev Pointer to the bufferevent structure that triggered the callback
* @param what Bit mask of events that triggered the callback (BEV_EVENT_*)
* @param ctx Context pointer containing the proxy client structure
*
* @note The context (ctx) is expected to be a pointer to proxy_client structure
*/
static void client_start_event_cb(struct bufferevent *bev, short what, void *ctx)
{
// Validate input parameters
if (!bev || !ctx) {
debug(LOG_ERR, "Invalid parameters: bev=%p, ctx=%p", bev, ctx);
return;
}
struct proxy_client *client = (struct proxy_client *)ctx;
struct common_conf *c_conf = get_common_config();
if (!c_conf) {
debug(LOG_ERR, "Failed to get common config");
return;
}
// Handle connection errors and EOF
if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
handle_client_error(client, bev, c_conf);
return;
}
// Handle successful connection
if (what & BEV_EVENT_CONNECTED) {
handle_client_connected(client, bev);
}
}
/**
* @brief Initializes a TCP multiplexing client connection
*
* This function sets up a new TCP multiplexing client by:
* 1. Validating the client and control buffer event
* 2. Sending initial window update
* 3. Creating a new work connection
*
* @param client Pointer to the proxy client structure containing connection details
* @return 0 on success, -1 on failure
*
* @note Client must have valid proxy_client structure with initialized ctl_bev
*/
static int init_tcp_mux_client(struct proxy_client *client) {
if (!client || !client->ctl_bev) {
debug(LOG_ERR, "Invalid client for TCP mux initialization");
return -1;
}
debug(LOG_DEBUG, "New client through TCP mux: stream_id=%d", client->stream_id);
send_window_update(client->ctl_bev, &client->stream, 0);
new_work_connection(client->ctl_bev, &client->stream);
return 0;
}
/**
* @brief Initializes a direct client connection to a server
*
* This function establishes a direct connection to a specified server using the
* provided address and port. It creates a bufferevent for the connection and
* sets up the necessary callbacks.
*
* @param client Pointer to the proxy client structure
* @param server_addr Server address to connect to
* @param server_port Server port to connect to
*
* @return 0 on success, -1 on failure
*
* @note The function will log debug messages for both successful and failed
* connection attempts
*/
static int init_direct_client(struct proxy_client *client,
const char *server_addr,
int server_port) {
struct bufferevent *bev = connect_server(client->base, server_addr, server_port);
if (!bev) {
debug(LOG_ERR, "Failed to connect to server [%s:%d]",
server_addr, server_port);
return -1;
}
debug(LOG_INFO, "Work connection: connecting to server [%s:%d]...",
server_addr, server_port);
client->ctl_bev = bev;
bufferevent_enable(bev, EV_WRITE);
bufferevent_setcb(bev, NULL, NULL, client_start_event_cb, client);
return 0;
}
/**
* @brief Creates and initializes a new proxy client connection
*
* This function handles the creation of a new proxy client and establishes
* its connection. It performs the following steps:
* 1. Creates a new proxy client instance
* 2. Retrieves and validates common configuration
* 3. Initializes the client's event base
* 4. Sets up the connection based on TCP multiplexing configuration:
* - If TCP mux is enabled, initializes multiplexed client
* - If TCP mux is disabled, initializes direct client connection
*
* The function includes proper error handling and cleanup for failed operations.
*
* @note This function assumes the existence of a global main_ctl structure
* @note Memory is properly freed in case of initialization failures
*/
static void new_client_connect()
{
// Create new proxy client
struct proxy_client *client = new_proxy_client();
if (!client) {
debug(LOG_ERR, "Failed to create new proxy client");
return;
}
// Get and validate common config
struct common_conf *c_conf = get_common_config();
if (!c_conf) {
debug(LOG_ERR, "Failed to get common config");
free(client);
return;
}
// Initialize client base
client->base = main_ctl->connect_base;
if (!client->base) {
debug(LOG_ERR, "Invalid event base");
free(client);
return;
}
// Handle connection based on mux configuration
if (c_conf->tcp_mux) {
client->ctl_bev = main_ctl->connect_bev;
if (init_tcp_mux_client(client) != 0) {
free(client);
return;
}
} else {
if (init_direct_client(client, c_conf->server_addr, c_conf->server_port) != 0) {
free(client);
return;
}
}
}
/**
* @brief Initializes and starts all configured proxy services
*
* This function retrieves all configured proxy services and initiates them by:
* 1. Getting the list of all configured proxy services
* 2. Iterating through each service
* 3. Validating each service
* 4. Skipping MSTSC type proxies
* 5. Sending new proxy requests for valid services
*
* If no proxy services are configured, the function logs a message and returns.
* Invalid proxy services encountered during iteration are logged and skipped.
*
* @note MSTSC proxy types are explicitly skipped during processing
*/
static void start_proxy_services()
{
// Get configured proxy services
struct proxy_service *all_ps = get_all_proxy_services();
if (!all_ps) {
debug(LOG_INFO, "No proxy services configured");
return;
}
debug(LOG_INFO, "Starting xfrp proxy services...");
// Iterate through all proxy services
struct proxy_service *ps = NULL, *tmp = NULL;
HASH_ITER(hh, all_ps, ps, tmp) {
// Validate proxy service
if (!ps) {
debug(LOG_ERR, "Invalid proxy service encountered");
continue;
}
// Skip MSTSC proxy type
if (ps->proxy_type && strcmp(ps->proxy_type, "mstsc") == 0) {
debug(LOG_DEBUG, "Skipping MSTSC service");
continue;
}
// Send new proxy request
debug(LOG_DEBUG, "Sending proxy service: %s", ps->proxy_name);
send_new_proxy(ps);
}
}
/**
* @brief Sends a ping message to the FRP server to maintain connection
*
* This function validates the bufferevent connection and sends an empty JSON
* ping message to the FRP server. The ping message helps keep the connection
* alive and verify connectivity.
*
* The message is encrypted before sending using the stream encryption context
* stored in main_ctl.
*
* @note Requires valid main_ctl and connect_bev to be initialized
*/
static void ping(void)
{
// Validate bufferevent
if (!main_ctl || !main_ctl->connect_bev) {
debug(LOG_ERR, "Invalid bufferevent for ping");
return;
}
// Send empty ping message
const char *ping_msg = "{}";
send_enc_msg_frp_server(main_ctl->connect_bev,
TypePing,
ping_msg,
strlen(ping_msg),
&main_ctl->stream);
debug(LOG_DEBUG, "Sent ping message");
}
/**
* @brief Creates and sends a new work connection request to the FRP server
*
* This function handles the creation of a new work connection by:
* 1. Creating a new work connection structure
* 2. Retrieving the run ID
* 3. Marshalling the work connection request
* 4. Sending the request to the FRP server
*
* @param bev The bufferevent structure for network communication
* @param stream The tmux stream structure containing stream information
*
* @note This function performs cleanup of allocated resources before returning
* @note The run ID must be initialized during login before calling this function
*
* Error conditions:
* - Invalid bufferevent parameter
* - Failed work connection creation
* - Missing run ID
* - Failed message marshalling
*/
static void new_work_connection(struct bufferevent *bev, struct tmux_stream *stream)
{
// Validate input parameters
if (!bev) {
debug(LOG_ERR, "Invalid bufferevent parameter");
return;
}
// Create new work connection
struct work_conn *work_c = new_work_conn();
if (!work_c) {
debug(LOG_ERR, "Failed to create new work connection");
return;
}
// Get and validate run ID
work_c->run_id = get_run_id();
if (!work_c->run_id) {
debug(LOG_ERR, "Run ID not found - must be initialized during login");
SAFE_FREE(work_c);
return;
}
// Marshal work connection request
char *work_conn_msg = NULL;
int msg_len = new_work_conn_marshal(work_c, &work_conn_msg);
if (msg_len <= 0 || !work_conn_msg) {
debug(LOG_ERR, "Failed to marshal work connection request");
SAFE_FREE(work_c);
return;
}
// Send work connection request
debug(LOG_DEBUG, "Sending new work connection request: length=%d", msg_len);
send_msg_frp_server(bev, TypeNewWorkConn, work_conn_msg, msg_len, stream);
// Cleanup
SAFE_FREE(work_conn_msg);
SAFE_FREE(work_c);
}
/**
* Establishes a connection to a server using libevent bufferevent
*
* This function creates a bufferevent socket and connects it to a server specified
* by name and port. It handles both direct IP connections and hostname-based
* connections requiring DNS resolution.
*
* @param base The event_base to be used for the connection
* @param name The server address (IP or hostname)
* @param port The port number to connect to
*
* @return A pointer to the connected bufferevent structure on success,
* NULL on failure
*
* The function will:
* - Validate input parameters
* - Create a new bufferevent socket
* - For IP addresses: Connect directly using the IP
* - For hostnames: Use DNS resolution if available
*
* @note Requires main_ctl->dnsbase to be initialized for hostname resolution
* @note The returned bufferevent must be freed by the caller when no longer needed
*/
struct bufferevent *connect_server(struct event_base *base, const char *name, const int port)
{
// Validate input parameters
if (!base || !name || port <= 0) {
debug(LOG_ERR, "Invalid connection parameters: base=%p, name=%s, port=%d",
base, name ? name : "NULL", port);
return NULL;
}
// Create new bufferevent socket
struct bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
if (!bev) {
debug(LOG_ERR, "Failed to create new bufferevent socket");
return NULL;
}
// For IP addresses, connect directly without DNS
if (is_valid_ip_address(name)) {
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(name);
sin.sin_port = htons(port);
if (bufferevent_socket_connect(bev, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
debug(LOG_ERR, "Direct IP connection failed to %s:%d", name, port);
bufferevent_free(bev);
return NULL;
}
}
// Otherwise use DNS resolution
else if (main_ctl && main_ctl->dnsbase) {
if (bufferevent_socket_connect_hostname(bev, main_ctl->dnsbase,
AF_INET, name, port) < 0) {
debug(LOG_ERR, "DNS hostname connection failed to %s:%d", name, port);
bufferevent_free(bev);
return NULL;
}
}
else {
debug(LOG_ERR, "No DNS base available for hostname resolution");
bufferevent_free(bev);
return NULL;
}
return bev;
}
/**
* @brief Creates and initializes a UDP server connection using libevent
*
* This function sets up a UDP socket and creates a bufferevent for it with the following steps:
* 1. Creates a UDP socket
* 2. Makes the socket non-blocking
* 3. Creates a bufferevent for the socket with close-on-free option
*
* @param base Pointer to the event_base to be used for the bufferevent
* @return struct bufferevent* Pointer to the created bufferevent on success, NULL on failure
*
* @note The returned bufferevent must be freed by the caller when no longer needed
* @note The socket will be automatically closed when the bufferevent is freed
*/
struct bufferevent *connect_udp_server(struct event_base *base)
{
// Validate input parameter
if (!base) {
debug(LOG_ERR, "Invalid event base parameter");
return NULL;
}
// Create UDP socket
evutil_socket_t fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (fd < 0) {
debug(LOG_ERR, "Failed to create UDP socket: %s", strerror(errno));
return NULL;
}
// Make socket non-blocking
if (evutil_make_socket_nonblocking(fd) < 0) {
debug(LOG_ERR, "Failed to make UDP socket non-blocking: %s", strerror(errno));
evutil_closesocket(fd);
return NULL;
}
// Create bufferevent for UDP socket
struct bufferevent *bev = bufferevent_socket_new(base, fd,
BEV_OPT_CLOSE_ON_FREE);
if (!bev) {
debug(LOG_ERR, "Failed to create UDP bufferevent: %s", strerror(errno));
evutil_closesocket(fd);
return NULL;
}
debug(LOG_DEBUG, "UDP server connection initialized successfully");
return bev;
}
/**
* @brief Schedules a heartbeat timer event
*
* This function schedules a periodic heartbeat timer using the heartbeat interval
* specified in the common configuration. The timer is used to send periodic
* heartbeat messages to maintain the connection.
*
* @param timeout Pointer to the event structure to be scheduled
*
* @note The heartbeat interval is read from the common configuration
* @note The function will log errors if the timer or config is invalid
* @note The timer is scheduled with microseconds set to 0
*/
static void schedule_heartbeat_timer(struct event *timeout) {
if (!timeout) {
debug(LOG_ERR, "Invalid timer event");
return;
}
struct common_conf *conf = get_common_config();
if (!conf) {
debug(LOG_ERR, "Failed to get common config");
return;
}
struct timeval tv = {
.tv_sec = conf->heartbeat_interval,
.tv_usec = 0
};
if (event_add(timeout, &tv) < 0) {
debug(LOG_ERR, "Failed to schedule heartbeat timer");
}
}
/**
* Checks if the server connection has timed out based on the last pong response time.
* If a timeout is detected, it resets the session and restarts the control process.
*
* The function compares the time elapsed since the last pong response against the
* heartbeat timeout value from the common configuration. If the elapsed time exceeds
* the timeout threshold, it triggers a reconnection sequence.
*
* @param current_time The current system time to check against
*
* @note Requires pong_time to be set by the pong handler
* @note Requires valid common configuration with heartbeat_timeout value
*/
static void check_server_timeout(time_t current_time) {
struct common_conf *conf = get_common_config();
if (!conf) {
debug(LOG_ERR, "Failed to get common config");
return;
}
if (!pong_time) {
return;
}
int elapsed = current_time - pong_time;
if (elapsed > conf->heartbeat_timeout) {
debug(LOG_INFO, "Server timeout detected: elapsed=%d seconds, timeout=%d seconds",
elapsed, conf->heartbeat_timeout);
reset_session_id();
clear_main_control();
run_control();
}
}
/**
* @brief Timer callback handler for heartbeat operations
*
* This function handles periodic heartbeat operations:
* 1. Sends ping to server if client is connected
* 2. Reschedules the next heartbeat timer
* 3. Checks for server timeout condition
*
* @param fd Socket file descriptor (unused)
* @param event Event type that triggered callback (unused)
* @param arg User-provided callback argument (unused)
*
* @note The function uses global state to track connection status and timing
* @note If getting current time fails, the function returns early without timeout check
*/
static void heartbeat_handler(evutil_socket_t fd, short event, void *arg) {
// Send ping if client is connected
if (is_xfrpc_connected()) {
debug(LOG_INFO, "Sending heartbeat ping to server");
ping();
}
// Reschedule next heartbeat
schedule_heartbeat_timer(main_ctl->ticker_ping);
// Check for server timeout
time_t current_time = time(NULL);
if (current_time == (time_t)-1) {
debug(LOG_ERR, "Failed to get current time");
return;
}
check_server_timeout(current_time);
}
/**
* Handles configuration for FTP proxy service by updating the remote data port
* of the main FTP proxy service.
*
* @param ps The proxy service containing FTP configuration
* @param npr The new proxy response containing remote port information
*
* @return 1 on successful configuration, 0 if main service not found or invalid port
*
* This function:
* 1. Looks up the main FTP proxy service using the configuration proxy name
* 2. Validates the remote port from the new proxy response
* 3. Updates the main service's remote data port if validation succeeds
*/
static int handle_ftp_configuration(struct proxy_service *ps, struct new_proxy_response *npr)
{
struct proxy_service *main_ps = get_proxy_service(ps->ftp_cfg_proxy_name);
if (!main_ps) {
debug(LOG_ERR, "Main FTP proxy service '%s' not found", ps->ftp_cfg_proxy_name);
return 0;
}
debug(LOG_DEBUG, "Found main FTP proxy service '%s'", main_ps->proxy_name);
if (npr->remote_port <= 0) {
debug(LOG_ERR, "Invalid FTP remote data port: %d", npr->remote_port);
return 0;
}
main_ps->remote_data_port = npr->remote_port;
return 1;
}
/**
* @brief Processes the raw response for a proxy service
*
* @param npr Pointer to the new proxy response structure
* @return int Returns status code:
* 0 on success
* negative value on failure
*/
static int proxy_service_resp_raw(struct new_proxy_response *npr)
{
// Validate input parameter
if (!npr) {
debug(LOG_ERR, "Invalid new proxy response parameter");
return 1;
}
// Check for error response
if (npr->error && strlen(npr->error) > 2) {
debug(LOG_ERR, "New proxy response error: %s", npr->error);
return 1;
}
// Validate proxy name
if (!npr->proxy_name || strlen(npr->proxy_name) == 0) {
debug(LOG_ERR, "Invalid or empty proxy name in response");
return 1;
}
// Get proxy service
struct proxy_service *ps = get_proxy_service(npr->proxy_name);
if (!ps) {
debug(LOG_ERR, "Proxy service '%s' not found", npr->proxy_name);
return 1;
}
if (!ps->proxy_type) {
debug(LOG_ERR, "Proxy type is NULL for service '%s'", npr->proxy_name);
return 1;
}
// Handle FTP configuration if present
if (ps->ftp_cfg_proxy_name) {
if (!handle_ftp_configuration(ps, npr)) {
return 1;
}
}
return 0;
}
/**
* @brief Handles encrypted message and decrypts it
*
* @param enc_msg Pointer to the encrypted message buffer
* @param ilen Length of the input encrypted message
* @param out Double pointer to store the decrypted output message
*
* @return int Returns status code indicating success or failure of decryption
*/
static int handle_enc_msg(const uint8_t *enc_msg, int ilen, uint8_t **out)
{
// Validate input parameters
if (!enc_msg || !out || ilen <= 0) {
debug(LOG_ERR, "Invalid input parameters: msg=%p, out=%p, length=%d",
enc_msg, out, ilen);
return -1;
}
// Initialize decoder if needed
const uint8_t *buf = enc_msg;
int remaining_len = ilen;
if (!is_decoder_inited()) {
int block_size = get_block_size();
if (remaining_len < block_size) {
debug(LOG_ERR, "Insufficient data for decoder initialization: need %d, got %d",
block_size, remaining_len);
return -1;
}
if (!init_main_decoder(buf)) {
debug(LOG_ERR, "Failed to initialize decoder");
return -1;
}
buf += block_size;
remaining_len -= block_size;
// Check if we only received initialization vector
if (remaining_len == 0) {
debug(LOG_DEBUG, "Received only initialization vector data");
*out = NULL;
return 0;
}
}
// Decrypt the message
uint8_t *dec_msg = NULL;
size_t dec_len = decrypt_data(buf, remaining_len, get_main_decoder(), &dec_msg);
if (dec_len <= 0 || !dec_msg) {
debug(LOG_ERR, "Decryption failed");
return -1;
}
*out = dec_msg;
return dec_len;
}
/**
* @brief Handles the request for a work connection type
*
* This function processes requests related to work connection types in the xfrpc
* system. It is intended to be used as a callback for handling specific connection
* type requests.
*
* @param ctx Pointer to the context data for the work connection request
*
* @note This function is static and only accessible within the current compilation unit
*/
static void handle_type_req_work_conn(void *ctx)
{
if (!is_xfrpc_connected()) {
start_proxy_services();
set_xfrpc_status(true);
}
new_client_connect();
}
/**
* @brief Handles the response message for a new proxy setup
*
* This function processes the response received after requesting a new proxy setup.
* It interprets the message header containing proxy setup response information.
*
* @param msg Pointer to the message header structure containing response data
*
* @note This function is for internal use within the control module
*/
static void handle_type_new_proxy_resp(struct msg_hdr *msg)
{
struct new_proxy_response *npr = new_proxy_resp_unmarshal((const char *)msg->data);
if (!npr) {
debug(LOG_ERR, "Failed to unmarshal new proxy response");
return;
}
proxy_service_resp_raw(npr);
SAFE_FREE(npr);
}
/**
* @brief Handles the start work connection message type
*
* @param msg Pointer to the message header structure
* @param len Length of the message
* @param ctx Pointer to context data
*
* This function processes messages of type 'start work connection'
* received from the frp server.
*/
static void handle_type_start_work_conn(struct msg_hdr *msg, int len, void *ctx)
{
struct start_work_conn_resp *sr = start_work_conn_resp_unmarshal((const char *)msg->data);
if (!sr) {
debug(LOG_ERR, "Failed to unmarshal TypeStartWorkConn");
return;
}
struct proxy_service *ps = get_proxy_service(sr->proxy_name);
if (!ps) {
debug(LOG_ERR, "Proxy service [%s] not found for TypeStartWorkConn", sr->proxy_name);
SAFE_FREE(sr);
return;
}
assert(ctx);
struct proxy_client *client = (struct proxy_client *)ctx;
client->ps = ps;
int remaining_len = len - sizeof(struct msg_hdr) - msg_hton(msg->length);
debug(LOG_DEBUG, "Proxy service [%s] [%s:%d] starting work connection. Remaining data length %d",
sr->proxy_name, ps->local_ip, ps->local_port, remaining_len);
if (remaining_len > 0) {
client->data_tail_size = remaining_len;
client->data_tail = msg->data + msg_hton(msg->length);
debug(LOG_DEBUG, "Data tail is %s", client->data_tail);
}
start_xfrp_tunnel(client);
set_client_work_start(client, 1);
SAFE_FREE(sr);
}
/**
* @brief Handles UDP packet types in message processing
*
* @param msg Pointer to the message header structure containing packet information
* @param ctx Pointer to context data needed for packet processing
*
* This function processes UDP type packets received in the message header.
* It performs the necessary handling and routing of UDP packets based on
* the message contents and context provided.
*/
static void handle_type_udp_packet(struct msg_hdr *msg, void *ctx)
{
struct udp_packet *udp = udp_packet_unmarshal((const char *)msg->data);
if (!udp) {
debug(LOG_ERR, "Failed to unmarshal TypeUDPPacket");
return;
}
debug(LOG_DEBUG, "Received UDP packet from server, content: %s", udp->content);
assert(ctx);
struct proxy_client *client = (struct proxy_client *)ctx;
assert(client->ps);
handle_udp_packet(udp, client);
SAFE_FREE(udp);
}
/**
* @brief Handles the control work based on received buffer data
*
* Processes control messages received in the buffer and performs
* corresponding control operations based on the message content.
*
* @param buf Pointer to the received data buffer
* @param len Length of the received data in bytes
* @param ctx Context pointer for additional data
*/
static void handle_control_work(const uint8_t *buf, int len, void *ctx)
{
uint8_t *frps_cmd = NULL;
if (!ctx) {
if (handle_enc_msg(buf, len, &frps_cmd) <= 0 || !frps_cmd) {
return;
}
} else {
frps_cmd = (uint8_t *)buf;
}
struct msg_hdr *msg = (struct msg_hdr *)frps_cmd;
uint8_t cmd_type = msg->type;
switch (cmd_type) {
case TypeReqWorkConn:
handle_type_req_work_conn(ctx);
break;
case TypeNewProxyResp:
handle_type_new_proxy_resp(msg);
break;
case TypeStartWorkConn:
handle_type_start_work_conn(msg, len, ctx);
break;
case TypeUDPPacket:
handle_type_udp_packet(msg, ctx);
break;
case TypePong:
pong_time = time(NULL);
break;
default:
debug(LOG_INFO, "Unsupported command type %d; ctx is %s", cmd_type, ctx ? "not NULL" : "NULL");
break;
}
if (!ctx)
free(frps_cmd);
}
static int validate_login_msg(const struct msg_hdr *mhdr) {
if (!mhdr || mhdr->type != TypeLoginResp) {
debug(LOG_ERR, "Invalid message type: expected %d, got %d",
TypeLoginResp, mhdr ? mhdr->type : -1);
return 0;
}
return 1;
}
/**
* Processes the login response message from the server
*
* @param mhdr Pointer to the message header structure containing login response
* @return Returns status code: 0 on success, negative value on failure
*/
static int process_login_response(const struct msg_hdr *mhdr) {
struct login_resp *lres = login_resp_unmarshal((const char *)mhdr->data);
if (!lres) {
debug(LOG_ERR, "Failed to unmarshal login response");
return 0;