FFmpeg
Loading...
Searching...
No Matches
tcp.c
Go to the documentation of this file.
1/*
2 * TCP protocol
3 * Copyright (c) 2002 Fabrice Bellard
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21#include "avformat.h"
22#include "libavutil/avassert.h"
23#include "libavutil/mem.h"
25#include "libavutil/opt.h"
26#include "libavutil/time.h"
27
28#include "internal.h"
29#include "network.h"
30#include "os_support.h"
31#include "url.h"
32#if HAVE_POLL_H
33#include <poll.h>
34#endif
35
36typedef struct TCPContext {
37 const AVClass *class;
38 int fd;
39 int listen;
49#if !HAVE_WINSOCK2_H
51#endif /* !HAVE_WINSOCK2_H */
53
54#define OFFSET(x) offsetof(TCPContext, x)
55#define D AV_OPT_FLAG_DECODING_PARAM
56#define E AV_OPT_FLAG_ENCODING_PARAM
57static const AVOption options[] = {
58 { "listen", "Listen for incoming connections", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, .flags = D|E },
59 { "local_port", "Local port", OFFSET(local_port), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, .flags = D|E },
60 { "local_addr", "Local address", OFFSET(local_addr), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, .flags = D|E },
61 { "timeout", "set timeout (in microseconds) of socket I/O operations", OFFSET(rw_timeout), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, .flags = D|E },
62 { "listen_timeout", "Connection awaiting timeout (in milliseconds)", OFFSET(listen_timeout), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, .flags = D|E },
63 { "send_buffer_size", "Socket send buffer size (in bytes)", OFFSET(send_buffer_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, .flags = D|E },
64 { "recv_buffer_size", "Socket receive buffer size (in bytes)", OFFSET(recv_buffer_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, .flags = D|E },
65 { "tcp_nodelay", "Use TCP_NODELAY to disable nagle's algorithm", OFFSET(tcp_nodelay), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = D|E },
66 { "tcp_keepalive", "Use TCP keepalive to detect dead connections and keep long-lived connections active.", OFFSET(tcp_keepalive), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = D|E },
67#if !HAVE_WINSOCK2_H
68 { "tcp_mss", "Maximum segment size for outgoing TCP packets", OFFSET(tcp_mss), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, .flags = D|E },
69#endif /* !HAVE_WINSOCK2_H */
70 { NULL }
71};
72
73static const AVClass tcp_class = {
74 .class_name = "tcp",
75 .item_name = av_default_item_name,
76 .option = options,
77 .version = LIBAVUTIL_VERSION_INT,
78};
79
80static int customize_fd(void *ctx, int fd, int family)
81{
82 TCPContext *s = ctx;
83
84 if (s->local_addr || s->local_port) {
85 struct addrinfo hints = { 0 }, *ai, *cur_ai;
86 int ret;
87
88 hints.ai_family = family;
89 hints.ai_socktype = SOCK_STREAM;
90
91 ret = getaddrinfo(s->local_addr, s->local_port, &hints, &ai);
92 if (ret) {
94 "Failed to getaddrinfo local addr: %s port: %s err: %s\n",
95 s->local_addr, s->local_port, gai_strerror(ret));
96 return ret;
97 }
98
99 cur_ai = ai;
100 while (cur_ai) {
101 ret = bind(fd, (struct sockaddr *)cur_ai->ai_addr, (int)cur_ai->ai_addrlen);
102 if (ret)
103 cur_ai = cur_ai->ai_next;
104 else
105 break;
106 }
107 freeaddrinfo(ai);
108
109 if (ret) {
110 ff_log_net_error(ctx, AV_LOG_ERROR, "bind local failed");
111 return ret;
112 }
113 }
114 /* Set the socket's send or receive buffer sizes, if specified.
115 If unspecified or setting fails, system default is used. */
116 if (s->recv_buffer_size > 0) {
117 if (setsockopt (fd, SOL_SOCKET, SO_RCVBUF, &s->recv_buffer_size, sizeof (s->recv_buffer_size))) {
118 ff_log_net_error(ctx, AV_LOG_WARNING, "setsockopt(SO_RCVBUF)");
119 }
120 }
121 if (s->send_buffer_size > 0) {
122 if (setsockopt (fd, SOL_SOCKET, SO_SNDBUF, &s->send_buffer_size, sizeof (s->send_buffer_size))) {
123 ff_log_net_error(ctx, AV_LOG_WARNING, "setsockopt(SO_SNDBUF)");
124 }
125 }
126 if (s->tcp_nodelay > 0) {
127 if (setsockopt (fd, IPPROTO_TCP, TCP_NODELAY, &s->tcp_nodelay, sizeof (s->tcp_nodelay))) {
128 ff_log_net_error(ctx, AV_LOG_WARNING, "setsockopt(TCP_NODELAY)");
129 }
130 }
131 if (s->tcp_keepalive > 0) {
132 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &s->tcp_keepalive, sizeof(s->tcp_keepalive))) {
133 ff_log_net_error(ctx, AV_LOG_WARNING, "setsockopt(SO_KEEPALIVE)");
134 }
135 }
136
137#if !HAVE_WINSOCK2_H
138 if (s->tcp_mss > 0) {
139 if (setsockopt (fd, IPPROTO_TCP, TCP_MAXSEG, &s->tcp_mss, sizeof (s->tcp_mss))) {
140 ff_log_net_error(ctx, AV_LOG_WARNING, "setsockopt(TCP_MAXSEG)");
141 }
142 }
143#endif /* !HAVE_WINSOCK2_H */
144
145 return 0;
146}
147
148/* return non zero if error */
149static int tcp_open(URLContext *h, const char *uri, int flags)
150{
151 struct addrinfo hints = { 0 }, *ai, *cur_ai;
152 int port, fd = -1;
153 TCPContext *s = h->priv_data;
154 const char *p;
155 int ret;
156 char hostname[1024],proto[1024],path[1024];
157 char portstr[10];
158 s->open_timeout = 5000000;
159
160 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname),
161 &port, path, sizeof(path), uri);
162 if (strcmp(proto, "tcp"))
163 return AVERROR(EINVAL);
164 if (port <= 0 || port >= 65536) {
165 av_log(h, AV_LOG_ERROR, "Port missing in uri\n");
166 return AVERROR(EINVAL);
167 }
168 p = strchr(uri, '?');
169 if (p) {
171 if (ret < 0)
172 return ret;
173 }
174 if (s->rw_timeout >= 0) {
175 s->open_timeout =
176 h->rw_timeout = s->rw_timeout;
177 }
178 hints.ai_family = AF_UNSPEC;
179 hints.ai_socktype = SOCK_STREAM;
180 snprintf(portstr, sizeof(portstr), "%d", port);
181 if (s->listen)
182 hints.ai_flags |= AI_PASSIVE;
183 if (!hostname[0])
184 ret = getaddrinfo(NULL, portstr, &hints, &ai);
185 else
186 ret = getaddrinfo(hostname, portstr, &hints, &ai);
187 if (ret) {
189 "Failed to resolve hostname %s: %s\n",
190 hostname, gai_strerror(ret));
191 return AVERROR(EIO);
192 }
193
194 cur_ai = ai;
195
196#if HAVE_STRUCT_SOCKADDR_IN6
197 // workaround for IOS9 getaddrinfo in IPv6 only network use hardcode IPv4 address can not resolve port number.
198 if (cur_ai->ai_family == AF_INET6){
199 struct sockaddr_in6 * sockaddr_v6 = (struct sockaddr_in6 *)cur_ai->ai_addr;
200 if (!sockaddr_v6->sin6_port){
201 sockaddr_v6->sin6_port = htons(port);
202 }
203 }
204#endif
205
206 if (s->listen > 0) {
207 while (cur_ai && fd < 0) {
208 fd = ff_socket(cur_ai->ai_family,
209 cur_ai->ai_socktype,
210 cur_ai->ai_protocol, h);
211 if (fd < 0) {
212 ret = ff_neterrno();
213 cur_ai = cur_ai->ai_next;
214 }
215 }
216 if (fd < 0)
217 goto fail1;
218 customize_fd(s, fd, cur_ai->ai_family);
219 }
220
221 if (s->listen == 2) {
222 // multi-client
223 if ((ret = ff_listen(fd, cur_ai->ai_addr, cur_ai->ai_addrlen, h)) < 0)
224 goto fail1;
225 } else if (s->listen == 1) {
226 // single client
227 if ((ret = ff_listen_bind(fd, cur_ai->ai_addr, cur_ai->ai_addrlen,
228 s->listen_timeout, h)) < 0)
229 goto fail1;
230 // Socket descriptor already closed here. Safe to overwrite to client one.
231 fd = ret;
232 } else {
233 ret = ff_connect_parallel(ai, s->open_timeout / 1000, 3, h, &fd, customize_fd, s);
234 if (ret < 0)
235 goto fail1;
236 }
237
238 h->is_streamed = 1;
239 s->fd = fd;
240
241 freeaddrinfo(ai);
242 return 0;
243
244 fail1:
245 if (fd >= 0)
246 closesocket(fd);
247 freeaddrinfo(ai);
248 return ret;
249}
250
252{
253 TCPContext *sc = s->priv_data;
254 TCPContext *cc;
255 int ret;
256 av_assert0(sc->listen);
257 if ((ret = ffurl_alloc(c, s->filename, s->flags, &s->interrupt_callback)) < 0)
258 return ret;
259 cc = (*c)->priv_data;
260 ret = ff_accept(sc->fd, sc->listen_timeout, s);
261 if (ret < 0) {
263 return ret;
264 }
265 cc->fd = ret;
266 return 0;
267}
268
269static int tcp_read(URLContext *h, uint8_t *buf, int size)
270{
271 TCPContext *s = h->priv_data;
272 int ret;
273
274 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
275 ret = ff_network_wait_fd_timeout(s->fd, 0, h->rw_timeout, &h->interrupt_callback);
276 if (ret)
277 return ret;
278 }
279 ret = recv(s->fd, buf, size, 0);
280 if (ret == 0)
281 return AVERROR_EOF;
282 return ret < 0 ? ff_neterrno() : ret;
283}
284
285static int tcp_write(URLContext *h, const uint8_t *buf, int size)
286{
287 TCPContext *s = h->priv_data;
288 int ret;
289
290 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
291 ret = ff_network_wait_fd_timeout(s->fd, 1, h->rw_timeout, &h->interrupt_callback);
292 if (ret)
293 return ret;
294 }
295 ret = send(s->fd, buf, size, MSG_NOSIGNAL);
296 return ret < 0 ? ff_neterrno() : ret;
297}
298
300{
301 TCPContext *s = h->priv_data;
302 int how;
303
305 how = SHUT_RDWR;
306 } else if (flags & AVIO_FLAG_WRITE) {
307 how = SHUT_WR;
308 } else {
309 how = SHUT_RD;
310 }
311
312 return shutdown(s->fd, how);
313}
314
316{
317 TCPContext *s = h->priv_data;
318 closesocket(s->fd);
319 return 0;
320}
321
323{
324 TCPContext *s = h->priv_data;
325 return s->fd;
326}
327
329{
330 TCPContext *s = h->priv_data;
331 int avail;
332 socklen_t avail_len = sizeof(avail);
333
334#if HAVE_WINSOCK2_H
335 /* SO_RCVBUF with winsock only reports the actual TCP window size when
336 auto-tuning has been disabled via setting SO_RCVBUF */
337 if (s->recv_buffer_size < 0) {
338 return AVERROR(ENOSYS);
339 }
340#endif
341
342 if (getsockopt(s->fd, SOL_SOCKET, SO_RCVBUF, &avail, &avail_len)) {
343 return ff_neterrno();
344 }
345 return avail;
346}
347
349 .name = "tcp",
350 .url_open = tcp_open,
351 .url_accept = tcp_accept,
352 .url_read = tcp_read,
353 .url_write = tcp_write,
354 .url_close = tcp_close,
355 .url_get_file_handle = tcp_get_file_handle,
356 .url_get_short_seek = tcp_get_window_size,
357 .url_shutdown = tcp_shutdown,
358 .priv_data_size = sizeof(TCPContext),
360 .priv_data_class = &tcp_class,
361};
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
#define E
Definition avdct.c:34
#define D
Definition avdct.c:35
Main libavformat public API header.
int ffurl_alloc(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb)
Create a URLContext for accessing to the resource indicated by url, but do not initiate the connectio...
Definition avio.c:360
int ffurl_closep(URLContext **hh)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition avio.c:656
#define AVIO_FLAG_READ
read-only
Definition avio.h:617
#define AVIO_FLAG_WRITE
write-only
Definition avio.h:618
#define AVIO_FLAG_NONBLOCK
Use non-blocking mode.
Definition avio.h:636
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define s(width, name)
Definition cbs_vp9.c:198
#define NULL
Definition coverity.c:32
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
@ AV_OPT_TYPE_STRING
Underlying C type is a uint8_t* that is either NULL or points to a C string allocated with the av_mal...
Definition opt.h:275
void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url)
Split a URL string into components.
Definition utils.c:361
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:241
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
int ff_parse_opts_from_query_string(void *obj, const char *str, int allow_unknown)
Set a list of query string options on an object.
Definition utils.c:643
Memory handling functions.
int ff_connect_parallel(struct addrinfo *addrs, int timeout_ms_per_address, int parallel, URLContext *h, int *fd, int(*customize_fd)(void *, int, int), void *customize_ctx)
Connect to any of the given addrinfo addresses, with multiple attempts running in parallel.
Definition network.c:413
int ff_socket(int af, int type, int proto, void *logctx)
Definition network.c:188
int ff_listen(int fd, const struct sockaddr *addr, socklen_t addrlen, void *logctx)
Bind to a file descriptor to an address without accepting connections.
Definition network.c:215
void ff_log_net_error(void *ctx, int level, const char *prefix)
Definition network.c:588
int ff_listen_bind(int fd, const struct sockaddr *addr, socklen_t addrlen, int timeout, URLContext *h)
Bind to a file descriptor and poll for a connection.
Definition network.c:251
int ff_network_wait_fd_timeout(int fd, int write, int64_t timeout, AVIOInterruptCB *int_cb)
This works similarly to ff_network_wait_fd, but waits up to 'timeout' microseconds Uses ff_network_wa...
Definition network.c:83
int ff_accept(int fd, int timeout, URLContext *h)
Poll for a single connection on the passed file descriptor.
Definition network.c:233
#define gai_strerror
Definition network.h:225
#define getaddrinfo
Definition network.h:217
#define MSG_NOSIGNAL
Definition network.h:133
#define ff_neterrno()
Definition network.h:68
#define freeaddrinfo
Definition network.h:218
#define AI_PASSIVE
Definition network.h:179
AVOptions.
miscellaneous OS support macros and functions.
misc parsing utilities
const URLProtocol ff_tcp_protocol
Definition tcp.c:348
#define snprintf
Definition snprintf.h:34
Describe the class of an AVClass context structure.
Definition log.h:76
AVOption.
Definition opt.h:428
char * local_port
Definition tcp.c:40
int tcp_nodelay
Definition tcp.c:47
int tcp_mss
Definition tcp.c:50
int listen_timeout
Definition tcp.c:44
int fd
Definition tcp.c:38
int open_timeout
Definition tcp.c:42
int rw_timeout
Definition tcp.c:43
int listen
Definition tcp.c:39
char * local_addr
Definition tcp.c:41
int tcp_keepalive
Definition tcp.c:48
int recv_buffer_size
Definition tcp.c:45
int send_buffer_size
Definition tcp.c:46
int ai_socktype
Definition network.h:140
int ai_flags
Definition network.h:138
int ai_family
Definition network.h:139
#define av_log(a,...)
static int tcp_close(URLContext *h)
Definition tcp.c:315
static const AVClass tcp_class
Definition tcp.c:73
static int tcp_accept(URLContext *s, URLContext **c)
Definition tcp.c:251
static int tcp_write(URLContext *h, const uint8_t *buf, int size)
Definition tcp.c:285
static int tcp_get_window_size(URLContext *h)
Definition tcp.c:328
static int customize_fd(void *ctx, int fd, int family)
Definition tcp.c:80
static int tcp_open(URLContext *h, const char *uri, int flags)
Definition tcp.c:149
static int tcp_read(URLContext *h, uint8_t *buf, int size)
Definition tcp.c:269
static int tcp_shutdown(URLContext *h, int flags)
Definition tcp.c:299
#define OFFSET(x)
Definition tcp.c:54
static int tcp_get_file_handle(URLContext *h)
Definition tcp.c:322
static AVFormatContext * ctx
Definition movenc.c:49
int size
unbuffered private I/O API
#define URL_PROTOCOL_FLAG_NETWORK
Definition url.h:33
static double c[64]