xref: /spdk/examples/sock/hello_world/hello_sock.c (revision 2f557958d0762ad00e068f997e2d25a205ded4b7)
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright (c) Intel Corporation.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include "spdk/stdinc.h"
35 #include "spdk/thread.h"
36 #include "spdk/env.h"
37 #include "spdk/event.h"
38 #include "spdk/log.h"
39 #include "spdk/string.h"
40 
41 #include "spdk/sock.h"
42 #include "spdk/net.h"
43 
44 #define ACCEPT_TIMEOUT_US 1000
45 #define CLOSE_TIMEOUT_US 1000000
46 #define BUFFER_SIZE 1024
47 #define ADDR_STR_LEN INET6_ADDRSTRLEN
48 
49 static bool g_is_running;
50 
51 static char *g_host;
52 static int g_port;
53 static bool g_is_server;
54 static bool g_verbose;
55 
56 /*
57  * We'll use this struct to gather housekeeping hello_context to pass between
58  * our events and callbacks.
59  */
60 struct hello_context_t {
61 	bool is_server;
62 	char *host;
63 	int port;
64 
65 	bool verbose;
66 	int bytes_in;
67 	int bytes_out;
68 
69 	struct spdk_sock *sock;
70 
71 	struct spdk_sock_group *group;
72 	struct spdk_poller *poller_in;
73 	struct spdk_poller *poller_out;
74 	struct spdk_poller *time_out;
75 
76 	int rc;
77 };
78 
79 /*
80  * Usage function for printing parameters that are specific to this application
81  */
82 static void
83 hello_sock_usage(void)
84 {
85 	printf(" -H host_addr  host address\n");
86 	printf(" -P port       port number\n");
87 	printf(" -S            start in server mode\n");
88 	printf(" -V            print out additional informations");
89 }
90 
91 /*
92  * This function is called to parse the parameters that are specific to this application
93  */
94 static void hello_sock_parse_arg(int ch, char *arg)
95 {
96 	switch (ch) {
97 	case 'H':
98 		g_host = arg;
99 		break;
100 	case 'P':
101 		g_port = atoi(arg);
102 		break;
103 	case 'S':
104 		g_is_server = 1;
105 		break;
106 	case 'V':
107 		g_verbose = true;
108 	}
109 }
110 
111 static void
112 hello_sock_net_fini_cb(void *cb_arg)
113 {
114 	struct hello_context_t *ctx = cb_arg;
115 	spdk_app_stop(ctx->rc);
116 }
117 
118 static int
119 hello_sock_close_timeout_poll(void *arg)
120 {
121 	struct hello_context_t *ctx = arg;
122 	SPDK_NOTICELOG("Connection closed\n");
123 
124 	spdk_poller_unregister(&ctx->time_out);
125 	spdk_poller_unregister(&ctx->poller_in);
126 	spdk_sock_close(&ctx->sock);
127 	spdk_sock_group_close(&ctx->group);
128 
129 	spdk_net_framework_fini(hello_sock_net_fini_cb, arg);
130 	return 0;
131 }
132 
133 static int
134 hello_sock_quit(struct hello_context_t *ctx, int rc)
135 {
136 	ctx->rc = rc;
137 	spdk_poller_unregister(&ctx->poller_out);
138 	ctx->time_out = spdk_poller_register(hello_sock_close_timeout_poll, ctx,
139 					     CLOSE_TIMEOUT_US);
140 	return 0;
141 }
142 
143 static int
144 hello_sock_recv_poll(void *arg)
145 {
146 	struct hello_context_t *ctx = arg;
147 	int rc;
148 	char buf_in[BUFFER_SIZE];
149 
150 	/*
151 	 * Get response
152 	 */
153 	rc = spdk_sock_recv(ctx->sock, buf_in, sizeof(buf_in) - 1);
154 
155 	if (rc <= 0) {
156 		if (errno == EAGAIN || errno == EWOULDBLOCK) {
157 			return 0;
158 		}
159 
160 		SPDK_ERRLOG("spdk_sock_recv() failed, errno %d: %s\n",
161 			    errno, spdk_strerror(errno));
162 		return -1;
163 	}
164 
165 	if (rc > 0) {
166 		ctx->bytes_in += rc;
167 		buf_in[rc] = '\0';
168 		printf("%s", buf_in);
169 	}
170 
171 	return 0;
172 }
173 
174 static int
175 hello_sock_writev_poll(void *arg)
176 {
177 	struct hello_context_t *ctx = arg;
178 	int rc = 0;
179 	char buf_out[BUFFER_SIZE];
180 	struct iovec iov;
181 	ssize_t n;
182 
183 	n = read(STDIN_FILENO, buf_out, sizeof(buf_out));
184 	if (n == 0 || !g_is_running) {
185 		/* EOF */
186 		SPDK_NOTICELOG("Closing connection...\n");
187 		hello_sock_quit(ctx, 0);
188 		return 0;
189 	}
190 	if (n > 0) {
191 		/*
192 		 * Send message to the server
193 		 */
194 		iov.iov_base = buf_out;
195 		iov.iov_len = n;
196 		rc = spdk_sock_writev(ctx->sock, &iov, 1);
197 		if (rc > 0) {
198 			ctx->bytes_out += rc;
199 		}
200 	}
201 	return rc;
202 }
203 
204 static int
205 hello_sock_connect(struct hello_context_t *ctx)
206 {
207 	int rc;
208 	char saddr[ADDR_STR_LEN], caddr[ADDR_STR_LEN];
209 	uint16_t cport, sport;
210 
211 	SPDK_NOTICELOG("Connecting to the server on %s:%d\n", ctx->host, ctx->port);
212 
213 	ctx->sock = spdk_sock_connect(ctx->host, ctx->port);
214 	if (ctx->sock == NULL) {
215 		SPDK_ERRLOG("connect error(%d): %s\n", errno, spdk_strerror(errno));
216 		return -1;
217 	}
218 
219 	rc = spdk_sock_getaddr(ctx->sock, saddr, sizeof(saddr), &sport, caddr, sizeof(caddr), &cport);
220 	if (rc < 0) {
221 		SPDK_ERRLOG("Cannot get connection addresses\n");
222 		spdk_sock_close(&ctx->sock);
223 		return -1;
224 	}
225 
226 	SPDK_NOTICELOG("Connection accepted from (%s, %hu) to (%s, %hu)\n", caddr, cport, saddr, sport);
227 
228 	fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL) | O_NONBLOCK);
229 
230 	g_is_running = true;
231 	ctx->poller_in = spdk_poller_register(hello_sock_recv_poll, ctx, 0);
232 	ctx->poller_out = spdk_poller_register(hello_sock_writev_poll, ctx, 0);
233 
234 	return 0;
235 }
236 
237 static void
238 hello_sock_cb(void *arg, struct spdk_sock_group *group, struct spdk_sock *sock)
239 {
240 	ssize_t n;
241 	char buf[BUFFER_SIZE];
242 	struct iovec iov;
243 	struct hello_context_t *ctx = arg;
244 
245 	n = spdk_sock_recv(sock, buf, sizeof(buf));
246 	if (n < 0) {
247 		if (errno == EAGAIN || errno == EWOULDBLOCK) {
248 			SPDK_ERRLOG("spdk_sock_recv() failed, errno %d: %s\n",
249 				    errno, spdk_strerror(errno));
250 			return;
251 		}
252 
253 		SPDK_ERRLOG("spdk_sock_recv() failed, errno %d: %s\n",
254 			    errno, spdk_strerror(errno));
255 	}
256 
257 	if (n > 0) {
258 		ctx->bytes_in += n;
259 		iov.iov_base = buf;
260 		iov.iov_len = n;
261 		n = spdk_sock_writev(sock, &iov, 1);
262 		if (n > 0) {
263 			ctx->bytes_out += n;
264 		}
265 		return;
266 	}
267 
268 	/* Connection closed */
269 	SPDK_NOTICELOG("Connection closed\n");
270 	spdk_sock_group_remove_sock(group, sock);
271 	spdk_sock_close(&sock);
272 }
273 
274 static int
275 hello_sock_accept_poll(void *arg)
276 {
277 	struct hello_context_t *ctx = arg;
278 	struct spdk_sock *sock;
279 	int rc;
280 	int count = 0;
281 	char saddr[ADDR_STR_LEN], caddr[ADDR_STR_LEN];
282 	uint16_t cport, sport;
283 
284 	if (!g_is_running) {
285 		hello_sock_quit(ctx, 0);
286 		return 0;
287 	}
288 
289 	while (1) {
290 		sock = spdk_sock_accept(ctx->sock);
291 		if (sock != NULL) {
292 			rc = spdk_sock_getaddr(sock, saddr, sizeof(saddr), &sport, caddr, sizeof(caddr), &cport);
293 			if (rc < 0) {
294 				SPDK_ERRLOG("Cannot get connection addresses\n");
295 				spdk_sock_close(&ctx->sock);
296 				return -1;
297 			}
298 
299 			SPDK_NOTICELOG("Accepting a new connection from (%s, %hu) to (%s, %hu)\n",
300 				       caddr, cport, saddr, sport);
301 
302 			rc = spdk_sock_group_add_sock(ctx->group, sock,
303 						      hello_sock_cb, ctx);
304 
305 			if (rc < 0) {
306 				spdk_sock_close(&sock);
307 				SPDK_ERRLOG("failed\n");
308 				break;
309 			}
310 
311 			count++;
312 		} else {
313 			if (errno != EAGAIN && errno != EWOULDBLOCK) {
314 				SPDK_ERRLOG("accept error(%d): %s\n", errno, spdk_strerror(errno));
315 			}
316 			break;
317 		}
318 	}
319 
320 	return count;
321 }
322 
323 static int
324 hello_sock_group_poll(void *arg)
325 {
326 	struct hello_context_t *ctx = arg;
327 	int rc;
328 
329 	rc = spdk_sock_group_poll(ctx->group);
330 	if (rc < 0) {
331 		SPDK_ERRLOG("Failed to poll sock_group=%p\n", ctx->group);
332 	}
333 
334 	return -1;
335 }
336 
337 static int
338 hello_sock_listen(struct hello_context_t *ctx)
339 {
340 	ctx->sock = spdk_sock_listen(ctx->host, ctx->port);
341 	if (ctx->sock == NULL) {
342 		SPDK_ERRLOG("Cannot create server socket\n");
343 		return -1;
344 	}
345 
346 	SPDK_NOTICELOG("Listening connection on %s:%d\n", ctx->host, ctx->port);
347 
348 	/*
349 	 * Create sock group for server socket
350 	 */
351 	ctx->group = spdk_sock_group_create();
352 
353 	g_is_running = true;
354 
355 	/*
356 	 * Start acceptor and group poller
357 	 */
358 	ctx->poller_in = spdk_poller_register(hello_sock_accept_poll, ctx,
359 					      ACCEPT_TIMEOUT_US);
360 	ctx->poller_out = spdk_poller_register(hello_sock_group_poll, ctx, 0);
361 
362 	return 0;
363 }
364 
365 static void
366 hello_sock_shutdown_cb(void)
367 {
368 	g_is_running = false;
369 }
370 
371 /*
372  * Our initial event that kicks off everything from main().
373  */
374 static void
375 hello_start(void *arg1, int rc)
376 {
377 	struct hello_context_t *ctx = arg1;
378 
379 	if (rc) {
380 		SPDK_ERRLOG("ERROR starting application\n");
381 		spdk_app_stop(-1);
382 		return;
383 	}
384 
385 	SPDK_NOTICELOG("Successfully started the application\n");
386 
387 	if (ctx->is_server) {
388 		rc = hello_sock_listen(ctx);
389 	} else {
390 		rc = hello_sock_connect(ctx);
391 	}
392 
393 	if (rc) {
394 		spdk_app_stop(-1);
395 		return;
396 	}
397 }
398 
399 static void
400 start_net_framework(void *arg1, void *arg2)
401 {
402 	spdk_net_framework_start(hello_start, arg1);
403 }
404 
405 int
406 main(int argc, char **argv)
407 {
408 	struct spdk_app_opts opts = {};
409 	int rc = 0;
410 	struct hello_context_t hello_context = {};
411 
412 	/* Set default values in opts structure. */
413 	spdk_app_opts_init(&opts);
414 	opts.name = "hello_sock";
415 	opts.config_file = "sock.conf";
416 	opts.shutdown_cb = hello_sock_shutdown_cb;
417 
418 	if ((rc = spdk_app_parse_args(argc, argv, &opts, "H:P:SV", NULL, hello_sock_parse_arg,
419 				      hello_sock_usage)) != SPDK_APP_PARSE_ARGS_SUCCESS) {
420 		exit(rc);
421 	}
422 	hello_context.is_server = g_is_server;
423 	hello_context.host = g_host;
424 	hello_context.port = g_port;
425 	hello_context.verbose = g_verbose;
426 
427 	rc = spdk_app_start(&opts, start_net_framework, &hello_context, NULL);
428 	if (rc) {
429 		SPDK_ERRLOG("ERROR starting application\n");
430 	}
431 
432 	SPDK_NOTICELOG("Exiting from application\n");
433 
434 	if (hello_context.verbose) {
435 		printf("** %d bytes received, %d bytes sent **\n",
436 		       hello_context.bytes_in, hello_context.bytes_out);
437 	}
438 
439 	/* Gracefully close out all of the SPDK subsystems. */
440 	spdk_app_fini();
441 	return rc;
442 }
443