Make use of JAYLINK_LOG_LEVEL_DEBUG_IO
[libjaylink.git] / libjaylink / transport_tcp.c
blob3d5409c5aab2d624948a6f3e44749d452132e977
1 /*
2 * This file is part of the libjaylink project.
4 * Copyright (C) 2015-2017 Marc Schink <jaylink-dev@marcschink.de>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include <stdlib.h>
21 #include <stdint.h>
22 #include <string.h>
23 #include <sys/types.h>
25 #ifdef _WIN32
26 #include <winsock2.h>
27 #include <ws2tcpip.h>
28 #else
29 #include <sys/time.h>
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <netdb.h>
33 #include <netinet/in.h>
34 #endif
36 #include "libjaylink.h"
37 #include "libjaylink-internal.h"
39 /**
40 * @file
42 * Transport abstraction layer (TCP/IP).
45 /** @cond PRIVATE */
46 #define CMD_SERVER 0x00
47 #define CMD_CLIENT 0x07
49 /**
50 * Response status code indicating that the maximum number of simultaneous
51 * connections on the device has been reached.
53 #define RESP_MAX_CONNECTIONS 0xfe
55 /** Buffer size in bytes. */
56 #define BUFFER_SIZE 2048
58 /** Timeout of a receive operation in milliseconds. */
59 #define RECV_TIMEOUT 5000
60 /** Timeout of a send operation in milliseconds. */
61 #define SEND_TIMEOUT 5000
63 /** String of the port number for the J-Link TCP/IP protocol. */
64 #define PORT_STRING "19020"
66 /** Size of the server's hello message in bytes. */
67 #define SERVER_HELLO_SIZE 4
68 /**
69 * Maximum length of the server name including trailing null-terminator in
70 * bytes.
72 #define SERVER_NAME_MAX_LENGTH 256
73 /** @endcond */
75 static int initialize_handle(struct jaylink_device_handle *devh)
77 struct jaylink_context *ctx;
79 ctx = devh->dev->ctx;
81 devh->buffer_size = BUFFER_SIZE;
82 devh->buffer = malloc(devh->buffer_size);
84 if (!devh->buffer) {
85 log_err(ctx, "Transport buffer malloc failed.");
86 return JAYLINK_ERR_MALLOC;
89 devh->read_length = 0;
90 devh->bytes_available = 0;
91 devh->read_pos = 0;
93 devh->write_length = 0;
94 devh->write_pos = 0;
96 return JAYLINK_OK;
99 static void cleanup_handle(struct jaylink_device_handle *devh)
101 free(devh->buffer);
104 static int _recv(struct jaylink_device_handle *devh, uint8_t *buffer,
105 size_t length)
107 struct jaylink_context *ctx;
108 size_t tmp;
110 ctx = devh->dev->ctx;
112 while (length > 0) {
113 tmp = length;
115 if (!socket_recv(devh->sock, buffer, &tmp, 0)) {
116 log_err(ctx, "Failed to receive data from device.");
117 return JAYLINK_ERR_IO;
118 } else if (!tmp) {
119 log_err(ctx, "Failed to receive data from device: "
120 "remote connection closed.");
121 return JAYLINK_ERR_IO;
124 buffer += tmp;
125 length -= tmp;
127 log_dbgio(ctx, "Received %zu bytes from device.", tmp);
130 return JAYLINK_OK;
133 static int handle_server_hello(struct jaylink_device_handle *devh)
135 int ret;
136 struct jaylink_context *ctx;
137 uint8_t buf[SERVER_HELLO_SIZE];
138 char name[SERVER_NAME_MAX_LENGTH];
139 uint16_t proto_version;
140 size_t length;
142 ctx = devh->dev->ctx;
144 ret = _recv(devh, buf, sizeof(buf));
146 if (ret != JAYLINK_OK) {
147 log_err(ctx, "Failed to receive hello message.");
148 return ret;
151 if (buf[0] == RESP_MAX_CONNECTIONS) {
152 log_err(ctx, "Maximum number of connections reached.");
153 return JAYLINK_ERR;
156 if (buf[0] != CMD_SERVER) {
157 log_err(ctx, "Invalid hello message received.");
158 return JAYLINK_ERR_PROTO;
161 proto_version = buffer_get_u16(buf, 1);
163 log_dbg(ctx, "Protocol version: 0x%04x.", proto_version);
165 length = buf[3];
166 ret = _recv(devh, (uint8_t *)name, length);
168 if (ret != JAYLINK_OK) {
169 log_err(ctx, "Failed to receive server name.");
170 return ret;
173 name[length] = '\0';
175 log_dbg(ctx, "Server name: %s.", name);
177 return JAYLINK_OK;
180 JAYLINK_PRIV int transport_tcp_open(struct jaylink_device_handle *devh)
182 int ret;
183 struct jaylink_context *ctx;
184 struct jaylink_device *dev;
185 struct addrinfo hints;
186 struct addrinfo *info;
187 struct addrinfo *rp;
188 struct timeval timeout;
189 int sock;
191 dev = devh->dev;
192 ctx = dev->ctx;
194 log_dbg(ctx, "Trying to open device (IPv4 address = %s).",
195 dev->ipv4_address);
197 ret = initialize_handle(devh);
199 if (ret != JAYLINK_OK) {
200 log_err(ctx, "Initialize device handle failed.");
201 return ret;
204 memset(&hints, 0, sizeof(struct addrinfo));
205 hints.ai_family = AF_INET;
206 hints.ai_socktype = SOCK_STREAM;
207 hints.ai_protocol = IPPROTO_TCP;
209 ret = getaddrinfo(dev->ipv4_address, PORT_STRING, &hints, &info);
211 if (ret != 0) {
212 log_err(ctx, "Address lookup failed.");
213 cleanup_handle(devh);
214 return JAYLINK_ERR;
217 sock = -1;
219 for (rp = info; rp != NULL; rp = rp->ai_next) {
220 sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
222 if (sock < 0)
223 continue;
225 if (!connect(sock, info->ai_addr, info->ai_addrlen))
226 break;
228 socket_close(sock);
229 sock = -1;
232 freeaddrinfo(info);
234 if (sock < 0) {
235 log_err(ctx, "Failed to open device.");
236 cleanup_handle(devh);
237 return JAYLINK_ERR;
240 log_dbg(ctx, "Device opened successfully.");
242 timeout.tv_sec = RECV_TIMEOUT / 1000;
243 timeout.tv_usec = (RECV_TIMEOUT % 1000) * 1000;
245 if (!socket_set_option(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout,
246 sizeof(struct timeval))) {
247 log_err(ctx, "Failed to set socket receive timeout.");
248 socket_close(sock);
249 cleanup_handle(devh);
250 return JAYLINK_ERR;
253 timeout.tv_sec = SEND_TIMEOUT / 1000;
254 timeout.tv_usec = (SEND_TIMEOUT % 1000) * 1000;
256 if (!socket_set_option(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout,
257 sizeof(struct timeval))) {
258 log_err(ctx, "Failed to set socket send timeout.");
259 socket_close(sock);
260 cleanup_handle(devh);
261 return JAYLINK_ERR;
264 devh->sock = sock;
266 ret = handle_server_hello(devh);
268 if (ret != JAYLINK_OK) {
269 socket_close(sock);
270 cleanup_handle(devh);
271 return ret;
274 return JAYLINK_OK;
277 JAYLINK_PRIV int transport_tcp_close(struct jaylink_device_handle *devh)
279 struct jaylink_context *ctx;
281 ctx = devh->dev->ctx;
283 log_dbg(ctx, "Closing device (IPv4 address = %s).",
284 devh->dev->ipv4_address);
286 cleanup_handle(devh);
288 log_dbg(ctx, "Device closed successfully.");
290 return JAYLINK_OK;
293 JAYLINK_PRIV int transport_tcp_start_write(struct jaylink_device_handle *devh,
294 size_t length, bool has_command)
296 struct jaylink_context *ctx;
298 if (!length)
299 return JAYLINK_ERR_ARG;
301 ctx = devh->dev->ctx;
303 log_dbgio(ctx, "Starting write operation (length = %zu bytes).",
304 length);
306 if (devh->write_pos > 0)
307 log_warn(ctx, "Last write operation left %zu bytes in the "
308 "buffer.", devh->write_pos);
310 if (devh->write_length > 0)
311 log_warn(ctx, "Last write operation was not performed.");
313 devh->write_length = length;
314 devh->write_pos = 0;
316 if (has_command) {
317 devh->buffer[0] = CMD_CLIENT;
318 devh->write_pos++;
321 return JAYLINK_OK;
324 JAYLINK_PRIV int transport_tcp_start_read(struct jaylink_device_handle *devh,
325 size_t length)
327 struct jaylink_context *ctx;
329 if (!length)
330 return JAYLINK_ERR_ARG;
332 ctx = devh->dev->ctx;
334 log_dbgio(ctx, "Starting read operation (length = %zu bytes).",
335 length);
337 if (devh->bytes_available > 0)
338 log_dbg(ctx, "Last read operation left %zu bytes in the "
339 "buffer.", devh->bytes_available);
341 if (devh->read_length > 0)
342 log_warn(ctx, "Last read operation left %zu bytes.",
343 devh->read_length);
345 devh->read_length = length;
347 return JAYLINK_OK;
350 JAYLINK_PRIV int transport_tcp_start_write_read(
351 struct jaylink_device_handle *devh, size_t write_length,
352 size_t read_length, bool has_command)
354 struct jaylink_context *ctx;
356 if (!read_length || !write_length)
357 return JAYLINK_ERR_ARG;
359 ctx = devh->dev->ctx;
361 log_dbgio(ctx, "Starting write / read operation (length = "
362 "%zu / %zu bytes).", write_length, read_length);
364 if (devh->write_pos > 0)
365 log_warn(ctx, "Last write operation left %zu bytes in the "
366 "buffer.", devh->write_pos);
368 if (devh->write_length > 0)
369 log_warn(ctx, "Last write operation was not performed.");
371 if (devh->bytes_available > 0)
372 log_warn(ctx, "Last read operation left %zu bytes in the "
373 "buffer.", devh->bytes_available);
375 if (devh->read_length > 0)
376 log_warn(ctx, "Last read operation left %zu bytes.",
377 devh->read_length);
379 devh->write_length = write_length;
380 devh->write_pos = 0;
382 if (has_command) {
383 devh->buffer[0] = CMD_CLIENT;
384 devh->write_pos++;
387 devh->read_length = read_length;
388 devh->bytes_available = 0;
389 devh->read_pos = 0;
391 return JAYLINK_OK;
394 static int _send(struct jaylink_device_handle *devh, const uint8_t *buffer,
395 size_t length)
397 struct jaylink_context *ctx;
398 size_t tmp;
400 ctx = devh->dev->ctx;
402 while (length > 0) {
403 tmp = length;
405 if (!socket_send(devh->sock, buffer, &tmp, 0)) {
406 log_err(ctx, "Failed to send data to device.");
407 return JAYLINK_ERR_IO;
410 buffer += tmp;
411 length -= tmp;
413 log_dbgio(ctx, "Sent %zu bytes to device.", tmp);
416 return JAYLINK_OK;
419 static bool adjust_buffer(struct jaylink_device_handle *devh, size_t size)
421 struct jaylink_context *ctx;
422 uint8_t *buffer;
423 size_t num;
425 ctx = devh->dev->ctx;
427 /* Adjust buffer size to a multiple of BUFFER_SIZE bytes. */
428 num = size / BUFFER_SIZE;
430 if (size % BUFFER_SIZE > 0)
431 num++;
433 size = num * BUFFER_SIZE;
434 buffer = realloc(devh->buffer, size);
436 if (!buffer) {
437 log_err(ctx, "Failed to adjust buffer size to %zu bytes.",
438 size);
439 return false;
442 devh->buffer = buffer;
443 devh->buffer_size = size;
445 log_dbg(ctx, "Adjusted buffer size to %zu bytes.", size);
447 return true;
450 JAYLINK_PRIV int transport_tcp_write(struct jaylink_device_handle *devh,
451 const uint8_t *buffer, size_t length)
453 int ret;
454 struct jaylink_context *ctx;
455 size_t tmp;
457 ctx = devh->dev->ctx;
459 if (length > devh->write_length) {
460 log_err(ctx, "Requested to write %zu bytes but only %zu bytes "
461 "are expected for the write operation.", length,
462 devh->write_length);
463 return JAYLINK_ERR_ARG;
467 * Store data in the buffer if the expected number of bytes for the
468 * write operation is not reached.
470 if (length < devh->write_length) {
471 if (devh->write_pos + length > devh->buffer_size) {
472 if (!adjust_buffer(devh, devh->write_pos + length))
473 return JAYLINK_ERR_MALLOC;
476 memcpy(devh->buffer + devh->write_pos, buffer, length);
478 devh->write_length -= length;
479 devh->write_pos += length;
481 log_dbgio(ctx, "Wrote %zu bytes into buffer.", length);
482 return JAYLINK_OK;
486 * Expected number of bytes for this write operation is reached and
487 * therefore the write operation will be performed.
489 devh->write_length = 0;
491 /* Send data directly to the device if the buffer is empty. */
492 if (!devh->write_pos)
493 return _send(devh, buffer, length);
495 tmp = MIN(length, devh->buffer_size - devh->write_pos);
498 * Fill up the internal buffer in order to reduce the number of
499 * messages sent to the device for performance reasons.
501 memcpy(devh->buffer + devh->write_pos, buffer, tmp);
503 length -= tmp;
504 buffer += tmp;
506 log_dbgio(ctx, "Buffer filled up with %zu bytes.", tmp);
508 ret = _send(devh, devh->buffer, devh->write_pos + tmp);
510 devh->write_pos = 0;
512 if (ret != JAYLINK_OK)
513 return ret;
515 if (!length)
516 return JAYLINK_OK;
518 return _send(devh, buffer, length);
521 JAYLINK_PRIV int transport_tcp_read(struct jaylink_device_handle *devh,
522 uint8_t *buffer, size_t length)
524 int ret;
525 struct jaylink_context *ctx;
527 ctx = devh->dev->ctx;
529 if (length > devh->read_length) {
530 log_err(ctx, "Requested to read %zu bytes but only %zu bytes "
531 "are expected for the read operation.", length,
532 devh->read_length);
533 return JAYLINK_ERR_ARG;
536 if (length <= devh->bytes_available) {
537 memcpy(buffer, devh->buffer + devh->read_pos, length);
539 devh->read_length -= length;
540 devh->bytes_available -= length;
541 devh->read_pos += length;
543 log_dbgio(ctx, "Read %zu bytes from buffer.", length);
544 return JAYLINK_OK;
547 if (devh->bytes_available) {
548 memcpy(buffer, devh->buffer + devh->read_pos,
549 devh->bytes_available);
551 buffer += devh->bytes_available;
552 length -= devh->bytes_available;
553 devh->read_length -= devh->bytes_available;
555 log_dbgio(ctx, "Read %zu bytes from buffer to flush it.",
556 devh->bytes_available);
558 devh->bytes_available = 0;
559 devh->read_pos = 0;
562 ret = _recv(devh, buffer, length);
564 if (ret != JAYLINK_OK)
565 return ret;
567 devh->read_length -= length;
569 return JAYLINK_OK;