rv34: Check for invalid slices offsets
[libav.git] / libavformat / rtmpproto.c
CommitLineData
9fd6b843
KS
1/*
2 * RTMP network protocol
3 * Copyright (c) 2009 Kostya Shishkov
4 *
2912e87a 5 * This file is part of Libav.
9fd6b843 6 *
2912e87a 7 * Libav is free software; you can redistribute it and/or
9fd6b843
KS
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 *
2912e87a 12 * Libav is distributed in the hope that it will be useful,
9fd6b843
KS
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
2912e87a 18 * License along with Libav; if not, write to the Free Software
9fd6b843
KS
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22/**
ba87f080 23 * @file
9fd6b843
KS
24 * RTMP protocol
25 */
26
27#include "libavcodec/bytestream.h"
28#include "libavutil/avstring.h"
ee8aecd2 29#include "libavutil/intfloat_readwrite.h"
9fd6b843
KS
30#include "libavutil/lfg.h"
31#include "libavutil/sha.h"
32#include "avformat.h"
e4a9e3cc 33#include "internal.h"
9fd6b843
KS
34
35#include "network.h"
36
37#include "flv.h"
38#include "rtmp.h"
39#include "rtmppkt.h"
0589da0a 40#include "url.h"
9fd6b843 41
cfac91fe
KS
42//#define DEBUG
43
9fd6b843
KS
44/** RTMP protocol handler state */
45typedef enum {
46 STATE_START, ///< client has not done anything yet
47 STATE_HANDSHAKED, ///< client has performed handshake
6bf22e18
S
48 STATE_RELEASING, ///< client releasing stream before publish it (for output)
49 STATE_FCPUBLISH, ///< client FCPublishing stream (for output)
9fd6b843
KS
50 STATE_CONNECTING, ///< client connected to server successfully
51 STATE_READY, ///< client has sent all needed commands and waits for server reply
52 STATE_PLAYING, ///< client has started receiving multimedia data from server
6bf22e18 53 STATE_PUBLISHING, ///< client has started sending multimedia data to server (for output)
72b870b9 54 STATE_STOPPED, ///< the broadcast has been stopped
9fd6b843
KS
55} ClientState;
56
57/** protocol handler context */
58typedef struct RTMPContext {
59 URLContext* stream; ///< TCP stream used in interactions with RTMP server
60 RTMPPacket prev_pkt[2][RTMP_CHANNELS]; ///< packet history used when reading and sending packets
61 int chunk_size; ///< size of the chunks RTMP packets are divided into
b316991b 62 int is_input; ///< input/output flag
9fd6b843 63 char playpath[256]; ///< path to filename to play (with possible "mp4:" prefix)
5e9ad759 64 char app[128]; ///< application
9fd6b843
KS
65 ClientState state; ///< current state
66 int main_channel_id; ///< an additional channel ID which is used for some invocations
67 uint8_t* flv_data; ///< buffer with data for demuxer
68 int flv_size; ///< current buffer size
69 int flv_off; ///< number of bytes read from current buffer
6bf22e18 70 RTMPPacket out_pkt; ///< rtmp packet, created from flv a/v or metadata (for output)
bf7c1719
KS
71 uint32_t client_report_size; ///< number of bytes after which client should report to server
72 uint32_t bytes_read; ///< number of bytes read from server
73 uint32_t last_bytes_read; ///< number of bytes read last reported to server
3ffe32eb 74 int skip_bytes; ///< number of bytes to skip from the input FLV stream in the next write call
9fd6b843
KS
75} RTMPContext;
76
77#define PLAYER_KEY_OPEN_PART_LEN 30 ///< length of partial key used for first client digest signing
78/** Client key used for digest signing */
79static const uint8_t rtmp_player_key[] = {
80 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
81 'F', 'l', 'a', 's', 'h', ' ', 'P', 'l', 'a', 'y', 'e', 'r', ' ', '0', '0', '1',
82
83 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
84 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
85 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
86};
87
88#define SERVER_KEY_OPEN_PART_LEN 36 ///< length of partial key used for first server digest signing
89/** Key used for RTMP server digest signing */
90static const uint8_t rtmp_server_key[] = {
91 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
92 'F', 'l', 'a', 's', 'h', ' ', 'M', 'e', 'd', 'i', 'a', ' ',
93 'S', 'e', 'r', 'v', 'e', 'r', ' ', '0', '0', '1',
94
95 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
96 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
97 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
98};
99
100/**
49bd8e4b 101 * Generate 'connect' call and send it to the server.
9fd6b843
KS
102 */
103static void gen_connect(URLContext *s, RTMPContext *rt, const char *proto,
5e9ad759 104 const char *host, int port)
9fd6b843
KS
105{
106 RTMPPacket pkt;
6bf22e18 107 uint8_t ver[64], *p;
9fd6b843
KS
108 char tcurl[512];
109
31da5966 110 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 4096);
9fd6b843
KS
111 p = pkt.data;
112
57b5555c 113 ff_url_join(tcurl, sizeof(tcurl), proto, NULL, host, port, "/%s", rt->app);
9fd6b843
KS
114 ff_amf_write_string(&p, "connect");
115 ff_amf_write_number(&p, 1.0);
116 ff_amf_write_object_start(&p);
117 ff_amf_write_field_name(&p, "app");
5e9ad759 118 ff_amf_write_string(&p, rt->app);
9fd6b843 119
6bf22e18 120 if (rt->is_input) {
c7240611
KS
121 snprintf(ver, sizeof(ver), "%s %d,%d,%d,%d", RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1,
122 RTMP_CLIENT_VER2, RTMP_CLIENT_VER3, RTMP_CLIENT_VER4);
6bf22e18
S
123 } else {
124 snprintf(ver, sizeof(ver), "FMLE/3.0 (compatible; %s)", LIBAVFORMAT_IDENT);
125 ff_amf_write_field_name(&p, "type");
126 ff_amf_write_string(&p, "nonprivate");
127 }
9fd6b843
KS
128 ff_amf_write_field_name(&p, "flashVer");
129 ff_amf_write_string(&p, ver);
130 ff_amf_write_field_name(&p, "tcUrl");
131 ff_amf_write_string(&p, tcurl);
6bf22e18 132 if (rt->is_input) {
c7240611
KS
133 ff_amf_write_field_name(&p, "fpad");
134 ff_amf_write_bool(&p, 0);
135 ff_amf_write_field_name(&p, "capabilities");
136 ff_amf_write_number(&p, 15.0);
137 ff_amf_write_field_name(&p, "audioCodecs");
138 ff_amf_write_number(&p, 1639.0);
139 ff_amf_write_field_name(&p, "videoCodecs");
140 ff_amf_write_number(&p, 252.0);
141 ff_amf_write_field_name(&p, "videoFunction");
142 ff_amf_write_number(&p, 1.0);
6bf22e18 143 }
9fd6b843
KS
144 ff_amf_write_object_end(&p);
145
146 pkt.data_size = p - pkt.data;
147
148 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
f8caa544 149 ff_rtmp_packet_destroy(&pkt);
9fd6b843
KS
150}
151
152/**
49bd8e4b 153 * Generate 'releaseStream' call and send it to the server. It should make
6bf22e18
S
154 * the server release some channel for media streams.
155 */
156static void gen_release_stream(URLContext *s, RTMPContext *rt)
157{
158 RTMPPacket pkt;
159 uint8_t *p;
160
161 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0,
162 29 + strlen(rt->playpath));
163
7f804085 164 av_log(s, AV_LOG_DEBUG, "Releasing stream...\n");
6bf22e18
S
165 p = pkt.data;
166 ff_amf_write_string(&p, "releaseStream");
167 ff_amf_write_number(&p, 2.0);
168 ff_amf_write_null(&p);
169 ff_amf_write_string(&p, rt->playpath);
170
171 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
172 ff_rtmp_packet_destroy(&pkt);
173}
174
175/**
49bd8e4b 176 * Generate 'FCPublish' call and send it to the server. It should make
6bf22e18
S
177 * the server preapare for receiving media streams.
178 */
179static void gen_fcpublish_stream(URLContext *s, RTMPContext *rt)
180{
181 RTMPPacket pkt;
182 uint8_t *p;
183
184 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0,
185 25 + strlen(rt->playpath));
186
7f804085 187 av_log(s, AV_LOG_DEBUG, "FCPublish stream...\n");
6bf22e18
S
188 p = pkt.data;
189 ff_amf_write_string(&p, "FCPublish");
190 ff_amf_write_number(&p, 3.0);
191 ff_amf_write_null(&p);
192 ff_amf_write_string(&p, rt->playpath);
193
194 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
195 ff_rtmp_packet_destroy(&pkt);
196}
197
198/**
49bd8e4b 199 * Generate 'FCUnpublish' call and send it to the server. It should make
6bf22e18
S
200 * the server destroy stream.
201 */
202static void gen_fcunpublish_stream(URLContext *s, RTMPContext *rt)
203{
204 RTMPPacket pkt;
205 uint8_t *p;
206
207 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0,
208 27 + strlen(rt->playpath));
209
7f804085 210 av_log(s, AV_LOG_DEBUG, "UnPublishing stream...\n");
6bf22e18
S
211 p = pkt.data;
212 ff_amf_write_string(&p, "FCUnpublish");
213 ff_amf_write_number(&p, 5.0);
214 ff_amf_write_null(&p);
215 ff_amf_write_string(&p, rt->playpath);
216
217 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
218 ff_rtmp_packet_destroy(&pkt);
219}
220
221/**
49bd8e4b 222 * Generate 'createStream' call and send it to the server. It should make
9fd6b843
KS
223 * the server allocate some channel for media streams.
224 */
225static void gen_create_stream(URLContext *s, RTMPContext *rt)
226{
227 RTMPPacket pkt;
228 uint8_t *p;
229
7f804085 230 av_log(s, AV_LOG_DEBUG, "Creating stream...\n");
31da5966 231 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 25);
9fd6b843
KS
232
233 p = pkt.data;
234 ff_amf_write_string(&p, "createStream");
6bf22e18
S
235 ff_amf_write_number(&p, rt->is_input ? 3.0 : 4.0);
236 ff_amf_write_null(&p);
237
238 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
239 ff_rtmp_packet_destroy(&pkt);
240}
241
242
243/**
49bd8e4b 244 * Generate 'deleteStream' call and send it to the server. It should make
6bf22e18
S
245 * the server remove some channel for media streams.
246 */
247static void gen_delete_stream(URLContext *s, RTMPContext *rt)
248{
249 RTMPPacket pkt;
250 uint8_t *p;
251
7f804085 252 av_log(s, AV_LOG_DEBUG, "Deleting stream...\n");
6bf22e18
S
253 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 34);
254
255 p = pkt.data;
256 ff_amf_write_string(&p, "deleteStream");
257 ff_amf_write_number(&p, 0.0);
9fd6b843 258 ff_amf_write_null(&p);
6bf22e18 259 ff_amf_write_number(&p, rt->main_channel_id);
9fd6b843
KS
260
261 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
262 ff_rtmp_packet_destroy(&pkt);
263}
264
265/**
49bd8e4b 266 * Generate 'play' call and send it to the server, then ping the server
9fd6b843
KS
267 * to start actual playing.
268 */
269static void gen_play(URLContext *s, RTMPContext *rt)
270{
271 RTMPPacket pkt;
272 uint8_t *p;
273
7f804085 274 av_log(s, AV_LOG_DEBUG, "Sending play command for '%s'\n", rt->playpath);
9fd6b843 275 ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0,
f836fa17 276 20 + strlen(rt->playpath));
9fd6b843
KS
277 pkt.extra = rt->main_channel_id;
278
279 p = pkt.data;
280 ff_amf_write_string(&p, "play");
281 ff_amf_write_number(&p, 0.0);
282 ff_amf_write_null(&p);
283 ff_amf_write_string(&p, rt->playpath);
9fd6b843
KS
284
285 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
286 ff_rtmp_packet_destroy(&pkt);
287
288 // set client buffer time disguised in ping packet
289 ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, 1, 10);
290
291 p = pkt.data;
292 bytestream_put_be16(&p, 3);
293 bytestream_put_be32(&p, 1);
294 bytestream_put_be32(&p, 256); //TODO: what is a good value here?
295
296 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
297 ff_rtmp_packet_destroy(&pkt);
298}
299
300/**
49bd8e4b 301 * Generate 'publish' call and send it to the server.
6bf22e18
S
302 */
303static void gen_publish(URLContext *s, RTMPContext *rt)
304{
305 RTMPPacket pkt;
306 uint8_t *p;
307
7f804085 308 av_log(s, AV_LOG_DEBUG, "Sending publish command for '%s'\n", rt->playpath);
6bf22e18
S
309 ff_rtmp_packet_create(&pkt, RTMP_SOURCE_CHANNEL, RTMP_PT_INVOKE, 0,
310 30 + strlen(rt->playpath));
311 pkt.extra = rt->main_channel_id;
312
313 p = pkt.data;
314 ff_amf_write_string(&p, "publish");
315 ff_amf_write_number(&p, 0.0);
316 ff_amf_write_null(&p);
317 ff_amf_write_string(&p, rt->playpath);
318 ff_amf_write_string(&p, "live");
319
320 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
321 ff_rtmp_packet_destroy(&pkt);
322}
323
324/**
49bd8e4b 325 * Generate ping reply and send it to the server.
9fd6b843
KS
326 */
327static void gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
328{
329 RTMPPacket pkt;
330 uint8_t *p;
331
332 ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, ppkt->timestamp + 1, 6);
333 p = pkt.data;
334 bytestream_put_be16(&p, 7);
4aaebf78 335 bytestream_put_be32(&p, AV_RB32(ppkt->data+2));
9fd6b843
KS
336 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
337 ff_rtmp_packet_destroy(&pkt);
338}
339
bf7c1719 340/**
49bd8e4b 341 * Generate report on bytes read so far and send it to the server.
bf7c1719
KS
342 */
343static void gen_bytes_read(URLContext *s, RTMPContext *rt, uint32_t ts)
344{
345 RTMPPacket pkt;
346 uint8_t *p;
347
348 ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_BYTES_READ, ts, 4);
349 p = pkt.data;
350 bytestream_put_be32(&p, rt->bytes_read);
351 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
352 ff_rtmp_packet_destroy(&pkt);
353}
354
9fd6b843
KS
355//TODO: Move HMAC code somewhere. Eventually.
356#define HMAC_IPAD_VAL 0x36
357#define HMAC_OPAD_VAL 0x5C
358
359/**
49bd8e4b 360 * Calculate HMAC-SHA2 digest for RTMP handshake packets.
9fd6b843
KS
361 *
362 * @param src input buffer
363 * @param len input buffer length (should be 1536)
364 * @param gap offset in buffer where 32 bytes should not be taken into account
365 * when calculating digest (since it will be used to store that digest)
366 * @param key digest key
367 * @param keylen digest key length
368 * @param dst buffer where calculated digest will be stored (32 bytes)
369 */
370static void rtmp_calc_digest(const uint8_t *src, int len, int gap,
371 const uint8_t *key, int keylen, uint8_t *dst)
372{
373 struct AVSHA *sha;
374 uint8_t hmac_buf[64+32] = {0};
375 int i;
376
377 sha = av_mallocz(av_sha_size);
378
379 if (keylen < 64) {
380 memcpy(hmac_buf, key, keylen);
381 } else {
382 av_sha_init(sha, 256);
383 av_sha_update(sha,key, keylen);
384 av_sha_final(sha, hmac_buf);
385 }
386 for (i = 0; i < 64; i++)
387 hmac_buf[i] ^= HMAC_IPAD_VAL;
388
389 av_sha_init(sha, 256);
390 av_sha_update(sha, hmac_buf, 64);
391 if (gap <= 0) {
392 av_sha_update(sha, src, len);
393 } else { //skip 32 bytes used for storing digest
394 av_sha_update(sha, src, gap);
395 av_sha_update(sha, src + gap + 32, len - gap - 32);
396 }
397 av_sha_final(sha, hmac_buf + 64);
398
399 for (i = 0; i < 64; i++)
400 hmac_buf[i] ^= HMAC_IPAD_VAL ^ HMAC_OPAD_VAL; //reuse XORed key for opad
401 av_sha_init(sha, 256);
402 av_sha_update(sha, hmac_buf, 64+32);
403 av_sha_final(sha, dst);
404
405 av_free(sha);
406}
407
408/**
49bd8e4b 409 * Put HMAC-SHA2 digest of packet data (except for the bytes where this digest
9fd6b843
KS
410 * will be stored) into that packet.
411 *
412 * @param buf handshake data (1536 bytes)
413 * @return offset to the digest inside input data
414 */
415static int rtmp_handshake_imprint_with_digest(uint8_t *buf)
416{
417 int i, digest_pos = 0;
418
419 for (i = 8; i < 12; i++)
420 digest_pos += buf[i];
421 digest_pos = (digest_pos % 728) + 12;
422
423 rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
424 rtmp_player_key, PLAYER_KEY_OPEN_PART_LEN,
425 buf + digest_pos);
426 return digest_pos;
427}
428
429/**
49bd8e4b 430 * Verify that the received server response has the expected digest value.
9fd6b843
KS
431 *
432 * @param buf handshake data received from the server (1536 bytes)
433 * @param off position to search digest offset from
434 * @return 0 if digest is valid, digest position otherwise
435 */
436static int rtmp_validate_digest(uint8_t *buf, int off)
437{
438 int i, digest_pos = 0;
439 uint8_t digest[32];
440
441 for (i = 0; i < 4; i++)
442 digest_pos += buf[i + off];
443 digest_pos = (digest_pos % 728) + off + 4;
444
445 rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
446 rtmp_server_key, SERVER_KEY_OPEN_PART_LEN,
447 digest);
448 if (!memcmp(digest, buf + digest_pos, 32))
449 return digest_pos;
450 return 0;
451}
452
453/**
49bd8e4b 454 * Perform handshake with the server by means of exchanging pseudorandom data
9fd6b843
KS
455 * signed with HMAC-SHA2 digest.
456 *
457 * @return 0 if handshake succeeds, negative value otherwise
458 */
459static int rtmp_handshake(URLContext *s, RTMPContext *rt)
460{
461 AVLFG rnd;
462 uint8_t tosend [RTMP_HANDSHAKE_PACKET_SIZE+1] = {
463 3, // unencrypted data
464 0, 0, 0, 0, // client uptime
465 RTMP_CLIENT_VER1,
466 RTMP_CLIENT_VER2,
467 RTMP_CLIENT_VER3,
468 RTMP_CLIENT_VER4,
469 };
470 uint8_t clientdata[RTMP_HANDSHAKE_PACKET_SIZE];
471 uint8_t serverdata[RTMP_HANDSHAKE_PACKET_SIZE+1];
472 int i;
473 int server_pos, client_pos;
474 uint8_t digest[32];
475
7f804085 476 av_log(s, AV_LOG_DEBUG, "Handshaking...\n");
9fd6b843
KS
477
478 av_lfg_init(&rnd, 0xDEADC0DE);
479 // generate handshake packet - 1536 bytes of pseudorandom data
480 for (i = 9; i <= RTMP_HANDSHAKE_PACKET_SIZE; i++)
481 tosend[i] = av_lfg_get(&rnd) >> 24;
482 client_pos = rtmp_handshake_imprint_with_digest(tosend + 1);
483
925e908b 484 ffurl_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE + 1);
dce37564 485 i = ffurl_read_complete(rt->stream, serverdata, RTMP_HANDSHAKE_PACKET_SIZE + 1);
9fd6b843 486 if (i != RTMP_HANDSHAKE_PACKET_SIZE + 1) {
7f804085 487 av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
9fd6b843
KS
488 return -1;
489 }
dce37564 490 i = ffurl_read_complete(rt->stream, clientdata, RTMP_HANDSHAKE_PACKET_SIZE);
9fd6b843 491 if (i != RTMP_HANDSHAKE_PACKET_SIZE) {
7f804085 492 av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
9fd6b843
KS
493 return -1;
494 }
495
7f804085 496 av_log(s, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n",
9fd6b843
KS
497 serverdata[5], serverdata[6], serverdata[7], serverdata[8]);
498
e2ee11e8 499 if (rt->is_input && serverdata[5] >= 3) {
c7240611 500 server_pos = rtmp_validate_digest(serverdata + 1, 772);
9fd6b843 501 if (!server_pos) {
c7240611
KS
502 server_pos = rtmp_validate_digest(serverdata + 1, 8);
503 if (!server_pos) {
7f804085 504 av_log(s, AV_LOG_ERROR, "Server response validating failed\n");
c7240611
KS
505 return -1;
506 }
9fd6b843 507 }
9fd6b843 508
c7240611
KS
509 rtmp_calc_digest(tosend + 1 + client_pos, 32, 0,
510 rtmp_server_key, sizeof(rtmp_server_key),
511 digest);
512 rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE-32, 0,
513 digest, 32,
514 digest);
515 if (memcmp(digest, clientdata + RTMP_HANDSHAKE_PACKET_SIZE - 32, 32)) {
7f804085 516 av_log(s, AV_LOG_ERROR, "Signature mismatch\n");
c7240611
KS
517 return -1;
518 }
9fd6b843 519
c7240611
KS
520 for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++)
521 tosend[i] = av_lfg_get(&rnd) >> 24;
522 rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0,
523 rtmp_player_key, sizeof(rtmp_player_key),
524 digest);
525 rtmp_calc_digest(tosend, RTMP_HANDSHAKE_PACKET_SIZE - 32, 0,
526 digest, 32,
527 tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
528
529 // write reply back to the server
925e908b 530 ffurl_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE);
6bf22e18 531 } else {
925e908b 532 ffurl_write(rt->stream, serverdata+1, RTMP_HANDSHAKE_PACKET_SIZE);
6bf22e18
S
533 }
534
9fd6b843
KS
535 return 0;
536}
537
538/**
49bd8e4b 539 * Parse received packet and possibly perform some action depending on
9fd6b843
KS
540 * the packet contents.
541 * @return 0 for no errors, negative values for serious errors which prevent
542 * further communications, positive values for uncritical errors
543 */
544static int rtmp_parse_result(URLContext *s, RTMPContext *rt, RTMPPacket *pkt)
545{
546 int i, t;
547 const uint8_t *data_end = pkt->data + pkt->data_size;
548
cfac91fe 549#ifdef DEBUG
7f804085 550 ff_rtmp_packet_dump(s, pkt);
cfac91fe
KS
551#endif
552
9fd6b843
KS
553 switch (pkt->type) {
554 case RTMP_PT_CHUNK_SIZE:
555 if (pkt->data_size != 4) {
7f804085 556 av_log(s, AV_LOG_ERROR,
9fd6b843
KS
557 "Chunk size change packet is not 4 bytes long (%d)\n", pkt->data_size);
558 return -1;
559 }
6bf22e18
S
560 if (!rt->is_input)
561 ff_rtmp_packet_write(rt->stream, pkt, rt->chunk_size, rt->prev_pkt[1]);
9fd6b843
KS
562 rt->chunk_size = AV_RB32(pkt->data);
563 if (rt->chunk_size <= 0) {
7f804085 564 av_log(s, AV_LOG_ERROR, "Incorrect chunk size %d\n", rt->chunk_size);
9fd6b843
KS
565 return -1;
566 }
7f804085 567 av_log(s, AV_LOG_DEBUG, "New chunk size = %d\n", rt->chunk_size);
9fd6b843
KS
568 break;
569 case RTMP_PT_PING:
570 t = AV_RB16(pkt->data);
571 if (t == 6)
572 gen_pong(s, rt, pkt);
573 break;
bf7c1719
KS
574 case RTMP_PT_CLIENT_BW:
575 if (pkt->data_size < 4) {
7f804085 576 av_log(s, AV_LOG_ERROR,
bf7c1719
KS
577 "Client bandwidth report packet is less than 4 bytes long (%d)\n",
578 pkt->data_size);
579 return -1;
580 }
7f804085 581 av_log(s, AV_LOG_DEBUG, "Client bandwidth = %d\n", AV_RB32(pkt->data));
bf7c1719
KS
582 rt->client_report_size = AV_RB32(pkt->data) >> 1;
583 break;
9fd6b843
KS
584 case RTMP_PT_INVOKE:
585 //TODO: check for the messages sent for wrong state?
586 if (!memcmp(pkt->data, "\002\000\006_error", 9)) {
587 uint8_t tmpstr[256];
588
589 if (!ff_amf_get_field_value(pkt->data + 9, data_end,
590 "description", tmpstr, sizeof(tmpstr)))
7f804085 591 av_log(s, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
9fd6b843
KS
592 return -1;
593 } else if (!memcmp(pkt->data, "\002\000\007_result", 10)) {
594 switch (rt->state) {
595 case STATE_HANDSHAKED:
6bf22e18
S
596 if (!rt->is_input) {
597 gen_release_stream(s, rt);
598 gen_fcpublish_stream(s, rt);
599 rt->state = STATE_RELEASING;
600 } else {
601 rt->state = STATE_CONNECTING;
602 }
9fd6b843 603 gen_create_stream(s, rt);
6bf22e18
S
604 break;
605 case STATE_FCPUBLISH:
9fd6b843
KS
606 rt->state = STATE_CONNECTING;
607 break;
6bf22e18
S
608 case STATE_RELEASING:
609 rt->state = STATE_FCPUBLISH;
610 /* hack for Wowza Media Server, it does not send result for
611 * releaseStream and FCPublish calls */
612 if (!pkt->data[10]) {
613 int pkt_id = (int) av_int2dbl(AV_RB64(pkt->data + 11));
614 if (pkt_id == 4)
615 rt->state = STATE_CONNECTING;
616 }
e07c92e4 617 if (rt->state != STATE_CONNECTING)
6bf22e18 618 break;
9fd6b843
KS
619 case STATE_CONNECTING:
620 //extract a number from the result
621 if (pkt->data[10] || pkt->data[19] != 5 || pkt->data[20]) {
7f804085 622 av_log(s, AV_LOG_WARNING, "Unexpected reply on connect()\n");
9fd6b843
KS
623 } else {
624 rt->main_channel_id = (int) av_int2dbl(AV_RB64(pkt->data + 21));
625 }
6bf22e18 626 if (rt->is_input) {
c7240611 627 gen_play(s, rt);
6bf22e18
S
628 } else {
629 gen_publish(s, rt);
630 }
9fd6b843
KS
631 rt->state = STATE_READY;
632 break;
633 }
634 } else if (!memcmp(pkt->data, "\002\000\010onStatus", 11)) {
635 const uint8_t* ptr = pkt->data + 11;
636 uint8_t tmpstr[256];
9fd6b843
KS
637
638 for (i = 0; i < 2; i++) {
639 t = ff_amf_tag_size(ptr, data_end);
640 if (t < 0)
641 return 1;
642 ptr += t;
643 }
644 t = ff_amf_get_field_value(ptr, data_end,
645 "level", tmpstr, sizeof(tmpstr));
646 if (!t && !strcmp(tmpstr, "error")) {
647 if (!ff_amf_get_field_value(ptr, data_end,
648 "description", tmpstr, sizeof(tmpstr)))
7f804085 649 av_log(s, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
9fd6b843
KS
650 return -1;
651 }
652 t = ff_amf_get_field_value(ptr, data_end,
653 "code", tmpstr, sizeof(tmpstr));
6bf22e18 654 if (!t && !strcmp(tmpstr, "NetStream.Play.Start")) rt->state = STATE_PLAYING;
72b870b9
MS
655 if (!t && !strcmp(tmpstr, "NetStream.Play.Stop")) rt->state = STATE_STOPPED;
656 if (!t && !strcmp(tmpstr, "NetStream.Play.UnpublishNotify")) rt->state = STATE_STOPPED;
6bf22e18 657 if (!t && !strcmp(tmpstr, "NetStream.Publish.Start")) rt->state = STATE_PUBLISHING;
9fd6b843
KS
658 }
659 break;
660 }
661 return 0;
662}
663
664/**
49bd8e4b 665 * Interact with the server by receiving and sending RTMP packets until
9fd6b843
KS
666 * there is some significant data (media data or expected status notification).
667 *
668 * @param s reading context
1d8041b3
SS
669 * @param for_header non-zero value tells function to work until it
670 * gets notification from the server that playing has been started,
671 * otherwise function will work until some media data is received (or
672 * an error happens)
9fd6b843
KS
673 * @return 0 for successful operation, negative value in case of error
674 */
675static int get_packet(URLContext *s, int for_header)
676{
677 RTMPContext *rt = s->priv_data;
678 int ret;
56e29bf2
S
679 uint8_t *p;
680 const uint8_t *next;
681 uint32_t data_size;
682 uint32_t ts, cts, pts=0;
9fd6b843 683
72b870b9
MS
684 if (rt->state == STATE_STOPPED)
685 return AVERROR_EOF;
686
e07c92e4 687 for (;;) {
271c869c 688 RTMPPacket rpkt = { 0 };
9fd6b843 689 if ((ret = ff_rtmp_packet_read(rt->stream, &rpkt,
adb54961 690 rt->chunk_size, rt->prev_pkt[0])) <= 0) {
b381a823 691 if (ret == 0) {
9fd6b843
KS
692 return AVERROR(EAGAIN);
693 } else {
694 return AVERROR(EIO);
695 }
696 }
bf7c1719
KS
697 rt->bytes_read += ret;
698 if (rt->bytes_read > rt->last_bytes_read + rt->client_report_size) {
7f804085 699 av_log(s, AV_LOG_DEBUG, "Sending bytes read report\n");
bf7c1719
KS
700 gen_bytes_read(s, rt, rpkt.timestamp + 1);
701 rt->last_bytes_read = rt->bytes_read;
702 }
9fd6b843
KS
703
704 ret = rtmp_parse_result(s, rt, &rpkt);
705 if (ret < 0) {//serious error in current packet
706 ff_rtmp_packet_destroy(&rpkt);
707 return -1;
708 }
72b870b9
MS
709 if (rt->state == STATE_STOPPED) {
710 ff_rtmp_packet_destroy(&rpkt);
711 return AVERROR_EOF;
712 }
6bf22e18 713 if (for_header && (rt->state == STATE_PLAYING || rt->state == STATE_PUBLISHING)) {
9fd6b843
KS
714 ff_rtmp_packet_destroy(&rpkt);
715 return 0;
716 }
6bf22e18 717 if (!rpkt.data_size || !rt->is_input) {
9fd6b843
KS
718 ff_rtmp_packet_destroy(&rpkt);
719 continue;
720 }
721 if (rpkt.type == RTMP_PT_VIDEO || rpkt.type == RTMP_PT_AUDIO ||
afbacb93 722 (rpkt.type == RTMP_PT_NOTIFY && !memcmp("\002\000\012onMetaData", rpkt.data, 13))) {
56e29bf2 723 ts = rpkt.timestamp;
9fd6b843 724
9fd6b843
KS
725 // generate packet header and put data into buffer for FLV demuxer
726 rt->flv_off = 0;
727 rt->flv_size = rpkt.data_size + 15;
728 rt->flv_data = p = av_realloc(rt->flv_data, rt->flv_size);
729 bytestream_put_byte(&p, rpkt.type);
730 bytestream_put_be24(&p, rpkt.data_size);
731 bytestream_put_be24(&p, ts);
732 bytestream_put_byte(&p, ts >> 24);
733 bytestream_put_be24(&p, 0);
734 bytestream_put_buffer(&p, rpkt.data, rpkt.data_size);
735 bytestream_put_be32(&p, 0);
736 ff_rtmp_packet_destroy(&rpkt);
737 return 0;
738 } else if (rpkt.type == RTMP_PT_METADATA) {
739 // we got raw FLV data, make it available for FLV demuxer
740 rt->flv_off = 0;
741 rt->flv_size = rpkt.data_size;
742 rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
56e29bf2
S
743 /* rewrite timestamps */
744 next = rpkt.data;
745 ts = rpkt.timestamp;
746 while (next - rpkt.data < rpkt.data_size - 11) {
747 next++;
748 data_size = bytestream_get_be24(&next);
749 p=next;
750 cts = bytestream_get_be24(&next);
aae9a093 751 cts |= bytestream_get_byte(&next) << 24;
56e29bf2
S
752 if (pts==0)
753 pts=cts;
754 ts += cts - pts;
755 pts = cts;
756 bytestream_put_be24(&p, ts);
757 bytestream_put_byte(&p, ts >> 24);
758 next += data_size + 3 + 4;
759 }
9fd6b843
KS
760 memcpy(rt->flv_data, rpkt.data, rpkt.data_size);
761 ff_rtmp_packet_destroy(&rpkt);
762 return 0;
763 }
764 ff_rtmp_packet_destroy(&rpkt);
765 }
9fd6b843
KS
766}
767
768static int rtmp_close(URLContext *h)
769{
770 RTMPContext *rt = h->priv_data;
771
e07c92e4 772 if (!rt->is_input) {
6bf22e18
S
773 rt->flv_data = NULL;
774 if (rt->out_pkt.data_size)
775 ff_rtmp_packet_destroy(&rt->out_pkt);
615c2879
S
776 if (rt->state > STATE_FCPUBLISH)
777 gen_fcunpublish_stream(h, rt);
6bf22e18 778 }
615c2879
S
779 if (rt->state > STATE_HANDSHAKED)
780 gen_delete_stream(h, rt);
6bf22e18 781
9fd6b843 782 av_freep(&rt->flv_data);
e52a9145 783 ffurl_close(rt->stream);
9fd6b843
KS
784 av_free(rt);
785 return 0;
786}
787
788/**
49bd8e4b 789 * Open RTMP connection and verify that the stream can be played.
9fd6b843
KS
790 *
791 * URL syntax: rtmp://server[:port][/app][/playpath]
792 * where 'app' is first one or two directories in the path
793 * (e.g. /ondemand/, /flash/live/, etc.)
794 * and 'playpath' is a file name (the rest of the path,
795 * may be prefixed with "mp4:")
796 */
797static int rtmp_open(URLContext *s, const char *uri, int flags)
798{
799 RTMPContext *rt;
5e9ad759 800 char proto[8], hostname[256], path[1024], *fname;
9fd6b843 801 uint8_t buf[2048];
b316991b 802 int port;
9fd6b843
KS
803 int ret;
804
9fd6b843
KS
805 rt = av_mallocz(sizeof(RTMPContext));
806 if (!rt)
807 return AVERROR(ENOMEM);
808 s->priv_data = rt;
59d96941 809 rt->is_input = !(flags & AVIO_FLAG_WRITE);
9fd6b843 810
f3bfe388 811 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
f984dcf6 812 path, sizeof(path), s->filename);
9fd6b843
KS
813
814 if (port < 0)
815 port = RTMP_DEFAULT_PORT;
57b5555c 816 ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
9fd6b843 817
59d96941
SS
818 if (ffurl_open(&rt->stream, buf, AVIO_FLAG_READ_WRITE) < 0) {
819 av_log(s , AV_LOG_ERROR, "Cannot open connection %s\n", buf);
9fd6b843 820 goto fail;
fe523958 821 }
9fd6b843 822
c7240611
KS
823 rt->state = STATE_START;
824 if (rtmp_handshake(s, rt))
825 return -1;
9fd6b843 826
c7240611
KS
827 rt->chunk_size = 128;
828 rt->state = STATE_HANDSHAKED;
829 //extract "app" part from path
830 if (!strncmp(path, "/ondemand/", 10)) {
831 fname = path + 10;
832 memcpy(rt->app, "ondemand", 9);
833 } else {
834 char *p = strchr(path + 1, '/');
835 if (!p) {
836 fname = path + 1;
837 rt->app[0] = '\0';
9fd6b843 838 } else {
c7240611
KS
839 char *c = strchr(p + 1, ':');
840 fname = strchr(p + 1, '/');
841 if (!fname || c < fname) {
842 fname = p + 1;
843 av_strlcpy(rt->app, path + 1, p - path);
9fd6b843 844 } else {
c7240611
KS
845 fname++;
846 av_strlcpy(rt->app, path + 1, fname - path - 1);
9fd6b843
KS
847 }
848 }
c7240611
KS
849 }
850 if (!strchr(fname, ':') &&
851 (!strcmp(fname + strlen(fname) - 4, ".f4v") ||
852 !strcmp(fname + strlen(fname) - 4, ".mp4"))) {
853 memcpy(rt->playpath, "mp4:", 5);
854 } else {
855 rt->playpath[0] = 0;
856 }
857 strncat(rt->playpath, fname, sizeof(rt->playpath) - 5);
9fd6b843 858
bf7c1719
KS
859 rt->client_report_size = 1048576;
860 rt->bytes_read = 0;
861 rt->last_bytes_read = 0;
862
7f804085 863 av_log(s, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n",
c7240611
KS
864 proto, path, rt->app, rt->playpath);
865 gen_connect(s, rt, proto, hostname, port);
9fd6b843 866
c7240611
KS
867 do {
868 ret = get_packet(s, 1);
869 } while (ret == EAGAIN);
870 if (ret < 0)
871 goto fail;
6bf22e18
S
872
873 if (rt->is_input) {
9fd6b843
KS
874 // generate FLV header for demuxer
875 rt->flv_size = 13;
876 rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
877 rt->flv_off = 0;
878 memcpy(rt->flv_data, "FLV\1\5\0\0\0\011\0\0\0\0", rt->flv_size);
6bf22e18
S
879 } else {
880 rt->flv_size = 0;
881 rt->flv_data = NULL;
882 rt->flv_off = 0;
9fd6b843
KS
883 }
884
5958df34 885 s->max_packet_size = rt->stream->max_packet_size;
9fd6b843
KS
886 s->is_streamed = 1;
887 return 0;
888
889fail:
890 rtmp_close(s);
891 return AVERROR(EIO);
892}
893
894static int rtmp_read(URLContext *s, uint8_t *buf, int size)
895{
896 RTMPContext *rt = s->priv_data;
897 int orig_size = size;
898 int ret;
899
900 while (size > 0) {
901 int data_left = rt->flv_size - rt->flv_off;
902
903 if (data_left >= size) {
904 memcpy(buf, rt->flv_data + rt->flv_off, size);
905 rt->flv_off += size;
906 return orig_size;
907 }
908 if (data_left > 0) {
909 memcpy(buf, rt->flv_data + rt->flv_off, data_left);
910 buf += data_left;
911 size -= data_left;
912 rt->flv_off = rt->flv_size;
e8ccf245 913 return data_left;
9fd6b843
KS
914 }
915 if ((ret = get_packet(s, 0)) < 0)
916 return ret;
917 }
918 return orig_size;
919}
920
9ad4c65f 921static int rtmp_write(URLContext *s, const uint8_t *buf, int size)
9fd6b843 922{
9ad4c65f 923 RTMPContext *rt = s->priv_data;
6bf22e18
S
924 int size_temp = size;
925 int pktsize, pkttype;
926 uint32_t ts;
927 const uint8_t *buf_temp = buf;
928
3ffe32eb
MS
929 if (rt->skip_bytes) {
930 int skip = FFMIN(rt->skip_bytes, size);
931 buf_temp += skip;
932 size_temp -= skip;
933 rt->skip_bytes -= skip;
934 if (size_temp <= 0)
935 return size;
936 }
937
938 if (!rt->flv_off && size_temp < 11) {
7f804085 939 av_log(s, AV_LOG_DEBUG, "FLV packet too small %d\n", size);
6bf22e18
S
940 return 0;
941 }
942
943 do {
944 if (!rt->flv_off) {
945 //skip flv header
946 if (buf_temp[0] == 'F' && buf_temp[1] == 'L' && buf_temp[2] == 'V') {
947 buf_temp += 9 + 4;
948 size_temp -= 9 + 4;
949 }
950
951 pkttype = bytestream_get_byte(&buf_temp);
952 pktsize = bytestream_get_be24(&buf_temp);
953 ts = bytestream_get_be24(&buf_temp);
954 ts |= bytestream_get_byte(&buf_temp) << 24;
955 bytestream_get_be24(&buf_temp);
956 size_temp -= 11;
957 rt->flv_size = pktsize;
958
959 //force 12bytes header
960 if (((pkttype == RTMP_PT_VIDEO || pkttype == RTMP_PT_AUDIO) && ts == 0) ||
961 pkttype == RTMP_PT_NOTIFY) {
962 if (pkttype == RTMP_PT_NOTIFY)
963 pktsize += 16;
964 rt->prev_pkt[1][RTMP_SOURCE_CHANNEL].channel_id = 0;
965 }
966
967 //this can be a big packet, it's better to send it right here
968 ff_rtmp_packet_create(&rt->out_pkt, RTMP_SOURCE_CHANNEL, pkttype, ts, pktsize);
969 rt->out_pkt.extra = rt->main_channel_id;
970 rt->flv_data = rt->out_pkt.data;
971
972 if (pkttype == RTMP_PT_NOTIFY)
973 ff_amf_write_string(&rt->flv_data, "@setDataFrame");
974 }
975
976 if (rt->flv_size - rt->flv_off > size_temp) {
977 bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, size_temp);
978 rt->flv_off += size_temp;
a14c7842 979 size_temp = 0;
6bf22e18
S
980 } else {
981 bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, rt->flv_size - rt->flv_off);
a14c7842 982 size_temp -= rt->flv_size - rt->flv_off;
6bf22e18
S
983 rt->flv_off += rt->flv_size - rt->flv_off;
984 }
985
986 if (rt->flv_off == rt->flv_size) {
3ffe32eb
MS
987 if (size_temp < 4) {
988 rt->skip_bytes = 4 - size_temp;
989 buf_temp += size_temp;
990 size_temp = 0;
991 } else {
992 bytestream_get_be32(&buf_temp);
993 size_temp -= 4;
994 }
6bf22e18
S
995 ff_rtmp_packet_write(rt->stream, &rt->out_pkt, rt->chunk_size, rt->prev_pkt[1]);
996 ff_rtmp_packet_destroy(&rt->out_pkt);
997 rt->flv_size = 0;
998 rt->flv_off = 0;
999 }
a14c7842 1000 } while (buf_temp - buf < size);
6bf22e18 1001 return size;
9fd6b843
KS
1002}
1003
c6610a21 1004URLProtocol ff_rtmp_protocol = {
f35ff97f
AK
1005 .name = "rtmp",
1006 .url_open = rtmp_open,
1007 .url_read = rtmp_read,
1008 .url_write = rtmp_write,
1009 .url_close = rtmp_close,
9fd6b843 1010};