1515#include <stdlib.h>
1616#include <stdint.h>
1717#include <string.h>
18+ #include <signal.h>
1819#include <unistd.h>
1920#include <stdio.h>
2021#include <errno.h>
2324#define BUF_SIZE (16 * 1024)
2425#define SERVER_ACCEPT_BACKLOG 128
2526
27+ volatile int connection_socket ;
2628
2729int print_usage () {
28- fprintf (stderr , "Usage: ./vsock-helper echo <cid> <port>\n" );
30+ fprintf (stderr , "Usage: ./vsock-helper echo <cid> <port> [stream|seqpacket] \n" );
2931 fprintf (stderr , "\n" );
3032 fprintf (stderr , " echo connect to an echo server, listening on CID:port.\n" );
3133 fprintf (stderr , " STDIN will be piped through to the echo server, and\n" );
3234 fprintf (stderr , " data coming from the server will pe sent to STDOUT.\n" );
35+ fprintf (stderr , " stream|seqpacket socket type (default: stream)\n" );
3336 fprintf (stderr , "\n" );
3437 return -1 ;
3538}
@@ -53,9 +56,9 @@ int xfer(int src_fd, int dst_fd) {
5356}
5457
5558
56- int run_echo (uint32_t cid , uint32_t port ) {
59+ int run_echo (uint32_t cid , uint32_t port , int sock_type ) {
5760
58- int sock = socket (AF_VSOCK , SOCK_STREAM , 0 );
61+ int sock = socket (AF_VSOCK , sock_type , 0 );
5962 if (sock < 0 ) {
6063 perror ("socket()" );
6164 return -1 ;
@@ -71,6 +74,8 @@ int run_echo(uint32_t cid, uint32_t port) {
7174 return -1 ;
7275 }
7376
77+ connection_socket = sock ;
78+
7479 for (;;) {
7580 int ping_cnt = xfer (STDIN_FILENO , sock );
7681 if (!ping_cnt ) break ;
@@ -87,23 +92,41 @@ int run_echo(uint32_t cid, uint32_t port) {
8792 return close (sock );
8893}
8994
95+ void stop_server_loop (int sig ) {
96+ close (connection_socket );
97+ }
98+
9099
91100int main (int argc , char * * argv ) {
101+ signal (SIGTERM , stop_server_loop );
102+ signal (SIGINT , stop_server_loop );
92103
93104 if (argc < 3 ) {
94105 return print_usage ();
95106 }
96107
97108 if (strcmp (argv [1 ], "echo" ) == 0 ) {
98- if (argc != 4 ) {
109+ if (argc < 4 || argc > 5 ) {
99110 return print_usage ();
100111 }
101112 uint32_t cid = atoi (argv [2 ]);
102113 uint32_t port = atoi (argv [3 ]);
103114 if (!cid || !port ) {
104115 return print_usage ();
105116 }
106- return run_echo (cid , port );
117+
118+ int sock_type = SOCK_STREAM ;
119+ if (argc == 5 ) {
120+ if (strcmp (argv [4 ], "seqpacket" ) == 0 ) {
121+ sock_type = SOCK_SEQPACKET ;
122+ } else if (strcmp (argv [4 ], "stream" ) == 0 ) {
123+ sock_type = SOCK_STREAM ;
124+ } else {
125+ return print_usage ();
126+ }
127+ }
128+
129+ return run_echo (cid , port , sock_type );
107130 }
108131
109132 return print_usage ();
0 commit comments