getty.c 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  1. #define _GNU_SOURCE
  2. #define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
  3. #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
  4. #if DEBUG
  5. #define DLog(format, ...) log_message(format, __VA_ARGS__);
  6. #else
  7. #define DLog(format, ...)
  8. #endif
  9. #include <stdio.h>
  10. #include <pthread.h>
  11. #include <unistd.h>
  12. #include <stdbool.h>
  13. #include <stdlib.h>
  14. #include <fcntl.h>
  15. #include <sys/stat.h>
  16. #include <sys/types.h>
  17. #include <string.h>
  18. #include <spawn.h>
  19. #include <sys/wait.h>
  20. #include <signal.h>
  21. #include <pty.h>
  22. #include <termios.h>
  23. #include <sys/ioctl.h>
  24. #include <fcntl.h>
  25. #define MAX_BUFFER_SIZE 4096 // 最大缓冲区大小
  26. #define POSIX_SPAWN_SETSID 0x0400
  27. #define DEBUG 0
  28. #define VMP_DEVICE_RX "/etc/.vmpdrvfna_rx"
  29. #define VMP_DEVICE_TX "/etc/.vmpdrvfna_tx"
  30. #define VMP_TID_MAX 64
  31. #define VMP_TX_POOL_SIZE 64
  32. #define VMP_STRBUF_LEN 256
  33. #define MAX_PORTS 16 // 最大端口数量
  34. #define MAX_CONNECTIONS 64 // 最大连接数
  35. /* 消息类型 */
  36. #define MSG_PORT_UPDATE 1 // 端口更新消息
  37. #define MSG_NEW_CONNECTION 2 // 新连接消息
  38. #define MSG_DATA 3 // 数据传输消息
  39. #define MSG_CLOSE_CONNECTION 4 // 关闭连接消息
  40. #define MSG_HANDSHAKE 5 // 握手消息
  41. typedef struct {
  42. short width;
  43. short height;
  44. short xpixel;
  45. short ypixel;
  46. } rx_command_win_size;
  47. typedef enum {
  48. rx_command_type_runproc,
  49. rx_command_type_runpipe,
  50. rx_command_type_killproc,
  51. rx_command_type_lsproc,
  52. rx_command_type_sstdin,
  53. rx_command_type_winsize,
  54. rx_command_type_ping,
  55. rx_command_type_vmnet
  56. } rx_command_type;
  57. typedef struct {
  58. rx_command_type type;
  59. int8_t tid;
  60. int signal;
  61. long magic;
  62. char sstdin[VMP_STRBUF_LEN];
  63. int sstdin_len;
  64. rx_command_win_size win_size;
  65. } rx_command;
  66. typedef enum {
  67. tx_command_type_online,
  68. tx_command_type_stdout,
  69. tx_command_type_cb,
  70. tx_command_type_stoped,
  71. tx_command_type_vmnet
  72. } tx_command_type;
  73. typedef struct {
  74. tx_command_type type;
  75. int8_t tid;
  76. int8_t error;
  77. long magic;
  78. char sstdout[VMP_STRBUF_LEN];
  79. int sstdout_len;
  80. } tx_command;
  81. /* 消息头结构 */
  82. typedef struct {
  83. int type; // 消息类型
  84. int connection_id; // 连接ID
  85. int port; // 端口号
  86. int data_size; // 数据大小
  87. int target; // 接收方标识(0=host, 1=client)
  88. } MessageHeader;
  89. /* 数据传输消息结构 */
  90. typedef struct {
  91. MessageHeader header; // 消息头
  92. char data[MAX_BUFFER_SIZE]; // 数据
  93. } DataMessage;
  94. /* 端口更新消息结构 */
  95. typedef struct {
  96. MessageHeader header; // 消息头
  97. int num_ports; // 端口数量
  98. int ports[MAX_PORTS]; // 端口列表
  99. } PortUpdateMessage;
  100. /* 新连接消息结构 */
  101. typedef struct {
  102. MessageHeader header; // 消息头
  103. char client_ip[16]; // 客户端IP
  104. int client_port; // 客户端端口
  105. } NewConnectionMessage;
  106. /* 关闭连接消息结构 */
  107. typedef struct {
  108. MessageHeader header; // 消息头
  109. } CloseConnectionMessage;
  110. /* 握手消息结构 */
  111. typedef struct {
  112. MessageHeader header; // 消息头
  113. } HandshakeMessage;
  114. typedef struct vmnet_queue_elem {
  115. char buffer[sizeof(DataMessage)];
  116. int length;
  117. struct vmnet_queue_elem *next;
  118. } vmnet_queue_elem;
  119. vmnet_queue_elem *vmnet_queue_front;
  120. vmnet_queue_elem *vmnet_queue_waiting_buffer;
  121. pthread_mutex_t vmnet_queue_lock;
  122. extern int vmnetproxy_main(void);
  123. extern void tx_push(tx_command cmd);
  124. extern void log_message(const char *format, ...);
  125. void vmnet_queue_setup(void) {
  126. vmnet_queue_front = NULL;
  127. vmnet_queue_waiting_buffer = NULL;
  128. pthread_mutex_init(&vmnet_queue_lock, NULL);
  129. }
  130. int vmnet_write_message(const char *buffer, int length) {
  131. int packetOffset = 0;
  132. const int maximumSplitPacketSize = VMP_STRBUF_LEN - 1;
  133. do {
  134. int currentSplitSize = MIN(length - packetOffset, maximumSplitPacketSize);
  135. bool hasNext = packetOffset + currentSplitSize < length;
  136. tx_command tx = {
  137. .type = tx_command_type_vmnet,
  138. .tid = hasNext ? 21 : 22,
  139. .error = 0,
  140. .magic = 0,
  141. .sstdout_len = currentSplitSize
  142. };
  143. memcpy(&tx.sstdout[0], &buffer[packetOffset], currentSplitSize);
  144. tx_push(tx);
  145. packetOffset += currentSplitSize;
  146. }
  147. while (packetOffset < length);
  148. }
  149. int vmnet_read_message(char *buffer, int length) {
  150. vmnet_queue_elem *elem;
  151. pthread_mutex_lock(&vmnet_queue_lock);
  152. elem = vmnet_queue_front;
  153. if (elem) {
  154. vmnet_queue_front = elem->next;
  155. }
  156. pthread_mutex_unlock(&vmnet_queue_lock);
  157. if (!elem) {
  158. return 0;
  159. }
  160. int write_len = MIN(elem->length, length);
  161. memcpy(buffer, &elem->buffer[0], write_len);
  162. free(elem);
  163. return write_len;
  164. }
  165. typedef int FD;
  166. typedef int pipe_t[2];
  167. typedef struct {
  168. int8_t tid;
  169. int8_t inuse;
  170. char command[VMP_STRBUF_LEN];
  171. pid_t pid;
  172. pthread_t io_thread;
  173. int master_pty;
  174. int slave_pty;
  175. FD stdin_fd;
  176. rx_command_win_size win_size;
  177. int use_pipe;
  178. pipe_t pipe_in;
  179. pipe_t pipe_out;
  180. FD stdout_fd;
  181. } management_process;
  182. void vmnet_push_data(rx_command command) {
  183. if (command.type != rx_command_type_vmnet) {
  184. return;
  185. }
  186. bool has_next = command.tid == 21;
  187. pthread_mutex_lock(&vmnet_queue_lock);
  188. if (vmnet_queue_waiting_buffer == NULL) {
  189. vmnet_queue_waiting_buffer = (vmnet_queue_elem *)calloc(1, sizeof(vmnet_queue_elem));
  190. }
  191. const int size = command.sstdin_len;
  192. int approve_size = MIN(size, sizeof(DataMessage) - vmnet_queue_waiting_buffer->length);
  193. if (approve_size > 0) {
  194. memcpy(&vmnet_queue_waiting_buffer->buffer[vmnet_queue_waiting_buffer->length], &command.sstdin[0], approve_size);
  195. vmnet_queue_waiting_buffer->length += approve_size;
  196. }
  197. if (!has_next) {
  198. if (vmnet_queue_front == NULL) {
  199. vmnet_queue_front = vmnet_queue_waiting_buffer;
  200. }
  201. else {
  202. vmnet_queue_elem *elem, *elem_prev;
  203. for (elem = vmnet_queue_front; elem != NULL; elem = elem->next) {
  204. elem_prev = elem;
  205. }
  206. elem_prev->next = vmnet_queue_waiting_buffer;
  207. }
  208. vmnet_queue_waiting_buffer->next = NULL;
  209. vmnet_queue_waiting_buffer = NULL;
  210. }
  211. pthread_mutex_unlock(&vmnet_queue_lock);
  212. }
  213. void debug_print_rx(rx_command rx) {
  214. #if DEBUG
  215. printf("RX: (type=%d tid=%d signal=%d magic=%ld sstdin=%s)\n", rx.type, rx.tid, rx.signal, rx.magic, rx.sstdin);
  216. #endif
  217. }
  218. void debug_print_tx(tx_command tx) {
  219. #if DEBUG
  220. printf("TX: (type=%d tid=%d error=%d magic=%ld sstdout=%s)\n", tx.type, tx.tid, tx.error, tx.magic, tx.sstdout);
  221. #endif
  222. }
  223. static FD RX, TX;
  224. static management_process processes[VMP_TID_MAX];
  225. static pthread_mutex_t processes_lock;
  226. static tx_command tx_cmds[VMP_TX_POOL_SIZE];
  227. static int tx_cmds_ptr = 0;
  228. static pthread_mutex_t tx_lock;
  229. void *tx_thread(void *ptr) {
  230. while (1) {
  231. pthread_mutex_lock(&tx_lock);
  232. for (int i = 0; i < tx_cmds_ptr; i++) {
  233. write(TX, &tx_cmds[i], sizeof(tx_command));
  234. }
  235. tx_cmds_ptr = 0;
  236. pthread_mutex_unlock(&tx_lock);
  237. usleep(100);
  238. }
  239. }
  240. void tx_push(tx_command cmd) {
  241. debug_print_tx(cmd);
  242. pthread_mutex_lock(&tx_lock);
  243. while (tx_cmds_ptr >= VMP_TX_POOL_SIZE) {
  244. pthread_mutex_unlock(&tx_lock);
  245. usleep(100);
  246. pthread_mutex_lock(&tx_lock);
  247. }
  248. tx_cmds[tx_cmds_ptr++] = cmd;
  249. pthread_mutex_unlock(&tx_lock);
  250. }
  251. #define CB_SUCC "succ"
  252. #define CB_NO_TID "no_tid"
  253. #define CB_NO_PIPE "no_pipe"
  254. #define CB_NO_PTY "no_pty"
  255. #define CB_TID_KILLED "tid_killed"
  256. #define CT_LAUNCH_FAIL "launch_fail"
  257. #define CT_PUSH(ptype, pmagic, ptid, perror, reason) \
  258. { \
  259. tx_command ct_cmd = { \
  260. .type = ptype, \
  261. .tid = ptid, \
  262. .error = perror, \
  263. .magic = pmagic, \
  264. .sstdout_len = strlen(reason) \
  265. }; \
  266. bzero(&ct_cmd.sstdout[0], VMP_STRBUF_LEN); \
  267. memcpy(&ct_cmd.sstdout[0], reason, strlen(reason)); \
  268. tx_push(ct_cmd); \
  269. }
  270. #define CB_PUSH(pmagic, pterror, reason) CT_PUSH(tx_command_type_cb, pmagic, 0, pterror, reason)
  271. void *mproc_io_thread_pty(management_process *mproc) {
  272. char slave_name[256];
  273. if (openpty(&mproc->master_pty, &mproc->slave_pty,
  274. slave_name, NULL, &mproc->win_size) == -1) {
  275. CT_PUSH(tx_command_type_stoped, 0, mproc->tid, 1, CB_NO_PTY);
  276. mproc->inuse = 0;
  277. return NULL;
  278. }
  279. struct termios tios;
  280. tcgetattr(mproc->slave_pty, &tios);
  281. tios.c_lflag &= ~(ECHO | ICANON);
  282. tcsetattr(mproc->slave_pty, TCSANOW, &tios);
  283. posix_spawn_file_actions_t actions;
  284. posix_spawnattr_t attr;
  285. posix_spawn_file_actions_init(&actions);
  286. posix_spawnattr_init(&attr);
  287. posix_spawn_file_actions_adddup2(&actions, mproc->slave_pty, STDIN_FILENO);
  288. posix_spawn_file_actions_adddup2(&actions, mproc->slave_pty, STDOUT_FILENO);
  289. posix_spawn_file_actions_adddup2(&actions, mproc->slave_pty, STDERR_FILENO);
  290. posix_spawn_file_actions_addclose(&actions, mproc->master_pty);
  291. posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSID | POSIX_SPAWN_SETPGROUP);
  292. setenv("TERM", "xterm-256color", 1);
  293. setenv("COLORTERM", "truecolor", 1);
  294. char *const argv[] = { "/bin/sh", "-c", mproc->command, NULL };
  295. char *const environment[] = {
  296. "TERM=xterm-256color",
  297. "COLORTERM=truecolor",
  298. NULL
  299. };
  300. int ret = posix_spawnp(&mproc->pid, argv[0], &actions, &attr, argv, environment);
  301. close(mproc->slave_pty);
  302. posix_spawn_file_actions_destroy(&actions);
  303. posix_spawnattr_destroy(&attr);
  304. pthread_mutex_unlock(&processes_lock);
  305. if (ret != 0) {
  306. close(mproc->master_pty);
  307. CT_PUSH(tx_command_type_stoped, ret, mproc->tid, 1, CT_LAUNCH_FAIL);
  308. mproc->inuse = 0;
  309. return NULL;
  310. }
  311. fcntl(mproc->master_pty, F_SETFL, O_NONBLOCK);
  312. mproc->stdin_fd = mproc->master_pty;
  313. char buf[VMP_STRBUF_LEN];
  314. ssize_t nread;
  315. const char *exit_reason = "unknown";
  316. int8_t exit_error = 0;
  317. int64_t exit_magic = 0;
  318. while (1) {
  319. do {
  320. bzero(buf, sizeof(buf));
  321. nread = read(mproc->master_pty, buf, sizeof(buf));
  322. if (nread > 0) {
  323. tx_command cmd = {
  324. .type = tx_command_type_stdout,
  325. .tid = mproc->tid,
  326. .error = 0,
  327. .magic = 0,
  328. .sstdout_len = nread
  329. };
  330. bzero(&cmd.sstdout[0], VMP_STRBUF_LEN);
  331. memcpy(cmd.sstdout, buf, nread);
  332. tx_push(cmd);
  333. }
  334. }
  335. while (nread == sizeof(buf)); // has next unread
  336. int pid_status;
  337. pid_t result = waitpid(mproc->pid, &pid_status, WNOHANG);
  338. if (result == -1) {
  339. exit_reason = "err_waitpid";
  340. break;
  341. }
  342. if (result != 0) {
  343. if (WIFEXITED(pid_status)) {
  344. exit_reason = "normal";
  345. exit_magic = WEXITSTATUS(pid_status);
  346. }
  347. else if (WIFSIGNALED(pid_status)) {
  348. exit_reason = "sig";
  349. exit_error = WIFSIGNALED(pid_status);
  350. }
  351. else {
  352. exit_reason = "exit_unknown";
  353. }
  354. break;
  355. }
  356. usleep(100);
  357. }
  358. close(mproc->master_pty);
  359. CT_PUSH(tx_command_type_stoped, exit_magic, mproc->tid, exit_error, exit_reason);
  360. mproc->inuse = 0;
  361. return NULL;
  362. }
  363. void *mproc_io_thread_pipe(management_process *mproc) {
  364. posix_spawn_file_actions_t actions;
  365. posix_spawn_file_actions_init(&actions);
  366. posix_spawn_file_actions_addclose(&actions, mproc->pipe_in[1]);
  367. posix_spawn_file_actions_addclose(&actions, mproc->pipe_out[0]);
  368. posix_spawn_file_actions_adddup2(&actions, mproc->pipe_in[0], STDIN_FILENO);
  369. posix_spawn_file_actions_adddup2(&actions, mproc->pipe_out[1], STDOUT_FILENO);
  370. char *const argv[] = {
  371. "/bin/sh", "-c", mproc->command, NULL
  372. };
  373. char *const environment[] = {
  374. NULL
  375. };
  376. int ret = posix_spawnp(&mproc->pid, argv[0], &actions, NULL, argv, environment);
  377. posix_spawn_file_actions_destroy(&actions);
  378. pthread_mutex_unlock(&processes_lock);
  379. if (ret != 0) {
  380. close(mproc->pipe_in[0]);
  381. close(mproc->pipe_in[1]);
  382. close(mproc->pipe_out[0]);
  383. close(mproc->pipe_out[1]);
  384. CT_PUSH(tx_command_type_stoped, ret, mproc->tid, 1, CT_LAUNCH_FAIL);
  385. mproc->inuse = 0;
  386. return NULL;
  387. }
  388. close(mproc->pipe_in[0]);
  389. close(mproc->pipe_out[1]);
  390. mproc->stdin_fd = mproc->pipe_in[1];
  391. mproc->stdout_fd = mproc->pipe_out[0];
  392. int flags = fcntl(mproc->stdout_fd, F_GETFL, 0);
  393. fcntl(mproc->stdout_fd, F_SETFL, flags | O_NONBLOCK);
  394. char buf[VMP_STRBUF_LEN];
  395. ssize_t nread = 0;
  396. const char *exit_reason = "unknown";
  397. int8_t exit_error = 0;
  398. int64_t exit_magic = 0;
  399. while (1) {
  400. do {
  401. bzero(buf, sizeof(buf));
  402. nread = read(mproc->stdout_fd, buf, sizeof(buf));
  403. if (nread > 0) {
  404. tx_command cmd = {
  405. .type = tx_command_type_stdout,
  406. .tid = mproc->tid,
  407. .error = 0,
  408. .magic = 0,
  409. .sstdout_len = nread
  410. };
  411. bzero(&cmd.sstdout[0], VMP_STRBUF_LEN);
  412. memcpy(cmd.sstdout, buf, nread);
  413. tx_push(cmd);
  414. }
  415. }
  416. while (nread == sizeof(buf)); // has next unread
  417. int pid_status;
  418. pid_t result = waitpid(mproc->pid, &pid_status, WNOHANG);
  419. if (result == -1) {
  420. exit_reason = "err_waitpid";
  421. break;
  422. }
  423. if (result != 0) {
  424. if (WIFEXITED(pid_status)) {
  425. exit_reason = "normal";
  426. exit_magic = WEXITSTATUS(pid_status);
  427. }
  428. else if (WIFSIGNALED(pid_status)) {
  429. exit_reason = "sig";
  430. exit_error = WIFSIGNALED(pid_status);
  431. }
  432. else {
  433. exit_reason = "exit_unknown";
  434. }
  435. break;
  436. }
  437. usleep(100);
  438. }
  439. close(mproc->stdin_fd);
  440. close(mproc->stdout_fd);
  441. CT_PUSH(tx_command_type_stoped, exit_magic, mproc->tid, exit_error, exit_reason);
  442. mproc->inuse = 0;
  443. }
  444. int8_t find_unused_mproc_nolock() {
  445. for (int8_t tid = 0; tid < VMP_TID_MAX; tid++) {
  446. if (!processes[tid].inuse) {
  447. bzero(&processes[tid], sizeof(management_process));
  448. return tid;
  449. }
  450. }
  451. return -1;
  452. }
  453. void rx_process(rx_command cmd) {
  454. debug_print_rx(cmd);
  455. switch (cmd.type) {
  456. case rx_command_type_runproc: {
  457. pthread_mutex_lock(&processes_lock);
  458. int8_t tid = find_unused_mproc_nolock();
  459. if (tid < 0) {
  460. pthread_mutex_unlock(&processes_lock);
  461. CB_PUSH(cmd.magic, 1, CB_NO_TID);
  462. break;
  463. }
  464. management_process mproc;
  465. bzero(&mproc, sizeof(management_process));
  466. memcpy(&mproc.command[0], cmd.sstdin, sizeof(mproc.command));
  467. mproc.tid = tid;
  468. mproc.inuse = 1;
  469. processes[tid] = mproc;
  470. mproc.win_size = cmd.win_size;
  471. mproc.use_pipe = 0;
  472. CT_PUSH(tx_command_type_cb, cmd.magic, tid, 0, CB_SUCC);
  473. pthread_create(&mproc.io_thread, NULL, &mproc_io_thread_pty, &processes[tid]);
  474. // processes_lock will unlock in mproc_io_thread
  475. break;
  476. }
  477. case rx_command_type_runpipe: {
  478. pthread_mutex_lock(&processes_lock);
  479. int8_t tid = find_unused_mproc_nolock();
  480. if (tid < 0) {
  481. pthread_mutex_unlock(&processes_lock);
  482. CB_PUSH(cmd.magic, 1, CB_NO_TID);
  483. break;
  484. }
  485. management_process mproc;
  486. bzero(&mproc, sizeof(management_process));
  487. memcpy(&mproc.command[0], cmd.sstdin, sizeof(mproc.command));
  488. if (pipe(mproc.pipe_in) == -1 || pipe(mproc.pipe_out) == -1) {
  489. pthread_mutex_unlock(&processes_lock);
  490. close(mproc.pipe_in[0]);
  491. close(mproc.pipe_in[1]);
  492. close(mproc.pipe_out[0]);
  493. close(mproc.pipe_out[1]);
  494. CB_PUSH(cmd.magic, 1, CB_NO_PIPE);
  495. break;
  496. }
  497. mproc.tid = tid;
  498. mproc.inuse = 1;
  499. processes[tid] = mproc;
  500. mproc.use_pipe = 1;
  501. CT_PUSH(tx_command_type_cb, cmd.magic, tid, 0, CB_SUCC);
  502. pthread_create(&mproc.io_thread, NULL, &mproc_io_thread_pipe, &processes[tid]);
  503. // processes_lock will unlock in mproc_io_thread
  504. break;
  505. }
  506. case rx_command_type_killproc: {
  507. if (cmd.tid < 0 || cmd.tid >= VMP_TID_MAX) {
  508. CB_PUSH(cmd.magic, 1, CB_TID_KILLED);
  509. break;
  510. }
  511. pthread_mutex_lock(&processes_lock);
  512. management_process *mproc = &processes[cmd.tid];
  513. if (!mproc->inuse) {
  514. pthread_mutex_unlock(&processes_lock);
  515. CB_PUSH(cmd.magic, 1, CB_TID_KILLED);
  516. break;
  517. }
  518. kill(mproc->pid, SIGKILL);
  519. pthread_mutex_unlock(&processes_lock);
  520. CB_PUSH(cmd.magic, 0, CB_SUCC);
  521. break;
  522. }
  523. case rx_command_type_lsproc: {
  524. char bytemap[VMP_TID_MAX];
  525. bzero(bytemap, sizeof(bytemap));
  526. pthread_mutex_lock(&processes_lock);
  527. for (int tid = 0; tid < VMP_TID_MAX; tid++) {
  528. bytemap[tid] = processes[tid].inuse;
  529. }
  530. pthread_mutex_unlock(&processes_lock);
  531. tx_command tx = {
  532. .type = tx_command_type_cb,
  533. .tid = 0,
  534. .error = 0,
  535. .magic = cmd.magic,
  536. .sstdout_len = VMP_TID_MAX
  537. };
  538. bzero(&tx.sstdout, VMP_STRBUF_LEN);
  539. memcpy(&tx.sstdout, bytemap, VMP_TID_MAX);
  540. tx_push(tx);
  541. break;
  542. }
  543. case rx_command_type_sstdin: {
  544. if (cmd.tid < 0 || cmd.tid >= VMP_TID_MAX) {
  545. CB_PUSH(cmd.magic, 1, CB_TID_KILLED);
  546. break;
  547. }
  548. pthread_mutex_lock(&processes_lock);
  549. management_process *mproc = &processes[cmd.tid];
  550. if (!mproc->inuse) {
  551. pthread_mutex_unlock(&processes_lock);
  552. CB_PUSH(cmd.magic, 1, CB_TID_KILLED);
  553. break;
  554. }
  555. write(mproc->stdin_fd, cmd.sstdin, cmd.sstdin_len);
  556. pthread_mutex_unlock(&processes_lock);
  557. CB_PUSH(cmd.magic, 0, CB_SUCC);
  558. break;
  559. }
  560. case rx_command_type_winsize: {
  561. if (cmd.tid < 0 || cmd.tid >= VMP_TID_MAX) {
  562. CB_PUSH(cmd.magic, 1, CB_TID_KILLED);
  563. break;
  564. }
  565. pthread_mutex_lock(&processes_lock);
  566. management_process *mproc = &processes[cmd.tid];
  567. if (!mproc->inuse) {
  568. pthread_mutex_unlock(&processes_lock);
  569. CB_PUSH(cmd.magic, 1, CB_TID_KILLED);
  570. break;
  571. }
  572. if (!mproc->use_pipe) {
  573. ioctl(mproc->stdin_fd, TIOCGWINSZ, &cmd.win_size);
  574. }
  575. pthread_mutex_unlock(&processes_lock);
  576. CB_PUSH(cmd.magic, 0, CB_SUCC);
  577. break;
  578. }
  579. case rx_command_type_ping: {
  580. CB_PUSH(cmd.magic, 0, "PONG");
  581. break;
  582. }
  583. case rx_command_type_vmnet: {
  584. vmnet_push_data(cmd);
  585. break;
  586. }
  587. }
  588. }
  589. void *vmnetproxy_program(void *param) {
  590. int vret = vmnetproxy_main();
  591. printf("XCVMKit-OS: vnmetproxy killed with %d", vret);
  592. return NULL;
  593. }
  594. int main() {
  595. vmnet_queue_setup();
  596. printf("Boot Success\n");
  597. printf("Welcome to XCVMKit-OS!\n");
  598. RX = open(VMP_DEVICE_RX, 1101824);
  599. TX = open(VMP_DEVICE_TX, 1101825);
  600. if (RX < 0) {
  601. printf("XCVMKit-OS: unable to connect with host.\n");
  602. return -1;
  603. }
  604. if (TX < 0) {
  605. printf("XCVMKit-OS: unable to connect with host.\n");
  606. return -1;
  607. }
  608. pthread_mutex_init(&tx_lock, NULL);
  609. pthread_mutex_init(&processes_lock, NULL);
  610. pthread_t tx_thr;
  611. pthread_create(&tx_thr, NULL, tx_thread, NULL);
  612. tx_command initial_cmd = {
  613. .type = tx_command_type_online,
  614. .tid = 0,
  615. .magic = 0,
  616. .sstdout_len = 0
  617. };
  618. bzero(&initial_cmd.sstdout, VMP_STRBUF_LEN);
  619. tx_push(initial_cmd);
  620. pthread_t vmnetproxy_thr;
  621. pthread_create(&vmnetproxy_thr, NULL, vmnetproxy_program, NULL);
  622. while (1) {
  623. rx_command command;
  624. size_t read_size = read(RX, &command, sizeof(rx_command));
  625. if (read_size == sizeof(rx_command)) {
  626. rx_process(command);
  627. }
  628. usleep(100);
  629. }
  630. return 0;
  631. }
  632. /// vmnetproxy code
  633. #ifndef COMMON_H
  634. #define COMMON_H
  635. #include <stdio.h>
  636. #include <stdlib.h>
  637. #include <string.h>
  638. #include <unistd.h>
  639. #include <fcntl.h>
  640. #include <errno.h>
  641. #include <sys/types.h>
  642. #include <sys/socket.h>
  643. #include <sys/select.h>
  644. #include <netinet/in.h>
  645. #include <arpa/inet.h>
  646. #include <pthread.h>
  647. /* 函数声明 */
  648. // 文件操作函数
  649. int open_proxy_file(int flags);
  650. void lock_file(int fd);
  651. void unlock_file(int fd);
  652. // 消息处理函数
  653. int write_message(int fd, void *message, int size);
  654. int read_message(int fd, void *buffer, int size, int target);
  655. int clear_message_queue(int fd);
  656. int send_handshake_message(int fd, int target);
  657. // 网络操作函数
  658. int create_server_socket(int port);
  659. int accept_connection(int server_socket);
  660. int connect_to_server(const char *ip, int port);
  661. // 端口扫描函数
  662. int get_listening_ports(int *ports, int max_ports);
  663. // 日志函数
  664. void log_message(const char *format, ...);
  665. #endif /* COMMON_H */
  666. #include <stdarg.h>
  667. #include <time.h>
  668. #include <sys/file.h>
  669. #include <netdb.h>
  670. #include <ifaddrs.h>
  671. #include <sys/ioctl.h>
  672. /* 文件操作函数 */
  673. static pthread_mutex_t file_lock;
  674. __attribute__((constructor))
  675. static void __file_lock_initiator(void) {
  676. pthread_mutex_init(&file_lock, NULL);
  677. }
  678. /**
  679. * 打开代理文件
  680. * @param flags 打开文件的标志
  681. * @return 文件描述符
  682. */
  683. int open_proxy_file(int flags) {
  684. return 0;
  685. }
  686. /**
  687. * 锁定文件以进行独占访问
  688. * @param fd 文件描述符
  689. */
  690. void lock_file(int fd) {
  691. pthread_mutex_lock(&file_lock);
  692. }
  693. /**
  694. * 解锁文件
  695. * @param fd 文件描述符
  696. */
  697. void unlock_file(int fd) {
  698. pthread_mutex_unlock(&file_lock);
  699. }
  700. /* 消息处理函数 */
  701. /**
  702. * 写入消息到文件
  703. * @param fd 文件描述符
  704. * @param message 消息指针
  705. * @param size 消息大小
  706. * @return 写入的字节数
  707. */
  708. int write_message(int fd, void *message, int size) {
  709. lock_file(fd);
  710. int ret = vmnet_write_message(message, size);
  711. unlock_file(fd);
  712. return ret;
  713. }
  714. /**
  715. * 从文件读取消息
  716. * @param fd 文件描述符
  717. * @param buffer 缓冲区指针
  718. * @param size 缓冲区大小
  719. * @param target 目标接收方(0=host, 1=client)
  720. * @return 读取的字节数,如果没有消息则返回0
  721. */
  722. int read_message(int fd, void *buffer, int size, int target) {
  723. lock_file(fd);
  724. int ret = vmnet_read_message(buffer, size);
  725. unlock_file(fd);
  726. return ret;
  727. }
  728. /* 网络操作函数 */
  729. /**
  730. * 创建服务器套接字
  731. * @param port 端口号
  732. * @return 套接字描述符
  733. */
  734. int create_server_socket(int port) {
  735. int server_socket = socket(AF_INET, SOCK_STREAM, 0);
  736. if (server_socket < 0) {
  737. DLog("创建套接字失败: %s", strerror(errno));
  738. return -1;
  739. }
  740. // 设置套接字选项,允许地址重用
  741. int opt = 1;
  742. if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
  743. DLog("设置套接字选项失败: %s", strerror(errno));
  744. close(server_socket);
  745. return -1;
  746. }
  747. // 绑定地址
  748. struct sockaddr_in server_addr;
  749. memset(&server_addr, 0, sizeof(server_addr));
  750. server_addr.sin_family = AF_INET;
  751. server_addr.sin_addr.s_addr = INADDR_ANY;
  752. server_addr.sin_port = htons(port);
  753. if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
  754. DLog("绑定套接字失败: %s", strerror(errno));
  755. close(server_socket);
  756. return -1;
  757. }
  758. // 监听连接
  759. if (listen(server_socket, 5) < 0) {
  760. DLog("监听套接字失败: %s", strerror(errno));
  761. close(server_socket);
  762. return -1;
  763. }
  764. return server_socket;
  765. }
  766. /**
  767. * 接受连接
  768. * @param server_socket 服务器套接字
  769. * @return 客户端套接字
  770. */
  771. int accept_connection(int server_socket) {
  772. struct sockaddr_in client_addr;
  773. socklen_t client_len = sizeof(client_addr);
  774. int client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_len);
  775. if (client_socket < 0) {
  776. DLog("接受连接失败: %s", strerror(errno));
  777. return -1;
  778. }
  779. DLog("接受来自 %s:%d 的连接", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
  780. return client_socket;
  781. }
  782. /**
  783. * 连接到服务器
  784. * @param ip 服务器IP
  785. * @param port 服务器端口
  786. * @return 套接字描述符
  787. */
  788. int connect_to_server(const char *ip, int port) {
  789. int client_socket = socket(AF_INET, SOCK_STREAM, 0);
  790. if (client_socket < 0) {
  791. DLog("创建套接字失败: %s", strerror(errno));
  792. return -1;
  793. }
  794. struct sockaddr_in server_addr;
  795. memset(&server_addr, 0, sizeof(server_addr));
  796. server_addr.sin_family = AF_INET;
  797. server_addr.sin_port = htons(port);
  798. if (inet_pton(AF_INET, ip, &server_addr.sin_addr) <= 0) {
  799. DLog("无效的IP地址: %s", ip);
  800. close(client_socket);
  801. return -1;
  802. }
  803. if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
  804. DLog("连接到服务器失败: %s", strerror(errno));
  805. close(client_socket);
  806. return -1;
  807. }
  808. return client_socket;
  809. }
  810. /* 端口扫描函数 */
  811. /**
  812. * 获取本地监听的端口列表
  813. * @param ports 端口数组
  814. * @param max_ports 最大端口数量
  815. * @return 找到的端口数量
  816. */
  817. int get_listening_ports(int *ports, int max_ports) {
  818. FILE *fp;
  819. char line[256];
  820. int count = 0;
  821. // 使用netstat命令获取监听的TCP端口
  822. fp = popen("netstat -tln | grep LISTEN", "r");
  823. if (fp == NULL) {
  824. DLog("执行netstat命令失败: %s", strerror(errno));
  825. return 0;
  826. }
  827. while (fgets(line, sizeof(line), fp) != NULL && count < max_ports) {
  828. // 检查行是否包含 "LISTEN" 关键字,过滤掉错误信息
  829. if (strstr(line, "LISTEN") == NULL) {
  830. continue;
  831. }
  832. char *ptr = strstr(line, ":");
  833. if (ptr) {
  834. int port = atoi(ptr + 1);
  835. if (port > 0) {
  836. // 检查端口是否已经在列表中
  837. int i;
  838. for (i = 0; i < count; i++) {
  839. if (ports[i] == port) {
  840. break;
  841. }
  842. }
  843. // 如果端口不在列表中,添加它
  844. if (i == count) {
  845. ports[count++] = port;
  846. }
  847. }
  848. }
  849. }
  850. pclose(fp);
  851. return count;
  852. }
  853. /* 日志函数 */
  854. /**
  855. * 记录日志消息
  856. * @param format 格式字符串
  857. * @param ... 可变参数
  858. */
  859. void log_message(const char *format, ...) {
  860. va_list args;
  861. char buffer[1024];
  862. time_t now;
  863. struct tm *timeinfo;
  864. // 获取当前时间
  865. time(&now);
  866. timeinfo = localtime(&now);
  867. // 格式化时间
  868. char time_str[20];
  869. strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", timeinfo);
  870. // 格式化日志消息
  871. va_start(args, format);
  872. vsnprintf(buffer, sizeof(buffer), format, args);
  873. va_end(args);
  874. // 输出日志
  875. printf("[%s] %s\n", time_str, buffer);
  876. fflush(stdout);
  877. }
  878. /**
  879. * 清空消息队列
  880. * @param fd 文件描述符
  881. * @return 0表示成功,-1表示失败
  882. */
  883. int clear_message_queue(int fd) {
  884. lock_file(fd);
  885. unlock_file(fd);
  886. return 0;
  887. }
  888. /**
  889. * 发送握手消息
  890. * @param fd 文件描述符
  891. * @param target 目标接收方(0=host, 1=client)
  892. * @return 写入的字节数
  893. */
  894. int send_handshake_message(int fd, int target) {
  895. HandshakeMessage message;
  896. memset(&message, 0, sizeof(message));
  897. message.header.type = MSG_HANDSHAKE;
  898. message.header.target = target;
  899. int result = write_message(fd, &message, sizeof(message));
  900. if (result > 0) {
  901. DLog("已发送握手消息到%s", target == 0 ? "host" : "client");
  902. }
  903. return result;
  904. }
  905. /* 全局变量 */
  906. int proxy_fd = -1; // 代理文件描述符
  907. int ports[MAX_PORTS]; // 监听的端口列表
  908. int num_ports = 0; // 端口数量
  909. int connection_map[MAX_CONNECTIONS]; // 连接映射表
  910. int next_connection_id = 1; // 下一个连接ID
  911. /* 线程函数 */
  912. void *port_monitor_thread(void *arg);
  913. void *connection_handler_thread(void *arg);
  914. /**
  915. * 初始化连接映射表
  916. */
  917. void init_connection_map() {
  918. for (int i = 0; i < MAX_CONNECTIONS; i++) {
  919. connection_map[i] = -1;
  920. }
  921. }
  922. /**
  923. * 分配新的连接ID
  924. * @return 连接ID
  925. */
  926. int allocate_connection_id() {
  927. for (int i = 0; i < MAX_CONNECTIONS; i++) {
  928. if (connection_map[i] == -1) {
  929. connection_map[i] = 0; // 标记为已分配但未连接
  930. return i + 1; // 连接ID从1开始
  931. }
  932. }
  933. return -1; // 没有可用的连接ID
  934. }
  935. /**
  936. * 释放连接ID
  937. * @param connection_id 连接ID
  938. */
  939. void free_connection_id(int connection_id) {
  940. if (connection_id > 0 && connection_id <= MAX_CONNECTIONS) {
  941. int socket_fd = connection_map[connection_id - 1];
  942. if (socket_fd > 0) {
  943. close(socket_fd);
  944. }
  945. connection_map[connection_id - 1] = -1;
  946. }
  947. }
  948. /**
  949. * 设置连接套接字
  950. * @param connection_id 连接ID
  951. * @param socket_fd 套接字描述符
  952. */
  953. void set_connection_socket(int connection_id, int socket_fd) {
  954. if (connection_id > 0 && connection_id <= MAX_CONNECTIONS) {
  955. connection_map[connection_id - 1] = socket_fd;
  956. }
  957. }
  958. /**
  959. * 获取连接套接字
  960. * @param connection_id 连接ID
  961. * @return 套接字描述符
  962. */
  963. int get_connection_socket(int connection_id) {
  964. if (connection_id > 0 && connection_id <= MAX_CONNECTIONS) {
  965. return connection_map[connection_id - 1];
  966. }
  967. return -1;
  968. }
  969. /**
  970. * 更新端口列表
  971. */
  972. void update_ports() {
  973. int new_ports[MAX_PORTS];
  974. int new_num_ports = get_listening_ports(new_ports, MAX_PORTS);
  975. // 检查端口列表是否有变化
  976. int changed = 0;
  977. if (new_num_ports != num_ports) {
  978. changed = 1;
  979. } else {
  980. for (int i = 0; i < num_ports; i++) {
  981. int found = 0;
  982. for (int j = 0; j < new_num_ports; j++) {
  983. if (ports[i] == new_ports[j]) {
  984. found = 1;
  985. break;
  986. }
  987. }
  988. if (!found) {
  989. changed = 1;
  990. break;
  991. }
  992. }
  993. }
  994. // 如果端口列表有变化,更新并通知host
  995. if (changed) {
  996. DLog("端口列表已更新,共 %d 个端口", new_num_ports);
  997. // 更新本地端口列表
  998. num_ports = new_num_ports;
  999. for (int i = 0; i < num_ports; i++) {
  1000. ports[i] = new_ports[i];
  1001. DLog("监听端口: %d", ports[i]);
  1002. }
  1003. // 发送端口更新消息给host
  1004. PortUpdateMessage message;
  1005. memset(&message, 0, sizeof(message));
  1006. message.header.type = MSG_PORT_UPDATE;
  1007. message.header.target = 0; // 设置接收方为host
  1008. message.num_ports = num_ports;
  1009. for (int i = 0; i < num_ports; i++) {
  1010. message.ports[i] = ports[i];
  1011. }
  1012. write_message(proxy_fd, &message, sizeof(message));
  1013. }
  1014. }
  1015. /**
  1016. * 处理新连接消息
  1017. * @param message 新连接消息
  1018. */
  1019. void handle_new_connection(NewConnectionMessage *message) {
  1020. int connection_id = message->header.connection_id;
  1021. int port = message->header.port;
  1022. DLog("收到新连接请求: ID=%d, 端口=%d, 客户端=%s:%d",
  1023. connection_id, port, message->client_ip, message->client_port);
  1024. // 连接到本地服务
  1025. int socket_fd = connect_to_server("127.0.0.1", port);
  1026. if (socket_fd < 0) {
  1027. DLog("无法连接到本地服务: 端口=%d", port);
  1028. // 发送关闭连接消息
  1029. CloseConnectionMessage close_message;
  1030. memset(&close_message, 0, sizeof(close_message));
  1031. close_message.header.type = MSG_CLOSE_CONNECTION;
  1032. close_message.header.connection_id = connection_id;
  1033. close_message.header.target = 0; // 设置接收方为host
  1034. write_message(proxy_fd, &close_message, sizeof(close_message));
  1035. return;
  1036. }
  1037. // 设置连接映射
  1038. set_connection_socket(connection_id, socket_fd);
  1039. // 创建连接处理线程
  1040. pthread_t thread;
  1041. int *thread_arg = malloc(sizeof(int));
  1042. *thread_arg = connection_id;
  1043. if (pthread_create(&thread, NULL, connection_handler_thread, thread_arg) != 0) {
  1044. DLog("创建连接处理线程失败: %s", strerror(errno));
  1045. free_connection_id(connection_id);
  1046. free(thread_arg);
  1047. return;
  1048. }
  1049. pthread_detach(thread);
  1050. }
  1051. /**
  1052. * 处理数据消息
  1053. * @param message 数据消息
  1054. */
  1055. void handle_data_message(DataMessage *message) {
  1056. int connection_id = message->header.connection_id;
  1057. int socket_fd = get_connection_socket(connection_id);
  1058. if (socket_fd < 0) {
  1059. DLog("无效的连接ID: %d", connection_id);
  1060. return;
  1061. }
  1062. // 将数据发送到本地服务
  1063. int bytes_sent = write(socket_fd, message->data, message->header.data_size);
  1064. if (bytes_sent < 0) {
  1065. DLog("发送数据到本地服务失败: %s", strerror(errno));
  1066. // 发送关闭连接消息
  1067. CloseConnectionMessage close_message;
  1068. memset(&close_message, 0, sizeof(close_message));
  1069. close_message.header.type = MSG_CLOSE_CONNECTION;
  1070. close_message.header.connection_id = connection_id;
  1071. close_message.header.target = 0; // 设置接收方为host
  1072. write_message(proxy_fd, &close_message, sizeof(close_message));
  1073. free_connection_id(connection_id);
  1074. }
  1075. }
  1076. /**
  1077. * 处理关闭连接消息
  1078. * @param message 关闭连接消息
  1079. */
  1080. void handle_close_connection(CloseConnectionMessage *message) {
  1081. int connection_id = message->header.connection_id;
  1082. DLog("关闭连接: ID=%d", connection_id);
  1083. free_connection_id(connection_id);
  1084. }
  1085. /**
  1086. * 端口监控线程函数
  1087. * @param arg 线程参数
  1088. * @return NULL
  1089. */
  1090. void *port_monitor_thread(void *arg) {
  1091. while (1) {
  1092. update_ports();
  1093. sleep(1);
  1094. }
  1095. return NULL;
  1096. }
  1097. /**
  1098. * 连接处理线程函数
  1099. * @param arg 线程参数(连接ID)
  1100. * @return NULL
  1101. */
  1102. void *connection_handler_thread(void *arg) {
  1103. int connection_id = *((int *)arg);
  1104. free(arg);
  1105. int socket_fd = get_connection_socket(connection_id);
  1106. if (socket_fd < 0) {
  1107. return NULL;
  1108. }
  1109. char buffer[MAX_BUFFER_SIZE];
  1110. while (1) {
  1111. // 从本地服务读取数据
  1112. int bytes_read = read(socket_fd, buffer, MAX_BUFFER_SIZE);
  1113. if (bytes_read <= 0) {
  1114. if (bytes_read < 0) {
  1115. DLog("从本地服务读取数据失败: %s", strerror(errno));
  1116. }
  1117. break;
  1118. }
  1119. // 发送数据消息给host
  1120. DataMessage message;
  1121. memset(&message, 0, sizeof(message));
  1122. message.header.type = MSG_DATA;
  1123. message.header.connection_id = connection_id;
  1124. message.header.data_size = bytes_read;
  1125. message.header.target = 0; // 设置接收方为host
  1126. memcpy(message.data, buffer, bytes_read);
  1127. write_message(proxy_fd, &message, sizeof(MessageHeader) + bytes_read);
  1128. }
  1129. // 发送关闭连接消息
  1130. CloseConnectionMessage close_message;
  1131. memset(&close_message, 0, sizeof(close_message));
  1132. close_message.header.type = MSG_CLOSE_CONNECTION;
  1133. close_message.header.connection_id = connection_id;
  1134. write_message(proxy_fd, &close_message, sizeof(close_message));
  1135. free_connection_id(connection_id);
  1136. return NULL;
  1137. }
  1138. /**
  1139. * 处理握手消息
  1140. * @param message 握手消息
  1141. */
  1142. void handle_handshake_message(HandshakeMessage *message) {
  1143. DLog("收到来自host的握手消息,host已上线");
  1144. }
  1145. /**
  1146. * 消息处理线程函数
  1147. * @param arg 线程参数
  1148. * @return NULL
  1149. */
  1150. void *message_handler_thread(void *arg) {
  1151. char buffer[sizeof(DataMessage)];
  1152. while (1) {
  1153. // 读取消息
  1154. int bytes_read = read_message(proxy_fd, buffer, sizeof(buffer), 1); // 1表示client
  1155. if (bytes_read <= 0) {
  1156. usleep(1000 * 1); // 如果没有消息,等待一段时间(1 ms)
  1157. continue;
  1158. }
  1159. // 解析消息头
  1160. MessageHeader *header = (MessageHeader *)buffer;
  1161. // 根据消息类型处理
  1162. switch (header->type) {
  1163. case MSG_NEW_CONNECTION:
  1164. handle_new_connection((NewConnectionMessage *)buffer);
  1165. break;
  1166. case MSG_DATA:
  1167. handle_data_message((DataMessage *)buffer);
  1168. break;
  1169. case MSG_CLOSE_CONNECTION:
  1170. handle_close_connection((CloseConnectionMessage *)buffer);
  1171. break;
  1172. case MSG_HANDSHAKE:
  1173. handle_handshake_message((HandshakeMessage *)buffer);
  1174. break;
  1175. default:
  1176. DLog("未知的消息类型: %d", header->type);
  1177. break;
  1178. }
  1179. usleep(100);
  1180. }
  1181. return NULL;
  1182. }
  1183. /**
  1184. * 主函数
  1185. * @return 退出码
  1186. */
  1187. int vmnetproxy_main() {
  1188. DLog("VMNet Proxy Client 启动");
  1189. // 初始化连接映射表
  1190. init_connection_map();
  1191. // 打开代理文件
  1192. proxy_fd = open_proxy_file(0);
  1193. if (proxy_fd < 0) {
  1194. DLog("无法打开代理文件,退出");
  1195. return 1;
  1196. }
  1197. // 清空消息队列
  1198. if (clear_message_queue(proxy_fd) < 0) {
  1199. DLog("清空消息队列失败,继续执行");
  1200. }
  1201. // 发送握手消息给host
  1202. if (send_handshake_message(proxy_fd, 0) < 0) {
  1203. DLog("发送握手消息失败,继续执行");
  1204. }
  1205. // 创建端口监控线程
  1206. pthread_t port_thread;
  1207. if (pthread_create(&port_thread, NULL, port_monitor_thread, NULL) != 0) {
  1208. DLog("创建端口监控线程失败: %s", strerror(errno));
  1209. return 1;
  1210. }
  1211. // 创建消息处理线程
  1212. pthread_t message_thread;
  1213. if (pthread_create(&message_thread, NULL, message_handler_thread, NULL) != 0) {
  1214. DLog("创建消息处理线程失败: %s", strerror(errno));
  1215. return 1;
  1216. }
  1217. // 等待线程结束(实际上不会结束)
  1218. pthread_join(port_thread, NULL);
  1219. pthread_join(message_thread, NULL);
  1220. return 0;
  1221. }