]> git.sesse.net Git - ffmpeg/blob - libavformat/tcp.c
Merge commit '5691c746cf62e69806aae1baf0a6e8252d519444'
[ffmpeg] / libavformat / tcp.c
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/parseutils.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/time.h"
26
27 #include "internal.h"
28 #include "network.h"
29 #include "os_support.h"
30 #include "url.h"
31 #if HAVE_POLL_H
32 #include <poll.h>
33 #endif
34
35 typedef struct TCPContext {
36     const AVClass *class;
37     int fd;
38     int listen;
39     int open_timeout;
40     int rw_timeout;
41     int listen_timeout;
42     int recv_buffer_size;
43     int send_buffer_size;
44     int tcp_nodelay;
45 #if !HAVE_WINSOCK2_H
46     int tcp_mss;
47 #endif /* !HAVE_WINSOCK2_H */
48 } TCPContext;
49
50 #define OFFSET(x) offsetof(TCPContext, x)
51 #define D AV_OPT_FLAG_DECODING_PARAM
52 #define E AV_OPT_FLAG_ENCODING_PARAM
53 static const AVOption options[] = {
54     { "listen",          "Listen for incoming connections",  OFFSET(listen),         AV_OPT_TYPE_INT, { .i64 = 0 },     0,       2,       .flags = D|E },
55     { "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 },
56     { "listen_timeout",  "Connection awaiting timeout (in milliseconds)",      OFFSET(listen_timeout), AV_OPT_TYPE_INT, { .i64 = -1 },         -1, INT_MAX, .flags = D|E },
57     { "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 },
58     { "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 },
59     { "tcp_nodelay", "Use TCP_NODELAY to disable nagle's algorithm",           OFFSET(tcp_nodelay), AV_OPT_TYPE_BOOL, { .i64 = 0 },             0, 1, .flags = D|E },
60 #if !HAVE_WINSOCK2_H
61     { "tcp_mss",     "Maximum segment size for outgoing TCP packets",          OFFSET(tcp_mss),     AV_OPT_TYPE_INT, { .i64 = -1 },         -1, INT_MAX, .flags = D|E },
62 #endif /* !HAVE_WINSOCK2_H */
63     { NULL }
64 };
65
66 static const AVClass tcp_class = {
67     .class_name = "tcp",
68     .item_name  = av_default_item_name,
69     .option     = options,
70     .version    = LIBAVUTIL_VERSION_INT,
71 };
72
73 /* return non zero if error */
74 static int tcp_open(URLContext *h, const char *uri, int flags)
75 {
76     struct addrinfo hints = { 0 }, *ai, *cur_ai;
77     int port, fd = -1;
78     TCPContext *s = h->priv_data;
79     const char *p;
80     char buf[256];
81     int ret;
82     char hostname[1024],proto[1024],path[1024];
83     char portstr[10];
84     s->open_timeout = 5000000;
85
86     av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname),
87         &port, path, sizeof(path), uri);
88     if (strcmp(proto, "tcp"))
89         return AVERROR(EINVAL);
90     if (port <= 0 || port >= 65536) {
91         av_log(h, AV_LOG_ERROR, "Port missing in uri\n");
92         return AVERROR(EINVAL);
93     }
94     p = strchr(uri, '?');
95     if (p) {
96         if (av_find_info_tag(buf, sizeof(buf), "listen", p)) {
97             char *endptr = NULL;
98             s->listen = strtol(buf, &endptr, 10);
99             /* assume if no digits were found it is a request to enable it */
100             if (buf == endptr)
101                 s->listen = 1;
102         }
103         if (av_find_info_tag(buf, sizeof(buf), "timeout", p)) {
104             s->rw_timeout = strtol(buf, NULL, 10);
105         }
106         if (av_find_info_tag(buf, sizeof(buf), "listen_timeout", p)) {
107             s->listen_timeout = strtol(buf, NULL, 10);
108         }
109     }
110     if (s->rw_timeout >= 0) {
111         s->open_timeout =
112         h->rw_timeout   = s->rw_timeout;
113     }
114     hints.ai_family = AF_UNSPEC;
115     hints.ai_socktype = SOCK_STREAM;
116     snprintf(portstr, sizeof(portstr), "%d", port);
117     if (s->listen)
118         hints.ai_flags |= AI_PASSIVE;
119     if (!hostname[0])
120         ret = getaddrinfo(NULL, portstr, &hints, &ai);
121     else
122         ret = getaddrinfo(hostname, portstr, &hints, &ai);
123     if (ret) {
124         av_log(h, AV_LOG_ERROR,
125                "Failed to resolve hostname %s: %s\n",
126                hostname, gai_strerror(ret));
127         return AVERROR(EIO);
128     }
129
130     cur_ai = ai;
131
132  restart:
133 #if HAVE_STRUCT_SOCKADDR_IN6
134     // workaround for IOS9 getaddrinfo in IPv6 only network use hardcode IPv4 address can not resolve port number.
135     if (cur_ai->ai_family == AF_INET6){
136         struct sockaddr_in6 * sockaddr_v6 = (struct sockaddr_in6 *)cur_ai->ai_addr;
137         if (!sockaddr_v6->sin6_port){
138             sockaddr_v6->sin6_port = htons(port);
139         }
140     }
141 #endif
142
143     fd = ff_socket(cur_ai->ai_family,
144                    cur_ai->ai_socktype,
145                    cur_ai->ai_protocol);
146     if (fd < 0) {
147         ret = ff_neterrno();
148         goto fail;
149     }
150
151     /* Set the socket's send or receive buffer sizes, if specified.
152        If unspecified or setting fails, system default is used. */
153     if (s->recv_buffer_size > 0) {
154         if (setsockopt (fd, SOL_SOCKET, SO_RCVBUF, &s->recv_buffer_size, sizeof (s->recv_buffer_size))) {
155             ff_log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RCVBUF)");
156         }
157     }
158     if (s->send_buffer_size > 0) {
159         if (setsockopt (fd, SOL_SOCKET, SO_SNDBUF, &s->send_buffer_size, sizeof (s->send_buffer_size))) {
160             ff_log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_SNDBUF)");
161         }
162     }
163     if (s->tcp_nodelay > 0) {
164         if (setsockopt (fd, IPPROTO_TCP, TCP_NODELAY, &s->tcp_nodelay, sizeof (s->tcp_nodelay))) {
165             ff_log_net_error(h, AV_LOG_WARNING, "setsockopt(TCP_NODELAY)");
166         }
167     }
168 #if !HAVE_WINSOCK2_H
169     if (s->tcp_mss > 0) {
170         if (setsockopt (fd, IPPROTO_TCP, TCP_MAXSEG, &s->tcp_mss, sizeof (s->tcp_mss))) {
171             ff_log_net_error(h, AV_LOG_WARNING, "setsockopt(TCP_MAXSEG)");
172         }
173     }
174 #endif /* !HAVE_WINSOCK2_H */
175
176     if (s->listen == 2) {
177         // multi-client
178         if ((ret = ff_listen(fd, cur_ai->ai_addr, cur_ai->ai_addrlen)) < 0)
179             goto fail1;
180     } else if (s->listen == 1) {
181         // single client
182         if ((ret = ff_listen_bind(fd, cur_ai->ai_addr, cur_ai->ai_addrlen,
183                                   s->listen_timeout, h)) < 0)
184             goto fail1;
185         // Socket descriptor already closed here. Safe to overwrite to client one.
186         fd = ret;
187     } else {
188         if ((ret = ff_listen_connect(fd, cur_ai->ai_addr, cur_ai->ai_addrlen,
189                                      s->open_timeout / 1000, h, !!cur_ai->ai_next)) < 0) {
190
191             if (ret == AVERROR_EXIT)
192                 goto fail1;
193             else
194                 goto fail;
195         }
196     }
197
198     h->is_streamed = 1;
199     s->fd = fd;
200
201     freeaddrinfo(ai);
202     return 0;
203
204  fail:
205     if (cur_ai->ai_next) {
206         /* Retry with the next sockaddr */
207         cur_ai = cur_ai->ai_next;
208         if (fd >= 0)
209             closesocket(fd);
210         ret = 0;
211         goto restart;
212     }
213  fail1:
214     if (fd >= 0)
215         closesocket(fd);
216     freeaddrinfo(ai);
217     return ret;
218 }
219
220 static int tcp_accept(URLContext *s, URLContext **c)
221 {
222     TCPContext *sc = s->priv_data;
223     TCPContext *cc;
224     int ret;
225     av_assert0(sc->listen);
226     if ((ret = ffurl_alloc(c, s->filename, s->flags, &s->interrupt_callback)) < 0)
227         return ret;
228     cc = (*c)->priv_data;
229     ret = ff_accept(sc->fd, sc->listen_timeout, s);
230     if (ret < 0) {
231         ffurl_closep(c);
232         return ret;
233     }
234     cc->fd = ret;
235     return 0;
236 }
237
238 static int tcp_read(URLContext *h, uint8_t *buf, int size)
239 {
240     TCPContext *s = h->priv_data;
241     int ret;
242
243     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
244         ret = ff_network_wait_fd_timeout(s->fd, 0, h->rw_timeout, &h->interrupt_callback);
245         if (ret)
246             return ret;
247     }
248     ret = recv(s->fd, buf, size, 0);
249     if (ret == 0)
250         return AVERROR_EOF;
251     return ret < 0 ? ff_neterrno() : ret;
252 }
253
254 static int tcp_write(URLContext *h, const uint8_t *buf, int size)
255 {
256     TCPContext *s = h->priv_data;
257     int ret;
258
259     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
260         ret = ff_network_wait_fd_timeout(s->fd, 1, h->rw_timeout, &h->interrupt_callback);
261         if (ret)
262             return ret;
263     }
264     ret = send(s->fd, buf, size, MSG_NOSIGNAL);
265     return ret < 0 ? ff_neterrno() : ret;
266 }
267
268 static int tcp_shutdown(URLContext *h, int flags)
269 {
270     TCPContext *s = h->priv_data;
271     int how;
272
273     if (flags & AVIO_FLAG_WRITE && flags & AVIO_FLAG_READ) {
274         how = SHUT_RDWR;
275     } else if (flags & AVIO_FLAG_WRITE) {
276         how = SHUT_WR;
277     } else {
278         how = SHUT_RD;
279     }
280
281     return shutdown(s->fd, how);
282 }
283
284 static int tcp_close(URLContext *h)
285 {
286     TCPContext *s = h->priv_data;
287     closesocket(s->fd);
288     return 0;
289 }
290
291 static int tcp_get_file_handle(URLContext *h)
292 {
293     TCPContext *s = h->priv_data;
294     return s->fd;
295 }
296
297 static int tcp_get_window_size(URLContext *h)
298 {
299     TCPContext *s = h->priv_data;
300     int avail;
301     socklen_t avail_len = sizeof(avail);
302
303 #if HAVE_WINSOCK2_H
304     /* SO_RCVBUF with winsock only reports the actual TCP window size when
305     auto-tuning has been disabled via setting SO_RCVBUF */
306     if (s->recv_buffer_size < 0) {
307         return AVERROR(ENOSYS);
308     }
309 #endif
310
311     if (getsockopt(s->fd, SOL_SOCKET, SO_RCVBUF, &avail, &avail_len)) {
312         return ff_neterrno();
313     }
314     return avail;
315 }
316
317 const URLProtocol ff_tcp_protocol = {
318     .name                = "tcp",
319     .url_open            = tcp_open,
320     .url_accept          = tcp_accept,
321     .url_read            = tcp_read,
322     .url_write           = tcp_write,
323     .url_close           = tcp_close,
324     .url_get_file_handle = tcp_get_file_handle,
325     .url_get_short_seek  = tcp_get_window_size,
326     .url_shutdown        = tcp_shutdown,
327     .priv_data_size      = sizeof(TCPContext),
328     .flags               = URL_PROTOCOL_FLAG_NETWORK,
329     .priv_data_class     = &tcp_class,
330 };