2 * This file is part of the libsigrok project.
4 * Copyright (C) 2023 Gerhard Sittig <gerhard.sittig@gmx.net>
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 3 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/>.
23 * Can we sort these include directives? Or do the platform specific
24 * headers depend on a specific order? Experience from VXI maintenance
25 * suggests that some systems can be picky and it's hard to notice ...
26 * For now the include statements follow the scpi_tcp.c template.
29 #define _WIN32_WINNT 0x0501
40 #include <arpa/inet.h>
42 #include <netinet/in.h>
43 #include <sys/socket.h>
44 #include <sys/types.h>
50 #include <sys/select.h>
53 #include <libsigrok/libsigrok.h>
54 #include "libsigrok-internal.h"
57 * Workaround because Windows cannot simply use established identifiers.
58 * https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-shutdown
60 #if !defined SHUT_RDWR && defined SD_BOTH
61 # define SHUT_RDWR SD_BOTH
64 #define LOG_PREFIX "tcp"
67 * Check whether a file descriptor is readable (without blocking).
69 * @param[in] fd The file descriptor to check for readability.
71 * @return TRUE when readable, FALSE when read would block or when
72 * readability could not get determined.
76 * TODO Move to common code, applies to non-sockets as well.
78 SR_PRIV gboolean sr_fd_is_readable(int fd)
84 memset(fds, 0, sizeof(fds));
86 fds[0].events = POLLIN;
87 ret = poll(fds, ARRAY_SIZE(fds), -1);
92 if (!(fds[0].revents & POLLIN))
103 memset(&tv, 0, sizeof(tv));
104 ret = select(fd + 1, &rfds, NULL, NULL, &tv);
109 if (!FD_ISSET(fd, rfds))
119 * Create a TCP communication instance.
121 * @param[in] host_addr The host name or IP address (a string).
122 * @param[in] tcp_port The TCP port number.
124 * @return A @ref sr_tcp_dev_inst structure on success. #NULL otherwise.
128 SR_PRIV struct sr_tcp_dev_inst *sr_tcp_dev_inst_new(
129 const char *host_addr, const char *tcp_port)
132 struct sr_tcp_dev_inst *tcp;
135 if (host_addr && *host_addr)
136 host = g_strdup(host_addr);
138 if (tcp_port && *tcp_port)
139 port = g_strdup(tcp_port);
141 tcp = g_malloc0(sizeof(*tcp));
144 tcp->host_addr = host;
145 tcp->tcp_port = port;
151 * Release a TCP communication instance.
153 * @param[in] host_addr The host name or IP address (a string).
154 * @param[in] tcp_port The TCP port number.
156 * @return A @ref sr_tcp_dev_inst structure on success. #NULL otherwise.
160 SR_PRIV void sr_tcp_dev_inst_free(struct sr_tcp_dev_inst *tcp)
166 (void)sr_tcp_disconnect(tcp);
167 g_free(tcp->host_addr);
172 * Construct display name for a TCP communication instance.
174 * @param[in] tcp The TCP communication instance to print the name of.
175 * @param[in] prefix An optional prefix text, or #NULL.
176 * @param[in] separator An optional separator character, or NUL.
177 * @param[out] path The caller provided buffer to fill in.
178 * @param[in] path_len The buffer's maximum length to fill in.
180 * @return SR_OK on success, SR_ERR_* otherwise.
184 SR_PRIV int sr_tcp_get_port_path(struct sr_tcp_dev_inst *tcp,
185 const char *prefix, char separator, char *path, size_t path_len)
189 /* Only construct connection name for full parameter sets. */
190 if (!tcp || !tcp->host_addr || !tcp->tcp_port)
193 /* Normalize input. Apply defaults. */
196 if (!*prefix && !separator)
199 /* Turn everything into strings. Simplifies the printf() call. */
200 sep_text[0] = separator;
203 /* Construct the resulting connection name. */
204 snprintf(path, path_len, "%s%s%s%s%s",
205 prefix, *prefix ? sep_text : "",
206 tcp->host_addr, sep_text, tcp->tcp_port);
211 * Connect to a remote TCP communication peer.
213 * @param[in] tcp The TCP communication instance to connect.
215 * @return SR_OK on success, SR_ERR_* otherwise.
219 SR_PRIV int sr_tcp_connect(struct sr_tcp_dev_inst *tcp)
221 struct addrinfo hints;
222 struct addrinfo *results, *r;
228 if (!tcp->host_addr || !tcp->tcp_port)
231 /* Lookup address information for the caller's spec. */
232 memset(&hints, 0, sizeof(hints));
233 hints.ai_family = AF_UNSPEC;
234 hints.ai_socktype = SOCK_STREAM;
235 hints.ai_protocol = IPPROTO_TCP;
236 ret = getaddrinfo(tcp->host_addr, tcp->tcp_port, &hints, &results);
238 sr_err("Address lookup failed: %s:%s: %s.",
239 tcp->host_addr, tcp->tcp_port, gai_strerror(ret));
243 /* Try to connect using the resulting address details. */
245 for (r = results; r; r = r->ai_next) {
246 fd = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
249 ret = connect(fd, r->ai_addr, r->ai_addrlen);
257 freeaddrinfo(results);
259 sr_err("Failed to connect to %s:%s: %s.",
260 tcp->host_addr, tcp->tcp_port, g_strerror(errno));
269 * Disconnect from a remote TCP communication peer.
271 * @param[in] tcp The TCP communication instance to disconnect.
273 * @return SR_OK on success, SR_ERR_* otherwise.
277 SR_PRIV int sr_tcp_disconnect(struct sr_tcp_dev_inst *tcp)
283 if (tcp->sock_fd < 0)
286 shutdown(tcp->sock_fd, SHUT_RDWR);
293 * Send transmit data to a TCP connection.
294 * Does a single operating system call, can return with short
295 * transmit byte counts. Will not continue after short writes,
296 * callers need to handle the condition.
298 * @param[in] tcp The TCP communication instance to send to.
299 * @param[in] data The data bytes to send.
300 * @param[in] dlen The number of bytes to send.
302 * @return Number of transmitted bytes on success, SR_ERR_* otherwise.
306 SR_PRIV int sr_tcp_write_bytes(struct sr_tcp_dev_inst *tcp,
307 const uint8_t *data, size_t dlen)
319 if (tcp->sock_fd < 0)
322 rc = send(tcp->sock_fd, data, dlen, 0);
325 written = (size_t)rc;
330 * Fetch receive data from a TCP connection.
331 * Does a single operating system call, can return with short
332 * receive byte counts. Will not continue after short reads,
333 * callers need to handle the condition.
335 * @param[in] tcp The TCP communication instance to read from.
336 * @param[in] data Caller provided buffer for receive data.
337 * @param[in] dlen The maximum number of bytes to receive.
338 * @param[in] nonblocking Whether to block for receive data.
340 * @return Number of received bytes on success, SR_ERR_* otherwise.
344 SR_PRIV int sr_tcp_read_bytes(struct sr_tcp_dev_inst *tcp,
345 uint8_t *data, size_t dlen, gboolean nonblocking)
357 if (tcp->sock_fd < 0)
360 if (nonblocking && !sr_fd_is_readable(tcp->sock_fd))
363 rc = recv(tcp->sock_fd, data, dlen, 0);
371 * Register receive callback for a TCP connection.
372 * The connection must have been established before. The callback
373 * gets invoked when receive data is available. Or when a timeout
376 * This is a simple wrapper around @ref sr_session_source_add().
378 * @param[in] session See @ref sr_session_source_add().
379 * @param[in] tcp The TCP communication instance to read from.
380 * @param[in] events See @ref sr_session_source_add().
381 * @param[in] timeout See @ref sr_session_source_add().
382 * @param[in] cb See @ref sr_session_source_add().
383 * @param[in] cb_data See @ref sr_session_source_add().
385 * @return SR_OK on success, SR_ERR* otherwise.
389 SR_PRIV int sr_tcp_source_add(struct sr_session *session,
390 struct sr_tcp_dev_inst *tcp, int events, int timeout,
391 sr_receive_data_callback cb, void *cb_data)
393 if (!tcp || tcp->sock_fd < 0)
395 return sr_session_source_add(session, tcp->sock_fd,
396 events, timeout, cb, cb_data);
400 * Unregister receive callback for a TCP connection.
402 * This is a simple wrapper around @ref sr_session_source_remove().
404 * @param[in] session See @ref sr_session_source_remove().
405 * @param[in] tcp The TCP communication instance to unregister.
407 * @return SR_OK on success, SR_ERR* otherwise.
411 SR_PRIV int sr_tcp_source_remove(struct sr_session *session,
412 struct sr_tcp_dev_inst *tcp)
414 if (!tcp || tcp->sock_fd < 0)
416 return sr_session_source_remove(session, tcp->sock_fd);