rtmpproto.c 105 KB
Newer Older
1 2
/*
 * RTMP network protocol
3
 * Copyright (c) 2009 Konstantin Shishkov
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
23
 * @file
24 25 26 27 28
 * RTMP protocol
 */

#include "libavcodec/bytestream.h"
#include "libavutil/avstring.h"
29
#include "libavutil/base64.h"
30
#include "libavutil/intfloat.h"
31
#include "libavutil/lfg.h"
32
#include "libavutil/md5.h"
33
#include "libavutil/opt.h"
34
#include "libavutil/random_seed.h"
35
#include "avformat.h"
36
#include "internal.h"
37 38 39 40 41

#include "network.h"

#include "flv.h"
#include "rtmp.h"
Samuel Pitoiset's avatar
Samuel Pitoiset committed
42
#include "rtmpcrypt.h"
43
#include "rtmppkt.h"
44
#include "url.h"
45

46 47 48 49
#if CONFIG_ZLIB
#include <zlib.h>
#endif

50
#define APP_MAX_LENGTH 1024
51
#define TCURL_MAX_LENGTH 1024
52
#define FLASHVER_MAX_LENGTH 64
53
#define RTMP_PKTDATA_DEFAULT_SIZE 4096
54
#define RTMP_HEADER 11
55

56 57 58 59
/** RTMP protocol handler state */
typedef enum {
    STATE_START,      ///< client has not done anything yet
    STATE_HANDSHAKED, ///< client has performed handshake
60
    STATE_FCPUBLISH,  ///< client FCPublishing stream (for output)
61
    STATE_PLAYING,    ///< client has started receiving multimedia data from server
62
    STATE_SEEKING,    ///< client has started the seek operation. Back on STATE_PLAYING when the time comes
63
    STATE_PUBLISHING, ///< client has started sending multimedia data to server (for output)
64
    STATE_RECEIVING,  ///< received a publish command (for input)
65
    STATE_SENDING,    ///< received a play command (for output)
66
    STATE_STOPPED,    ///< the broadcast has been stopped
67 68
} ClientState;

69 70 71 72 73
typedef struct TrackedMethod {
    char *name;
    int id;
} TrackedMethod;

74 75
/** protocol handler context */
typedef struct RTMPContext {
76
    const AVClass *class;
77
    URLContext*   stream;                     ///< TCP stream used in interactions with RTMP server
78 79
    RTMPPacket    *prev_pkt[2];               ///< packet history used when reading and sending packets ([0] for reading, [1] for writing)
    int           nb_prev_pkt[2];             ///< number of elements in prev_pkt
80 81
    int           in_chunk_size;              ///< size of the chunks incoming RTMP packets are divided into
    int           out_chunk_size;             ///< size of the chunks outgoing RTMP packets are divided into
82
    int           is_input;                   ///< input/output flag
83
    char          *playpath;                  ///< stream identifier to play (with possible "mp4:" prefix)
84
    int           live;                       ///< 0: recorded, -1: live, -2: both
85
    char          *app;                       ///< name of application
86
    char          *conn;                      ///< append arbitrary AMF data to the Connect message
87
    ClientState   state;                      ///< current state
88
    int           stream_id;                  ///< ID assigned by the server for the stream
89 90 91
    uint8_t*      flv_data;                   ///< buffer with data for demuxer
    int           flv_size;                   ///< current buffer size
    int           flv_off;                    ///< number of bytes read from current buffer
92
    int           flv_nb_packets;             ///< number of flv packets published
93
    RTMPPacket    out_pkt;                    ///< rtmp packet, created from flv a/v or metadata (for output)
94
    uint32_t      receive_report_size;        ///< number of bytes after which we should report the number of received bytes to the peer
95 96
    uint64_t      bytes_read;                 ///< number of bytes read from server
    uint64_t      last_bytes_read;            ///< number of bytes read last reported to server
97
    uint32_t      last_timestamp;             ///< last timestamp received in a packet
98
    int           skip_bytes;                 ///< number of bytes to skip from the input FLV stream in the next write call
99 100 101
    int           has_audio;                  ///< presence of audio data
    int           has_video;                  ///< presence of video data
    int           received_metadata;          ///< Indicates if we have received metadata about the streams
102
    uint8_t       flv_header[RTMP_HEADER];    ///< partial incoming flv packet header
103
    int           flv_header_bytes;           ///< number of initialized bytes in flv_header
104
    int           nb_invokes;                 ///< keeps track of invoke messages
105
    char*         tcurl;                      ///< url of the target stream
106
    char*         flashver;                   ///< version of the flash plugin
107 108 109
    char*         swfhash;                    ///< SHA256 hash of the decompressed SWF file (32 bytes)
    int           swfhash_len;                ///< length of the SHA256 hash
    int           swfsize;                    ///< size of the decompressed SWF file
110
    char*         swfurl;                     ///< url of the swf player
111
    char*         swfverify;                  ///< URL to player swf file, compute hash/size automatically
112
    char          swfverification[42];        ///< hash of the SWF verification
113
    char*         pageurl;                    ///< url of the web page
114
    char*         subscribe;                  ///< name of live stream to subscribe
115
    int           max_sent_unacked;           ///< max unacked sent bytes
116
    int           client_buffer_time;         ///< client buffer time in ms
117
    int           flush_interval;             ///< number of packets flushed in the same request (RTMPT only)
Samuel Pitoiset's avatar
Samuel Pitoiset committed
118
    int           encrypted;                  ///< use an encrypted connection (RTMPE only)
119 120 121
    TrackedMethod*tracked_methods;            ///< tracked methods buffer
    int           nb_tracked_methods;         ///< number of tracked methods
    int           tracked_methods_size;       ///< size of the tracked methods buffer
122 123 124
    int           listen;                     ///< listen mode flag
    int           listen_timeout;             ///< listen timeout to wait for new connections
    int           nb_streamid;                ///< The next stream id to return on createStream calls
125
    double        duration;                   ///< Duration of the stream in seconds as returned by the server (only valid if non-zero)
126 127 128 129 130
    char          username[50];
    char          password[50];
    char          auth_params[500];
    int           do_reconnect;
    int           auth_tried;
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
} RTMPContext;

#define PLAYER_KEY_OPEN_PART_LEN 30   ///< length of partial key used for first client digest signing
/** Client key used for digest signing */
static const uint8_t rtmp_player_key[] = {
    'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
    'F', 'l', 'a', 's', 'h', ' ', 'P', 'l', 'a', 'y', 'e', 'r', ' ', '0', '0', '1',

    0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
    0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
    0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
};

#define SERVER_KEY_OPEN_PART_LEN 36   ///< length of partial key used for first server digest signing
/** Key used for RTMP server digest signing */
static const uint8_t rtmp_server_key[] = {
    'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
    'F', 'l', 'a', 's', 'h', ' ', 'M', 'e', 'd', 'i', 'a', ' ',
    'S', 'e', 'r', 'v', 'e', 'r', ' ', '0', '0', '1',

    0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
    0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
    0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
};

156
static int handle_chunk_size(URLContext *s, RTMPPacket *pkt);
James Almer's avatar
James Almer committed
157 158
static int handle_window_ack_size(URLContext *s, RTMPPacket *pkt);
static int handle_set_peer_bw(URLContext *s, RTMPPacket *pkt);
159

160 161
static int add_tracked_method(RTMPContext *rt, const char *name, int id)
{
162
    int err;
163 164 165

    if (rt->nb_tracked_methods + 1 > rt->tracked_methods_size) {
        rt->tracked_methods_size = (rt->nb_tracked_methods + 1) * 2;
166
        if ((err = av_reallocp(&rt->tracked_methods, rt->tracked_methods_size *
167 168 169
                               sizeof(*rt->tracked_methods))) < 0) {
            rt->nb_tracked_methods = 0;
            rt->tracked_methods_size = 0;
170
            return err;
171
        }
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    }

    rt->tracked_methods[rt->nb_tracked_methods].name = av_strdup(name);
    if (!rt->tracked_methods[rt->nb_tracked_methods].name)
        return AVERROR(ENOMEM);
    rt->tracked_methods[rt->nb_tracked_methods].id = id;
    rt->nb_tracked_methods++;

    return 0;
}

static void del_tracked_method(RTMPContext *rt, int index)
{
    memmove(&rt->tracked_methods[index], &rt->tracked_methods[index + 1],
            sizeof(*rt->tracked_methods) * (rt->nb_tracked_methods - index - 1));
    rt->nb_tracked_methods--;
}

190 191 192 193 194 195 196 197 198
static int find_tracked_method(URLContext *s, RTMPPacket *pkt, int offset,
                               char **tracked_method)
{
    RTMPContext *rt = s->priv_data;
    GetByteContext gbc;
    double pkt_id;
    int ret;
    int i;

199
    bytestream2_init(&gbc, pkt->data + offset, pkt->size - offset);
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    if ((ret = ff_amf_read_number(&gbc, &pkt_id)) < 0)
        return ret;

    for (i = 0; i < rt->nb_tracked_methods; i++) {
        if (rt->tracked_methods[i].id != pkt_id)
            continue;

        *tracked_method = rt->tracked_methods[i].name;
        del_tracked_method(rt, i);
        break;
    }

    return 0;
}

215 216 217 218 219
static void free_tracked_methods(RTMPContext *rt)
{
    int i;

    for (i = 0; i < rt->nb_tracked_methods; i ++)
220 221
        av_freep(&rt->tracked_methods[i].name);
    av_freep(&rt->tracked_methods);
222 223
    rt->tracked_methods_size = 0;
    rt->nb_tracked_methods   = 0;
224 225 226 227 228 229 230 231 232 233 234 235
}

static int rtmp_send_packet(RTMPContext *rt, RTMPPacket *pkt, int track)
{
    int ret;

    if (pkt->type == RTMP_PT_INVOKE && track) {
        GetByteContext gbc;
        char name[128];
        double pkt_id;
        int len;

236
        bytestream2_init(&gbc, pkt->data, pkt->size);
237 238 239 240 241 242 243 244 245 246
        if ((ret = ff_amf_read_string(&gbc, name, sizeof(name), &len)) < 0)
            goto fail;

        if ((ret = ff_amf_read_number(&gbc, &pkt_id)) < 0)
            goto fail;

        if ((ret = add_tracked_method(rt, name, pkt_id)) < 0)
            goto fail;
    }

247
    ret = ff_rtmp_packet_write(rt->stream, pkt, rt->out_chunk_size,
248
                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
249 250 251 252 253
fail:
    ff_rtmp_packet_destroy(pkt);
    return ret;
}

254 255
static int rtmp_write_amf_data(URLContext *s, char *param, uint8_t **p)
{
256
    char *field, *value;
257 258 259 260 261 262 263 264 265 266 267 268 269 270
    char type;

    /* The type must be B for Boolean, N for number, S for string, O for
     * object, or Z for null. For Booleans the data must be either 0 or 1 for
     * FALSE or TRUE, respectively. Likewise for Objects the data must be
     * 0 or 1 to end or begin an object, respectively. Data items in subobjects
     * may be named, by prefixing the type with 'N' and specifying the name
     * before the value (ie. NB:myFlag:1). This option may be used multiple times
     * to construct arbitrary AMF sequences. */
    if (param[0] && param[1] == ':') {
        type = param[0];
        value = param + 2;
    } else if (param[0] == 'N' && param[1] && param[2] == ':') {
        type = param[1];
271 272 273 274 275 276
        field = param + 3;
        value = strchr(field, ':');
        if (!value)
            goto fail;
        *value = '\0';
        value++;
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

        ff_amf_write_field_name(p, field);
    } else {
        goto fail;
    }

    switch (type) {
    case 'B':
        ff_amf_write_bool(p, value[0] != '0');
        break;
    case 'S':
        ff_amf_write_string(p, value);
        break;
    case 'N':
        ff_amf_write_number(p, strtod(value, NULL));
        break;
    case 'Z':
        ff_amf_write_null(p);
        break;
    case 'O':
        if (value[0] != '0')
            ff_amf_write_object_start(p);
        else
            ff_amf_write_object_end(p);
        break;
    default:
        goto fail;
        break;
    }

    return 0;

fail:
    av_log(s, AV_LOG_ERROR, "Invalid AMF parameter: %s\n", param);
    return AVERROR(EINVAL);
}

314
/**
315
 * Generate 'connect' call and send it to the server.
316
 */
317
static int gen_connect(URLContext *s, RTMPContext *rt)
318 319
{
    RTMPPacket pkt;
320
    uint8_t *p;
321 322 323
    int ret;

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
324
                                     0, 4096 + APP_MAX_LENGTH)) < 0)
325
        return ret;
326 327 328 329

    p = pkt.data;

    ff_amf_write_string(&p, "connect");
330
    ff_amf_write_number(&p, ++rt->nb_invokes);
331 332
    ff_amf_write_object_start(&p);
    ff_amf_write_field_name(&p, "app");
333
    ff_amf_write_string2(&p, rt->app, rt->auth_params);
334

335
    if (!rt->is_input) {
336 337 338
        ff_amf_write_field_name(&p, "type");
        ff_amf_write_string(&p, "nonprivate");
    }
339
    ff_amf_write_field_name(&p, "flashVer");
340
    ff_amf_write_string(&p, rt->flashver);
341

342
    if (rt->swfurl || rt->swfverify) {
343
        ff_amf_write_field_name(&p, "swfUrl");
344 345 346 347
        if (rt->swfurl)
            ff_amf_write_string(&p, rt->swfurl);
        else
            ff_amf_write_string(&p, rt->swfverify);
348 349
    }

350
    ff_amf_write_field_name(&p, "tcUrl");
351
    ff_amf_write_string2(&p, rt->tcurl, rt->auth_params);
352
    if (rt->is_input) {
353 354 355 356
        ff_amf_write_field_name(&p, "fpad");
        ff_amf_write_bool(&p, 0);
        ff_amf_write_field_name(&p, "capabilities");
        ff_amf_write_number(&p, 15.0);
357 358 359 360

        /* Tell the server we support all the audio codecs except
         * SUPPORT_SND_INTEL (0x0008) and SUPPORT_SND_UNUSED (0x0010)
         * which are unused in the RTMP protocol implementation. */
361
        ff_amf_write_field_name(&p, "audioCodecs");
362
        ff_amf_write_number(&p, 4071.0);
363 364 365 366
        ff_amf_write_field_name(&p, "videoCodecs");
        ff_amf_write_number(&p, 252.0);
        ff_amf_write_field_name(&p, "videoFunction");
        ff_amf_write_number(&p, 1.0);
367 368 369 370 371

        if (rt->pageurl) {
            ff_amf_write_field_name(&p, "pageUrl");
            ff_amf_write_string(&p, rt->pageurl);
        }
372
    }
373 374
    ff_amf_write_object_end(&p);

375
    if (rt->conn) {
376
        char *param = rt->conn;
377 378

        // Write arbitrary AMF data to the Connect message.
379
        while (param) {
380 381 382 383 384 385 386
            char *sep;
            param += strspn(param, " ");
            if (!*param)
                break;
            sep = strchr(param, ' ');
            if (sep)
                *sep = '\0';
387 388 389 390 391 392
            if ((ret = rtmp_write_amf_data(s, param, &p)) < 0) {
                // Invalid AMF parameter.
                ff_rtmp_packet_destroy(&pkt);
                return ret;
            }

393 394 395 396
            if (sep)
                param = sep + 1;
            else
                break;
397 398 399
        }
    }

400
    pkt.size = p - pkt.data;
401

402
    return rtmp_send_packet(rt, &pkt, 1);
403 404
}

405 406 407

#define RTMP_CTRL_ABORT_MESSAGE  (2)

408 409 410 411 412 413 414 415 416 417 418 419
static int read_connect(URLContext *s, RTMPContext *rt)
{
    RTMPPacket pkt = { 0 };
    uint8_t *p;
    const uint8_t *cp;
    int ret;
    char command[64];
    int stringlen;
    double seqnum;
    uint8_t tmpstr[256];
    GetByteContext gbc;

420 421
    // handle RTMP Protocol Control Messages
    for (;;) {
422 423 424
        if ((ret = ff_rtmp_packet_read(rt->stream, &pkt, rt->in_chunk_size,
                                       &rt->prev_pkt[0], &rt->nb_prev_pkt[0])) < 0)
            return ret;
425 426 427 428 429 430 431 432 433 434 435 436 437 438
#ifdef DEBUG
        ff_rtmp_packet_dump(s, &pkt);
#endif
        if (pkt.type == RTMP_PT_CHUNK_SIZE) {
            if ((ret = handle_chunk_size(s, &pkt)) < 0) {
                ff_rtmp_packet_destroy(&pkt);
                return ret;
            }
        } else if (pkt.type == RTMP_CTRL_ABORT_MESSAGE) {
            av_log(s, AV_LOG_ERROR, "received abort message\n");
            ff_rtmp_packet_destroy(&pkt);
            return AVERROR_UNKNOWN;
        } else if (pkt.type == RTMP_PT_BYTES_READ) {
            av_log(s, AV_LOG_TRACE, "received acknowledgement\n");
James Almer's avatar
James Almer committed
439 440
        } else if (pkt.type == RTMP_PT_WINDOW_ACK_SIZE) {
            if ((ret = handle_window_ack_size(s, &pkt)) < 0) {
441 442 443
                ff_rtmp_packet_destroy(&pkt);
                return ret;
            }
James Almer's avatar
James Almer committed
444 445
        } else if (pkt.type == RTMP_PT_SET_PEER_BW) {
            if ((ret = handle_set_peer_bw(s, &pkt)) < 0) {
446 447 448 449 450 451 452 453 454 455
                ff_rtmp_packet_destroy(&pkt);
                return ret;
            }
        } else if (pkt.type == RTMP_PT_INVOKE) {
            // received RTMP Command Message
            break;
        } else {
            av_log(s, AV_LOG_ERROR, "Unknown control message type (%d)\n", pkt.type);
        }
        ff_rtmp_packet_destroy(&pkt);
456 457
    }

458
    cp = pkt.data;
459
    bytestream2_init(&gbc, cp, pkt.size);
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    if (ff_amf_read_string(&gbc, command, sizeof(command), &stringlen)) {
        av_log(s, AV_LOG_ERROR, "Unable to read command string\n");
        ff_rtmp_packet_destroy(&pkt);
        return AVERROR_INVALIDDATA;
    }
    if (strcmp(command, "connect")) {
        av_log(s, AV_LOG_ERROR, "Expecting connect, got %s\n", command);
        ff_rtmp_packet_destroy(&pkt);
        return AVERROR_INVALIDDATA;
    }
    ret = ff_amf_read_number(&gbc, &seqnum);
    if (ret)
        av_log(s, AV_LOG_WARNING, "SeqNum not found\n");
    /* Here one could parse an AMF Object with data as flashVers and others. */
    ret = ff_amf_get_field_value(gbc.buffer,
                                 gbc.buffer + bytestream2_get_bytes_left(&gbc),
                                 "app", tmpstr, sizeof(tmpstr));
    if (ret)
        av_log(s, AV_LOG_WARNING, "App field not found in connect\n");
    if (!ret && strcmp(tmpstr, rt->app))
        av_log(s, AV_LOG_WARNING, "App field don't match up: %s <-> %s\n",
               tmpstr, rt->app);
    ff_rtmp_packet_destroy(&pkt);

484
    // Send Window Acknowledgement Size (as defined in specification)
485
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
486
                                     RTMP_PT_WINDOW_ACK_SIZE, 0, 4)) < 0)
487 488
        return ret;
    p = pkt.data;
489 490 491
    // Inform the peer about how often we want acknowledgements about what
    // we send. (We don't check for the acknowledgements currently.)
    bytestream_put_be32(&p, rt->max_sent_unacked);
492
    pkt.size = p - pkt.data;
493
    ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
494
                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
495 496 497
    ff_rtmp_packet_destroy(&pkt);
    if (ret < 0)
        return ret;
498
    // Set Peer Bandwidth
499
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
500
                                     RTMP_PT_SET_PEER_BW, 0, 5)) < 0)
501 502
        return ret;
    p = pkt.data;
503 504 505
    // Tell the peer to only send this many bytes unless it gets acknowledgements.
    // This could be any arbitrary value we want here.
    bytestream_put_be32(&p, rt->max_sent_unacked);
506
    bytestream_put_byte(&p, 2); // dynamic
507
    pkt.size = p - pkt.data;
508
    ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
509
                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
510 511 512 513
    ff_rtmp_packet_destroy(&pkt);
    if (ret < 0)
        return ret;

514
    // User control
515
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
516
                                     RTMP_PT_USER_CONTROL, 0, 6)) < 0)
517 518 519 520
        return ret;

    p = pkt.data;
    bytestream_put_be16(&p, 0); // 0 -> Stream Begin
521
    bytestream_put_be32(&p, 0); // Stream 0
522
    ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
523
                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
524 525 526 527 528
    ff_rtmp_packet_destroy(&pkt);
    if (ret < 0)
        return ret;

    // Chunk size
529
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
530 531 532 533 534 535
                                     RTMP_PT_CHUNK_SIZE, 0, 4)) < 0)
        return ret;

    p = pkt.data;
    bytestream_put_be32(&p, rt->out_chunk_size);
    ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
536
                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
537 538 539 540
    ff_rtmp_packet_destroy(&pkt);
    if (ret < 0)
        return ret;

Martin Storsjö's avatar
Martin Storsjö committed
541
    // Send _result NetConnection.Connect.Success to connect
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL,
                                     RTMP_PT_INVOKE, 0,
                                     RTMP_PKTDATA_DEFAULT_SIZE)) < 0)
        return ret;

    p = pkt.data;
    ff_amf_write_string(&p, "_result");
    ff_amf_write_number(&p, seqnum);

    ff_amf_write_object_start(&p);
    ff_amf_write_field_name(&p, "fmsVer");
    ff_amf_write_string(&p, "FMS/3,0,1,123");
    ff_amf_write_field_name(&p, "capabilities");
    ff_amf_write_number(&p, 31);
    ff_amf_write_object_end(&p);

    ff_amf_write_object_start(&p);
    ff_amf_write_field_name(&p, "level");
    ff_amf_write_string(&p, "status");
    ff_amf_write_field_name(&p, "code");
    ff_amf_write_string(&p, "NetConnection.Connect.Success");
    ff_amf_write_field_name(&p, "description");
    ff_amf_write_string(&p, "Connection succeeded.");
    ff_amf_write_field_name(&p, "objectEncoding");
    ff_amf_write_number(&p, 0);
    ff_amf_write_object_end(&p);

569
    pkt.size = p - pkt.data;
570
    ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
571
                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
572 573 574 575 576 577 578 579 580 581 582 583
    ff_rtmp_packet_destroy(&pkt);
    if (ret < 0)
        return ret;

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL,
                                     RTMP_PT_INVOKE, 0, 30)) < 0)
        return ret;
    p = pkt.data;
    ff_amf_write_string(&p, "onBWDone");
    ff_amf_write_number(&p, 0);
    ff_amf_write_null(&p);
    ff_amf_write_number(&p, 8192);
584
    pkt.size = p - pkt.data;
585
    ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
586
                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
587 588 589 590 591
    ff_rtmp_packet_destroy(&pkt);

    return ret;
}

592
/**
593
 * Generate 'releaseStream' call and send it to the server. It should make
594 595
 * the server release some channel for media streams.
 */
596
static int gen_release_stream(URLContext *s, RTMPContext *rt)
597 598 599
{
    RTMPPacket pkt;
    uint8_t *p;
600
    int ret;
601

602 603 604
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 29 + strlen(rt->playpath))) < 0)
        return ret;
605

606
    av_log(s, AV_LOG_DEBUG, "Releasing stream...\n");
607 608
    p = pkt.data;
    ff_amf_write_string(&p, "releaseStream");
609
    ff_amf_write_number(&p, ++rt->nb_invokes);
610 611 612
    ff_amf_write_null(&p);
    ff_amf_write_string(&p, rt->playpath);

613
    return rtmp_send_packet(rt, &pkt, 1);
614 615 616
}

/**
617
 * Generate 'FCPublish' call and send it to the server. It should make
618
 * the server prepare for receiving media streams.
619
 */
620
static int gen_fcpublish_stream(URLContext *s, RTMPContext *rt)
621 622 623
{
    RTMPPacket pkt;
    uint8_t *p;
624
    int ret;
625

626 627 628
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 25 + strlen(rt->playpath))) < 0)
        return ret;
629

630
    av_log(s, AV_LOG_DEBUG, "FCPublish stream...\n");
631 632
    p = pkt.data;
    ff_amf_write_string(&p, "FCPublish");
633
    ff_amf_write_number(&p, ++rt->nb_invokes);
634 635 636
    ff_amf_write_null(&p);
    ff_amf_write_string(&p, rt->playpath);

637
    return rtmp_send_packet(rt, &pkt, 1);
638 639 640
}

/**
641
 * Generate 'FCUnpublish' call and send it to the server. It should make
642 643
 * the server destroy stream.
 */
644
static int gen_fcunpublish_stream(URLContext *s, RTMPContext *rt)
645 646 647
{
    RTMPPacket pkt;
    uint8_t *p;
648
    int ret;
649

650 651 652
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 27 + strlen(rt->playpath))) < 0)
        return ret;
653

654
    av_log(s, AV_LOG_DEBUG, "UnPublishing stream...\n");
655 656
    p = pkt.data;
    ff_amf_write_string(&p, "FCUnpublish");
657
    ff_amf_write_number(&p, ++rt->nb_invokes);
658 659 660
    ff_amf_write_null(&p);
    ff_amf_write_string(&p, rt->playpath);

661
    return rtmp_send_packet(rt, &pkt, 0);
662 663
}

664
/**
665
 * Generate 'createStream' call and send it to the server. It should make
666 667
 * the server allocate some channel for media streams.
 */
668
static int gen_create_stream(URLContext *s, RTMPContext *rt)
669 670 671
{
    RTMPPacket pkt;
    uint8_t *p;
672
    int ret;
673

674
    av_log(s, AV_LOG_DEBUG, "Creating stream...\n");
675 676 677 678

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 25)) < 0)
        return ret;
679 680 681

    p = pkt.data;
    ff_amf_write_string(&p, "createStream");
682
    ff_amf_write_number(&p, ++rt->nb_invokes);
683 684
    ff_amf_write_null(&p);

685
    return rtmp_send_packet(rt, &pkt, 1);
686 687 688 689
}


/**
690
 * Generate 'deleteStream' call and send it to the server. It should make
691 692
 * the server remove some channel for media streams.
 */
693
static int gen_delete_stream(URLContext *s, RTMPContext *rt)
694 695 696
{
    RTMPPacket pkt;
    uint8_t *p;
697
    int ret;
698

699
    av_log(s, AV_LOG_DEBUG, "Deleting stream...\n");
700 701 702 703

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 34)) < 0)
        return ret;
704 705 706

    p = pkt.data;
    ff_amf_write_string(&p, "deleteStream");
707
    ff_amf_write_number(&p, ++rt->nb_invokes);
708
    ff_amf_write_null(&p);
709
    ff_amf_write_number(&p, rt->stream_id);
710

711
    return rtmp_send_packet(rt, &pkt, 0);
712 713
}

714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
/**
 * Generate 'getStreamLength' call and send it to the server. If the server
 * knows the duration of the selected stream, it will reply with the duration
 * in seconds.
 */
static int gen_get_stream_length(URLContext *s, RTMPContext *rt)
{
    RTMPPacket pkt;
    uint8_t *p;
    int ret;

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SOURCE_CHANNEL, RTMP_PT_INVOKE,
                                     0, 31 + strlen(rt->playpath))) < 0)
        return ret;

    p = pkt.data;
    ff_amf_write_string(&p, "getStreamLength");
    ff_amf_write_number(&p, ++rt->nb_invokes);
    ff_amf_write_null(&p);
    ff_amf_write_string(&p, rt->playpath);

    return rtmp_send_packet(rt, &pkt, 1);
}

738 739 740 741 742 743 744 745 746
/**
 * Generate client buffer time and send it to the server.
 */
static int gen_buffer_time(URLContext *s, RTMPContext *rt)
{
    RTMPPacket pkt;
    uint8_t *p;
    int ret;

747
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_USER_CONTROL,
748 749 750 751
                                     1, 10)) < 0)
        return ret;

    p = pkt.data;
752
    bytestream_put_be16(&p, 3); // SetBuffer Length
753
    bytestream_put_be32(&p, rt->stream_id);
754 755
    bytestream_put_be32(&p, rt->client_buffer_time);

756
    return rtmp_send_packet(rt, &pkt, 0);
757 758
}

759
/**
760
 * Generate 'play' call and send it to the server, then ping the server
761 762
 * to start actual playing.
 */
763
static int gen_play(URLContext *s, RTMPContext *rt)
764 765 766
{
    RTMPPacket pkt;
    uint8_t *p;
767
    int ret;
768

769
    av_log(s, AV_LOG_DEBUG, "Sending play command for '%s'\n", rt->playpath);
770

771
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SOURCE_CHANNEL, RTMP_PT_INVOKE,
772 773 774
                                     0, 29 + strlen(rt->playpath))) < 0)
        return ret;

775
    pkt.extra = rt->stream_id;
776 777 778

    p = pkt.data;
    ff_amf_write_string(&p, "play");
779
    ff_amf_write_number(&p, ++rt->nb_invokes);
780 781
    ff_amf_write_null(&p);
    ff_amf_write_string(&p, rt->playpath);
782
    ff_amf_write_number(&p, rt->live * 1000);
783

784
    return rtmp_send_packet(rt, &pkt, 1);
785 786
}

787 788 789 790 791 792
static int gen_seek(URLContext *s, RTMPContext *rt, int64_t timestamp)
{
    RTMPPacket pkt;
    uint8_t *p;
    int ret;

793 794
    av_log(s, AV_LOG_DEBUG, "Sending seek command for timestamp %"PRId64"\n",
           timestamp);
795 796 797 798

    if ((ret = ff_rtmp_packet_create(&pkt, 3, RTMP_PT_INVOKE, 0, 26)) < 0)
        return ret;

799
    pkt.extra = rt->stream_id;
800 801 802 803 804 805 806 807 808 809

    p = pkt.data;
    ff_amf_write_string(&p, "seek");
    ff_amf_write_number(&p, 0); //no tracking back responses
    ff_amf_write_null(&p); //as usual, the first null param
    ff_amf_write_number(&p, timestamp); //where we want to jump

    return rtmp_send_packet(rt, &pkt, 1);
}

810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
/**
 * Generate a pause packet that either pauses or unpauses the current stream.
 */
static int gen_pause(URLContext *s, RTMPContext *rt, int pause, uint32_t timestamp)
{
    RTMPPacket pkt;
    uint8_t *p;
    int ret;

    av_log(s, AV_LOG_DEBUG, "Sending pause command for timestamp %d\n",
           timestamp);

    if ((ret = ff_rtmp_packet_create(&pkt, 3, RTMP_PT_INVOKE, 0, 29)) < 0)
        return ret;

    pkt.extra = rt->stream_id;

    p = pkt.data;
    ff_amf_write_string(&p, "pause");
    ff_amf_write_number(&p, 0); //no tracking back responses
    ff_amf_write_null(&p); //as usual, the first null param
    ff_amf_write_bool(&p, pause); // pause or unpause
    ff_amf_write_number(&p, timestamp); //where we pause the stream

    return rtmp_send_packet(rt, &pkt, 1);
}

837
/**
838
 * Generate 'publish' call and send it to the server.
839
 */
840
static int gen_publish(URLContext *s, RTMPContext *rt)
841 842 843
{
    RTMPPacket pkt;
    uint8_t *p;
844
    int ret;
845

846
    av_log(s, AV_LOG_DEBUG, "Sending publish command for '%s'\n", rt->playpath);
847 848 849 850 851

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SOURCE_CHANNEL, RTMP_PT_INVOKE,
                                     0, 30 + strlen(rt->playpath))) < 0)
        return ret;

852
    pkt.extra = rt->stream_id;
853 854 855

    p = pkt.data;
    ff_amf_write_string(&p, "publish");
856
    ff_amf_write_number(&p, ++rt->nb_invokes);
857 858 859 860
    ff_amf_write_null(&p);
    ff_amf_write_string(&p, rt->playpath);
    ff_amf_write_string(&p, "live");

861
    return rtmp_send_packet(rt, &pkt, 1);
862 863
}

864
/**
865
 * Generate ping reply and send it to the server.
866
 */
867
static int gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
868 869 870
{
    RTMPPacket pkt;
    uint8_t *p;
871 872
    int ret;

873
    if (ppkt->size < 6) {
874
        av_log(s, AV_LOG_ERROR, "Too short ping packet (%d)\n",
875
               ppkt->size);
876 877 878
        return AVERROR_INVALIDDATA;
    }

879
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,RTMP_PT_USER_CONTROL,
880 881
                                     ppkt->timestamp + 1, 6)) < 0)
        return ret;
882 883

    p = pkt.data;
884
    bytestream_put_be16(&p, 7); // PingResponse
885
    bytestream_put_be32(&p, AV_RB32(ppkt->data+2));
886

887
    return rtmp_send_packet(rt, &pkt, 0);
888 889
}

890 891 892 893 894 895 896 897 898 899
/**
 * Generate SWF verification message and send it to the server.
 */
static int gen_swf_verification(URLContext *s, RTMPContext *rt)
{
    RTMPPacket pkt;
    uint8_t *p;
    int ret;

    av_log(s, AV_LOG_DEBUG, "Sending SWF verification...\n");
900
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_USER_CONTROL,
901 902 903 904 905 906 907 908 909 910
                                     0, 44)) < 0)
        return ret;

    p = pkt.data;
    bytestream_put_be16(&p, 27);
    memcpy(p, rt->swfverification, 42);

    return rtmp_send_packet(rt, &pkt, 0);
}

911
/**
912
 * Generate window acknowledgement size message and send it to the server.
913
 */
914
static int gen_window_ack_size(URLContext *s, RTMPContext *rt)
915 916 917
{
    RTMPPacket pkt;
    uint8_t *p;
918 919
    int ret;

920
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_WINDOW_ACK_SIZE,
921 922
                                     0, 4)) < 0)
        return ret;
923 924

    p = pkt.data;
925
    bytestream_put_be32(&p, rt->max_sent_unacked);
926

927
    return rtmp_send_packet(rt, &pkt, 0);
928 929
}

930 931 932
/**
 * Generate check bandwidth message and send it to the server.
 */
933
static int gen_check_bw(URLContext *s, RTMPContext *rt)
934 935 936
{
    RTMPPacket pkt;
    uint8_t *p;
937
    int ret;
938

939 940 941
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 21)) < 0)
        return ret;
942 943 944

    p = pkt.data;
    ff_amf_write_string(&p, "_checkbw");
945
    ff_amf_write_number(&p, ++rt->nb_invokes);
946 947
    ff_amf_write_null(&p);

948
    return rtmp_send_packet(rt, &pkt, 1);
949 950
}

951
/**
952
 * Generate report on bytes read so far and send it to the server.
953
 */
954
static int gen_bytes_read(URLContext *s, RTMPContext *rt, uint32_t ts)
955 956 957
{
    RTMPPacket pkt;
    uint8_t *p;
958 959 960 961 962
    int ret;

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_BYTES_READ,
                                     ts, 4)) < 0)
        return ret;
963 964 965

    p = pkt.data;
    bytestream_put_be32(&p, rt->bytes_read);
966

967
    return rtmp_send_packet(rt, &pkt, 0);
968 969
}

970 971
static int gen_fcsubscribe_stream(URLContext *s, RTMPContext *rt,
                                  const char *subscribe)
972 973 974 975 976 977
{
    RTMPPacket pkt;
    uint8_t *p;
    int ret;

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
978
                                     0, 27 + strlen(subscribe))) < 0)
979 980 981 982 983 984
        return ret;

    p = pkt.data;
    ff_amf_write_string(&p, "FCSubscribe");
    ff_amf_write_number(&p, ++rt->nb_invokes);
    ff_amf_write_null(&p);
985
    ff_amf_write_string(&p, subscribe);
986

987
    return rtmp_send_packet(rt, &pkt, 1);
988 989
}

990
/**
991
 * Put HMAC-SHA2 digest of packet data (except for the bytes where this digest
992 993 994
 * will be stored) into that packet.
 *
 * @param buf handshake data (1536 bytes)
Samuel Pitoiset's avatar
Samuel Pitoiset committed
995
 * @param encrypted use an encrypted connection (RTMPE)
996 997
 * @return offset to the digest inside input data
 */
Samuel Pitoiset's avatar
Samuel Pitoiset committed
998
static int rtmp_handshake_imprint_with_digest(uint8_t *buf, int encrypted)
999
{
1000
    int ret, digest_pos;
1001

Samuel Pitoiset's avatar
Samuel Pitoiset committed
1002 1003 1004 1005
    if (encrypted)
        digest_pos = ff_rtmp_calc_digest_pos(buf, 772, 728, 776);
    else
        digest_pos = ff_rtmp_calc_digest_pos(buf, 8, 728, 12);
1006

1007 1008 1009
    ret = ff_rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
                              rtmp_player_key, PLAYER_KEY_OPEN_PART_LEN,
                              buf + digest_pos);
1010 1011 1012
    if (ret < 0)
        return ret;

1013 1014 1015 1016
    return digest_pos;
}

/**
1017
 * Verify that the received server response has the expected digest value.
1018 1019 1020 1021 1022 1023 1024 1025
 *
 * @param buf handshake data received from the server (1536 bytes)
 * @param off position to search digest offset from
 * @return 0 if digest is valid, digest position otherwise
 */
static int rtmp_validate_digest(uint8_t *buf, int off)
{
    uint8_t digest[32];
1026
    int ret, digest_pos;
1027

1028
    digest_pos = ff_rtmp_calc_digest_pos(buf, off, 728, off + 4);
1029

1030 1031 1032
    ret = ff_rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
                              rtmp_server_key, SERVER_KEY_OPEN_PART_LEN,
                              digest);
1033 1034 1035
    if (ret < 0)
        return ret;

1036 1037 1038 1039 1040
    if (!memcmp(digest, buf + digest_pos, 32))
        return digest_pos;
    return 0;
}

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
static int rtmp_calc_swf_verification(URLContext *s, RTMPContext *rt,
                                      uint8_t *buf)
{
    uint8_t *p;
    int ret;

    if (rt->swfhash_len != 32) {
        av_log(s, AV_LOG_ERROR,
               "Hash of the decompressed SWF file is not 32 bytes long.\n");
        return AVERROR(EINVAL);
    }

    p = &rt->swfverification[0];
    bytestream_put_byte(&p, 1);
    bytestream_put_byte(&p, 1);
    bytestream_put_be32(&p, rt->swfsize);
    bytestream_put_be32(&p, rt->swfsize);

    if ((ret = ff_rtmp_calc_digest(rt->swfhash, 32, 0, buf, 32, p)) < 0)
        return ret;

    return 0;
}

1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
#if CONFIG_ZLIB
static int rtmp_uncompress_swfplayer(uint8_t *in_data, int64_t in_size,
                                     uint8_t **out_data, int64_t *out_size)
{
    z_stream zs = { 0 };
    void *ptr;
    int size;
    int ret = 0;

    zs.avail_in = in_size;
    zs.next_in  = in_data;
    ret = inflateInit(&zs);
    if (ret != Z_OK)
        return AVERROR_UNKNOWN;

    do {
        uint8_t tmp_buf[16384];

        zs.avail_out = sizeof(tmp_buf);
        zs.next_out  = tmp_buf;

        ret = inflate(&zs, Z_NO_FLUSH);
        if (ret != Z_OK && ret != Z_STREAM_END) {
            ret = AVERROR_UNKNOWN;
            goto fail;
        }

        size = sizeof(tmp_buf) - zs.avail_out;
        if (!(ptr = av_realloc(*out_data, *out_size + size))) {
            ret = AVERROR(ENOMEM);
            goto fail;
        }
        *out_data = ptr;

        memcpy(*out_data + *out_size, tmp_buf, size);
        *out_size += size;
    } while (zs.avail_out == 0);

fail:
    inflateEnd(&zs);
    return ret;
}
#endif

static int rtmp_calc_swfhash(URLContext *s)
{
    RTMPContext *rt = s->priv_data;
    uint8_t *in_data = NULL, *out_data = NULL, *swfdata;
1113
    int64_t in_size;
1114
    URLContext *stream = NULL;
1115 1116 1117 1118 1119
    char swfhash[32];
    int swfsize;
    int ret = 0;

    /* Get the SWF player file. */
1120 1121
    if ((ret = ffurl_open_whitelist(&stream, rt->swfverify, AVIO_FLAG_READ,
                                    &s->interrupt_callback, NULL,
1122
                                    s->protocol_whitelist, s->protocol_blacklist, s)) < 0) {
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
        av_log(s, AV_LOG_ERROR, "Cannot open connection %s.\n", rt->swfverify);
        goto fail;
    }

    if ((in_size = ffurl_seek(stream, 0, AVSEEK_SIZE)) < 0) {
        ret = AVERROR(EIO);
        goto fail;
    }

    if (!(in_data = av_malloc(in_size))) {
        ret = AVERROR(ENOMEM);
        goto fail;
    }

    if ((ret = ffurl_read_complete(stream, in_data, in_size)) < 0)
        goto fail;

    if (in_size < 3) {
        ret = AVERROR_INVALIDDATA;
        goto fail;
    }

    if (!memcmp(in_data, "CWS", 3)) {
1146 1147
#if CONFIG_ZLIB
        int64_t out_size;
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
        /* Decompress the SWF player file using Zlib. */
        if (!(out_data = av_malloc(8))) {
            ret = AVERROR(ENOMEM);
            goto fail;
        }
        *in_data = 'F'; // magic stuff
        memcpy(out_data, in_data, 8);
        out_size = 8;

        if ((ret = rtmp_uncompress_swfplayer(in_data + 8, in_size - 8,
                                             &out_data, &out_size)) < 0)
            goto fail;
1160 1161
        swfsize = out_size;
        swfdata = out_data;
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
#else
        av_log(s, AV_LOG_ERROR,
               "Zlib is required for decompressing the SWF player file.\n");
        ret = AVERROR(EINVAL);
        goto fail;
#endif
    } else {
        swfsize = in_size;
        swfdata = in_data;
    }

    /* Compute the SHA256 hash of the SWF player file. */
    if ((ret = ff_rtmp_calc_digest(swfdata, swfsize, 0,
                                   "Genuine Adobe Flash Player 001", 30,
                                   swfhash)) < 0)
        goto fail;

    /* Set SWFVerification parameters. */
    av_opt_set_bin(rt, "rtmp_swfhash", swfhash, 32, 0);
    rt->swfsize = swfsize;

fail:
    av_freep(&in_data);
    av_freep(&out_data);
    ffurl_close(stream);
    return ret;
}

1190
/**
1191
 * Perform handshake with the server by means of exchanging pseudorandom data
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
 * signed with HMAC-SHA2 digest.
 *
 * @return 0 if handshake succeeds, negative value otherwise
 */
static int rtmp_handshake(URLContext *s, RTMPContext *rt)
{
    AVLFG rnd;
    uint8_t tosend    [RTMP_HANDSHAKE_PACKET_SIZE+1] = {
        3,                // unencrypted data
        0, 0, 0, 0,       // client uptime
1202 1203 1204 1205
        RTMP_CLIENT_VER1,
        RTMP_CLIENT_VER2,
        RTMP_CLIENT_VER3,
        RTMP_CLIENT_VER4,
1206 1207 1208 1209 1210
    };
    uint8_t clientdata[RTMP_HANDSHAKE_PACKET_SIZE];
    uint8_t serverdata[RTMP_HANDSHAKE_PACKET_SIZE+1];
    int i;
    int server_pos, client_pos;
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1211 1212
    uint8_t digest[32], signature[32];
    int ret, type = 0;
1213

1214
    av_log(s, AV_LOG_DEBUG, "Handshaking...\n");
1215 1216 1217 1218 1219

    av_lfg_init(&rnd, 0xDEADC0DE);
    // generate handshake packet - 1536 bytes of pseudorandom data
    for (i = 9; i <= RTMP_HANDSHAKE_PACKET_SIZE; i++)
        tosend[i] = av_lfg_get(&rnd) >> 24;
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1220

1221
    if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
        /* When the client wants to use RTMPE, we have to change the command
         * byte to 0x06 which means to use encrypted data and we have to set
         * the flash version to at least 9.0.115.0. */
        tosend[0] = 6;
        tosend[5] = 128;
        tosend[6] = 0;
        tosend[7] = 3;
        tosend[8] = 2;

        /* Initialize the Diffie-Hellmann context and generate the public key
         * to send to the server. */
        if ((ret = ff_rtmpe_gen_pub_key(rt->stream, tosend + 1)) < 0)
            return ret;
    }

1237
    client_pos = rtmp_handshake_imprint_with_digest(tosend + 1, rt->encrypted);
1238 1239
    if (client_pos < 0)
        return client_pos;
1240

1241 1242 1243 1244 1245 1246
    if ((ret = ffurl_write(rt->stream, tosend,
                           RTMP_HANDSHAKE_PACKET_SIZE + 1)) < 0) {
        av_log(s, AV_LOG_ERROR, "Cannot write RTMP handshake request\n");
        return ret;
    }

1247 1248
    if ((ret = ffurl_read_complete(rt->stream, serverdata,
                                   RTMP_HANDSHAKE_PACKET_SIZE + 1)) < 0) {
1249
        av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
1250
        return ret;
1251
    }
1252 1253 1254

    if ((ret = ffurl_read_complete(rt->stream, clientdata,
                                   RTMP_HANDSHAKE_PACKET_SIZE)) < 0) {
1255
        av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
1256
        return ret;
1257 1258
    }

Samuel Pitoiset's avatar
Samuel Pitoiset committed
1259
    av_log(s, AV_LOG_DEBUG, "Type answer %d\n", serverdata[0]);
1260
    av_log(s, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n",
1261 1262
           serverdata[5], serverdata[6], serverdata[7], serverdata[8]);

1263
    if (rt->is_input && serverdata[5] >= 3) {
1264
        server_pos = rtmp_validate_digest(serverdata + 1, 772);
1265 1266 1267
        if (server_pos < 0)
            return server_pos;

1268
        if (!server_pos) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1269
            type = 1;
1270
            server_pos = rtmp_validate_digest(serverdata + 1, 8);
1271 1272 1273
            if (server_pos < 0)
                return server_pos;

1274
            if (!server_pos) {
1275
                av_log(s, AV_LOG_ERROR, "Server response validating failed\n");
1276
                return AVERROR(EIO);
1277
            }
1278 1279
        }

1280 1281 1282 1283 1284 1285 1286 1287
        /* Generate SWFVerification token (SHA256 HMAC hash of decompressed SWF,
         * key are the last 32 bytes of the server handshake. */
        if (rt->swfsize) {
            if ((ret = rtmp_calc_swf_verification(s, rt, serverdata + 1 +
                                                  RTMP_HANDSHAKE_PACKET_SIZE - 32)) < 0)
                return ret;
        }

1288 1289 1290
        ret = ff_rtmp_calc_digest(tosend + 1 + client_pos, 32, 0,
                                  rtmp_server_key, sizeof(rtmp_server_key),
                                  digest);
1291 1292 1293
        if (ret < 0)
            return ret;

1294
        ret = ff_rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE - 32,
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1295
                                  0, digest, 32, signature);
1296 1297 1298
        if (ret < 0)
            return ret;

1299
        if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
            /* Compute the shared secret key sent by the server and initialize
             * the RC4 encryption. */
            if ((ret = ff_rtmpe_compute_secret_key(rt->stream, serverdata + 1,
                                                   tosend + 1, type)) < 0)
                return ret;

            /* Encrypt the signature received by the server. */
            ff_rtmpe_encrypt_sig(rt->stream, signature, digest, serverdata[0]);
        }

        if (memcmp(signature, clientdata + RTMP_HANDSHAKE_PACKET_SIZE - 32, 32)) {
1311
            av_log(s, AV_LOG_ERROR, "Signature mismatch\n");
1312
            return AVERROR(EIO);
1313
        }
1314

1315 1316
        for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++)
            tosend[i] = av_lfg_get(&rnd) >> 24;
1317 1318 1319
        ret = ff_rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0,
                                  rtmp_player_key, sizeof(rtmp_player_key),
                                  digest);
1320 1321 1322
        if (ret < 0)
            return ret;

1323 1324 1325
        ret = ff_rtmp_calc_digest(tosend, RTMP_HANDSHAKE_PACKET_SIZE - 32, 0,
                                  digest, 32,
                                  tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
1326 1327
        if (ret < 0)
            return ret;
1328

1329
        if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1330 1331 1332 1333 1334 1335
            /* Encrypt the signature to be send to the server. */
            ff_rtmpe_encrypt_sig(rt->stream, tosend +
                                 RTMP_HANDSHAKE_PACKET_SIZE - 32, digest,
                                 serverdata[0]);
        }

1336
        // write reply back to the server
1337 1338 1339
        if ((ret = ffurl_write(rt->stream, tosend,
                               RTMP_HANDSHAKE_PACKET_SIZE)) < 0)
            return ret;
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1340

1341
        if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1342 1343 1344 1345
            /* Set RC4 keys for encryption and update the keystreams. */
            if ((ret = ff_rtmpe_update_keystream(rt->stream)) < 0)
                return ret;
        }
1346
    } else {
1347
        if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
            /* Compute the shared secret key sent by the server and initialize
             * the RC4 encryption. */
            if ((ret = ff_rtmpe_compute_secret_key(rt->stream, serverdata + 1,
                            tosend + 1, 1)) < 0)
                return ret;

            if (serverdata[0] == 9) {
                /* Encrypt the signature received by the server. */
                ff_rtmpe_encrypt_sig(rt->stream, signature, digest,
                                     serverdata[0]);
            }
        }

1361 1362 1363
        if ((ret = ffurl_write(rt->stream, serverdata + 1,
                               RTMP_HANDSHAKE_PACKET_SIZE)) < 0)
            return ret;
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1364

1365
        if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1366 1367 1368 1369
            /* Set RC4 keys for encryption and update the keystreams. */
            if ((ret = ff_rtmpe_update_keystream(rt->stream)) < 0)
                return ret;
        }
1370 1371
    }

1372 1373 1374
    return 0;
}

1375 1376 1377 1378
static int rtmp_receive_hs_packet(RTMPContext* rt, uint32_t *first_int,
                                  uint32_t *second_int, char *arraydata,
                                  int size)
{
1379
    int inoutsize;
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398

    inoutsize = ffurl_read_complete(rt->stream, arraydata,
                                    RTMP_HANDSHAKE_PACKET_SIZE);
    if (inoutsize <= 0)
        return AVERROR(EIO);
    if (inoutsize != RTMP_HANDSHAKE_PACKET_SIZE) {
        av_log(rt, AV_LOG_ERROR, "Erroneous Message size %d"
               " not following standard\n", (int)inoutsize);
        return AVERROR(EINVAL);
    }

    *first_int  = AV_RB32(arraydata);
    *second_int = AV_RB32(arraydata + 4);
    return 0;
}

static int rtmp_send_hs_packet(RTMPContext* rt, uint32_t first_int,
                               uint32_t second_int, char *arraydata, int size)
{
1399
    int inoutsize;
1400 1401

    AV_WB32(arraydata, first_int);
1402
    AV_WB32(arraydata + 4, second_int);
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
    inoutsize = ffurl_write(rt->stream, arraydata,
                            RTMP_HANDSHAKE_PACKET_SIZE);
    if (inoutsize != RTMP_HANDSHAKE_PACKET_SIZE) {
        av_log(rt, AV_LOG_ERROR, "Unable to write answer\n");
        return AVERROR(EIO);
    }

    return 0;
}

/**
 * rtmp handshake server side
 */
static int rtmp_server_handshake(URLContext *s, RTMPContext *rt)
{
    uint8_t buffer[RTMP_HANDSHAKE_PACKET_SIZE];
    uint32_t hs_epoch;
    uint32_t hs_my_epoch;
    uint8_t hs_c1[RTMP_HANDSHAKE_PACKET_SIZE];
    uint8_t hs_s1[RTMP_HANDSHAKE_PACKET_SIZE];
    uint32_t zeroes;
    uint32_t temp       = 0;
    int randomidx       = 0;
1426
    int inoutsize       = 0;
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
    int ret;

    inoutsize = ffurl_read_complete(rt->stream, buffer, 1);       // Receive C0
    if (inoutsize <= 0) {
        av_log(s, AV_LOG_ERROR, "Unable to read handshake\n");
        return AVERROR(EIO);
    }
    // Check Version
    if (buffer[0] != 3) {
        av_log(s, AV_LOG_ERROR, "RTMP protocol version mismatch\n");
        return AVERROR(EIO);
    }
    if (ffurl_write(rt->stream, buffer, 1) <= 0) {                 // Send S0
        av_log(s, AV_LOG_ERROR,
               "Unable to write answer - RTMP S0\n");
        return AVERROR(EIO);
    }
    /* Receive C1 */
    ret = rtmp_receive_hs_packet(rt, &hs_epoch, &zeroes, hs_c1,
                                 RTMP_HANDSHAKE_PACKET_SIZE);
    if (ret) {
        av_log(s, AV_LOG_ERROR, "RTMP Handshake C1 Error\n");
        return ret;
    }
    /* Send S1 */
    /* By now same epoch will be sent */
    hs_my_epoch = hs_epoch;
    /* Generate random */
1455
    for (randomidx = 8; randomidx < (RTMP_HANDSHAKE_PACKET_SIZE);
1456
         randomidx += 4)
1457
        AV_WB32(hs_s1 + randomidx, av_get_random_seed());
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489

    ret = rtmp_send_hs_packet(rt, hs_my_epoch, 0, hs_s1,
                              RTMP_HANDSHAKE_PACKET_SIZE);
    if (ret) {
        av_log(s, AV_LOG_ERROR, "RTMP Handshake S1 Error\n");
        return ret;
    }
    /* Send S2 */
    ret = rtmp_send_hs_packet(rt, hs_epoch, 0, hs_c1,
                              RTMP_HANDSHAKE_PACKET_SIZE);
    if (ret) {
        av_log(s, AV_LOG_ERROR, "RTMP Handshake S2 Error\n");
        return ret;
    }
    /* Receive C2 */
    ret = rtmp_receive_hs_packet(rt, &temp, &zeroes, buffer,
                                 RTMP_HANDSHAKE_PACKET_SIZE);
    if (ret) {
        av_log(s, AV_LOG_ERROR, "RTMP Handshake C2 Error\n");
        return ret;
    }
    if (temp != hs_my_epoch)
        av_log(s, AV_LOG_WARNING,
               "Erroneous C2 Message epoch does not match up with C1 epoch\n");
    if (memcmp(buffer + 8, hs_s1 + 8,
               RTMP_HANDSHAKE_PACKET_SIZE - 8))
        av_log(s, AV_LOG_WARNING,
               "Erroneous C2 Message random does not match up\n");

    return 0;
}

1490 1491 1492 1493 1494
static int handle_chunk_size(URLContext *s, RTMPPacket *pkt)
{
    RTMPContext *rt = s->priv_data;
    int ret;

1495
    if (pkt->size < 4) {
1496
        av_log(s, AV_LOG_ERROR,
1497
               "Too short chunk size change packet (%d)\n",
1498
               pkt->size);
1499
        return AVERROR_INVALIDDATA;
1500 1501 1502
    }

    if (!rt->is_input) {
1503 1504 1505
        /* Send the same chunk size change packet back to the server,
         * setting the outgoing chunk size to the same as the incoming one. */
        if ((ret = ff_rtmp_packet_write(rt->stream, pkt, rt->out_chunk_size,
1506
                                        &rt->prev_pkt[1], &rt->nb_prev_pkt[1])) < 0)
1507
            return ret;
1508
        rt->out_chunk_size = AV_RB32(pkt->data);
1509 1510
    }

1511 1512 1513 1514
    rt->in_chunk_size = AV_RB32(pkt->data);
    if (rt->in_chunk_size <= 0) {
        av_log(s, AV_LOG_ERROR, "Incorrect chunk size %d\n",
               rt->in_chunk_size);
1515
        return AVERROR_INVALIDDATA;
1516
    }
1517 1518
    av_log(s, AV_LOG_DEBUG, "New incoming chunk size = %d\n",
           rt->in_chunk_size);
1519 1520 1521 1522

    return 0;
}

1523
static int handle_user_control(URLContext *s, RTMPPacket *pkt)
1524 1525 1526 1527
{
    RTMPContext *rt = s->priv_data;
    int t, ret;

1528
    if (pkt->size < 2) {
1529
        av_log(s, AV_LOG_ERROR, "Too short user control packet (%d)\n",
1530
               pkt->size);
1531 1532 1533
        return AVERROR_INVALIDDATA;
    }

1534
    t = AV_RB16(pkt->data);
1535
    if (t == 6) { // PingRequest
1536 1537
        if ((ret = gen_pong(s, rt, pkt)) < 0)
            return ret;
1538 1539 1540 1541 1542 1543 1544
    } else if (t == 26) {
        if (rt->swfsize) {
            if ((ret = gen_swf_verification(s, rt)) < 0)
                return ret;
        } else {
            av_log(s, AV_LOG_WARNING, "Ignoring SWFVerification request.\n");
        }
1545 1546 1547 1548 1549
    }

    return 0;
}

1550
static int handle_set_peer_bw(URLContext *s, RTMPPacket *pkt)
1551
{
1552 1553
    RTMPContext *rt = s->priv_data;

1554
    if (pkt->size < 4) {
1555
        av_log(s, AV_LOG_ERROR,
1556
               "Peer bandwidth packet is less than 4 bytes long (%d)\n",
1557
               pkt->size);
1558
        return AVERROR_INVALIDDATA;
1559
    }
1560

1561 1562 1563 1564 1565 1566 1567 1568
    // We currently don't check how much the peer has acknowledged of
    // what we have sent. To do that properly, we should call
    // gen_window_ack_size here, to tell the peer that we want an
    // acknowledgement with (at least) that interval.
    rt->max_sent_unacked = AV_RB32(pkt->data);
    if (rt->max_sent_unacked <= 0) {
        av_log(s, AV_LOG_ERROR, "Incorrect set peer bandwidth %d\n",
               rt->max_sent_unacked);
1569 1570 1571
        return AVERROR_INVALIDDATA;

    }
1572
    av_log(s, AV_LOG_DEBUG, "Max sent, unacked = %d\n", rt->max_sent_unacked);
1573 1574 1575 1576

    return 0;
}

1577
static int handle_window_ack_size(URLContext *s, RTMPPacket *pkt)
1578 1579 1580
{
    RTMPContext *rt = s->priv_data;

1581
    if (pkt->size < 4) {
1582
        av_log(s, AV_LOG_ERROR,
1583
               "Too short window acknowledgement size packet (%d)\n",
1584
               pkt->size);
1585 1586 1587
        return AVERROR_INVALIDDATA;
    }

1588 1589
    rt->receive_report_size = AV_RB32(pkt->data);
    if (rt->receive_report_size <= 0) {
1590
        av_log(s, AV_LOG_ERROR, "Incorrect window acknowledgement size %d\n",
1591
               rt->receive_report_size);
1592
        return AVERROR_INVALIDDATA;
1593
    }
1594 1595 1596 1597 1598
    av_log(s, AV_LOG_DEBUG, "Window acknowledgement size = %d\n", rt->receive_report_size);
    // Send an Acknowledgement packet after receiving half the maximum
    // size, to make sure the peer can keep on sending without waiting
    // for acknowledgements.
    rt->receive_report_size >>= 1;
1599 1600 1601 1602

    return 0;
}

1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
static int do_adobe_auth(RTMPContext *rt, const char *user, const char *salt,
                         const char *opaque, const char *challenge)
{
    uint8_t hash[16];
    char hashstr[AV_BASE64_SIZE(sizeof(hash))], challenge2[10];
    struct AVMD5 *md5 = av_md5_alloc();
    if (!md5)
        return AVERROR(ENOMEM);

    snprintf(challenge2, sizeof(challenge2), "%08x", av_get_random_seed());

    av_md5_init(md5);
    av_md5_update(md5, user, strlen(user));
    av_md5_update(md5, salt, strlen(salt));
    av_md5_update(md5, rt->password, strlen(rt->password));
    av_md5_final(md5, hash);
    av_base64_encode(hashstr, sizeof(hashstr), hash,
                     sizeof(hash));
    av_md5_init(md5);
    av_md5_update(md5, hashstr, strlen(hashstr));
    if (opaque)
        av_md5_update(md5, opaque, strlen(opaque));
    else if (challenge)
        av_md5_update(md5, challenge, strlen(challenge));
    av_md5_update(md5, challenge2, strlen(challenge2));
    av_md5_final(md5, hash);
    av_base64_encode(hashstr, sizeof(hashstr), hash,
                     sizeof(hash));
    snprintf(rt->auth_params, sizeof(rt->auth_params),
             "?authmod=%s&user=%s&challenge=%s&response=%s",
             "adobe", user, challenge2, hashstr);
    if (opaque)
        av_strlcatf(rt->auth_params, sizeof(rt->auth_params),
                    "&opaque=%s", opaque);

    av_free(md5);
    return 0;
}

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
static int do_llnw_auth(RTMPContext *rt, const char *user, const char *nonce)
{
    uint8_t hash[16];
    char hashstr1[33], hashstr2[33];
    const char *realm = "live";
    const char *method = "publish";
    const char *qop = "auth";
    const char *nc = "00000001";
    char cnonce[10];
    struct AVMD5 *md5 = av_md5_alloc();
    if (!md5)
        return AVERROR(ENOMEM);

    snprintf(cnonce, sizeof(cnonce), "%08x", av_get_random_seed());

    av_md5_init(md5);
    av_md5_update(md5, user, strlen(user));
    av_md5_update(md5, ":", 1);
    av_md5_update(md5, realm, strlen(realm));
    av_md5_update(md5, ":", 1);
    av_md5_update(md5, rt->password, strlen(rt->password));
    av_md5_final(md5, hash);
    ff_data_to_hex(hashstr1, hash, 16, 1);
    hashstr1[32] = '\0';

    av_md5_init(md5);
    av_md5_update(md5, method, strlen(method));
    av_md5_update(md5, ":/", 2);
    av_md5_update(md5, rt->app, strlen(rt->app));
1671 1672
    if (!strchr(rt->app, '/'))
        av_md5_update(md5, "/_definst_", strlen("/_definst_"));
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
    av_md5_final(md5, hash);
    ff_data_to_hex(hashstr2, hash, 16, 1);
    hashstr2[32] = '\0';

    av_md5_init(md5);
    av_md5_update(md5, hashstr1, strlen(hashstr1));
    av_md5_update(md5, ":", 1);
    if (nonce)
        av_md5_update(md5, nonce, strlen(nonce));
    av_md5_update(md5, ":", 1);
    av_md5_update(md5, nc, strlen(nc));
    av_md5_update(md5, ":", 1);
    av_md5_update(md5, cnonce, strlen(cnonce));
    av_md5_update(md5, ":", 1);
    av_md5_update(md5, qop, strlen(qop));
    av_md5_update(md5, ":", 1);
    av_md5_update(md5, hashstr2, strlen(hashstr2));
    av_md5_final(md5, hash);
    ff_data_to_hex(hashstr1, hash, 16, 1);

    snprintf(rt->auth_params, sizeof(rt->auth_params),
             "?authmod=%s&user=%s&nonce=%s&cnonce=%s&nc=%s&response=%s",
             "llnw", user, nonce, cnonce, nc, hashstr1);

    av_free(md5);
    return 0;
}

1701 1702 1703
static int handle_connect_error(URLContext *s, const char *desc)
{
    RTMPContext *rt = s->priv_data;
1704
    char buf[300], *ptr, authmod[15];
1705 1706
    int i = 0, ret = 0;
    const char *user = "", *salt = "", *opaque = NULL,
1707
               *challenge = NULL, *cptr = NULL, *nonce = NULL;
1708

1709 1710
    if (!(cptr = strstr(desc, "authmod=adobe")) &&
        !(cptr = strstr(desc, "authmod=llnw"))) {
1711 1712 1713 1714
        av_log(s, AV_LOG_ERROR,
               "Unknown connect error (unsupported authentication method?)\n");
        return AVERROR_UNKNOWN;
    }
1715 1716 1717 1718
    cptr += strlen("authmod=");
    while (*cptr && *cptr != ' ' && i < sizeof(authmod) - 1)
        authmod[i++] = *cptr++;
    authmod[i] = '\0';
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741

    if (!rt->username[0] || !rt->password[0]) {
        av_log(s, AV_LOG_ERROR, "No credentials set\n");
        return AVERROR_UNKNOWN;
    }

    if (strstr(desc, "?reason=authfailed")) {
        av_log(s, AV_LOG_ERROR, "Incorrect username/password\n");
        return AVERROR_UNKNOWN;
    } else if (strstr(desc, "?reason=nosuchuser")) {
        av_log(s, AV_LOG_ERROR, "Incorrect username\n");
        return AVERROR_UNKNOWN;
    }

    if (rt->auth_tried) {
        av_log(s, AV_LOG_ERROR, "Authentication failed\n");
        return AVERROR_UNKNOWN;
    }

    rt->auth_params[0] = '\0';

    if (strstr(desc, "code=403 need auth")) {
        snprintf(rt->auth_params, sizeof(rt->auth_params),
1742
                 "?authmod=%s&user=%s", authmod, rt->username);
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
        return 0;
    }

    if (!(cptr = strstr(desc, "?reason=needauth"))) {
        av_log(s, AV_LOG_ERROR, "No auth parameters found\n");
        return AVERROR_UNKNOWN;
    }

    av_strlcpy(buf, cptr + 1, sizeof(buf));
    ptr = buf;

    while (ptr) {
        char *next  = strchr(ptr, '&');
        char *value = strchr(ptr, '=');
        if (next)
            *next++ = '\0';
1759
        if (value) {
1760
            *value++ = '\0';
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
            if (!strcmp(ptr, "user")) {
                user = value;
            } else if (!strcmp(ptr, "salt")) {
                salt = value;
            } else if (!strcmp(ptr, "opaque")) {
                opaque = value;
            } else if (!strcmp(ptr, "challenge")) {
                challenge = value;
            } else if (!strcmp(ptr, "nonce")) {
                nonce = value;
1771 1772
            } else {
                av_log(s, AV_LOG_INFO, "Ignoring unsupported var %s\n", ptr);
1773 1774 1775
            }
        } else {
            av_log(s, AV_LOG_WARNING, "Variable %s has NULL value\n", ptr);
1776 1777 1778 1779
        }
        ptr = next;
    }

1780
    if (!strcmp(authmod, "adobe")) {
1781
        if ((ret = do_adobe_auth(rt, user, salt, opaque, challenge)) < 0)
1782 1783 1784 1785 1786
            return ret;
    } else {
        if ((ret = do_llnw_auth(rt, user, nonce)) < 0)
            return ret;
    }
1787 1788 1789 1790 1791

    rt->auth_tried = 1;
    return 0;
}

1792
static int handle_invoke_error(URLContext *s, RTMPPacket *pkt)
1793
{
1794
    RTMPContext *rt = s->priv_data;
1795
    const uint8_t *data_end = pkt->data + pkt->size;
1796 1797
    char *tracked_method = NULL;
    int level = AV_LOG_ERROR;
1798
    uint8_t tmpstr[256];
1799 1800 1801 1802
    int ret;

    if ((ret = find_tracked_method(s, pkt, 9, &tracked_method)) < 0)
        return ret;
1803 1804 1805

    if (!ff_amf_get_field_value(pkt->data + 9, data_end,
                                "description", tmpstr, sizeof(tmpstr))) {
1806 1807 1808 1809 1810
        if (tracked_method && (!strcmp(tracked_method, "_checkbw")      ||
                               !strcmp(tracked_method, "releaseStream") ||
                               !strcmp(tracked_method, "FCSubscribe")   ||
                               !strcmp(tracked_method, "FCPublish"))) {
            /* Gracefully ignore Adobe-specific historical artifact errors. */
1811 1812
            level = AV_LOG_WARNING;
            ret = 0;
1813 1814
        } else if (tracked_method && !strcmp(tracked_method, "getStreamLength")) {
            level = rt->live ? AV_LOG_DEBUG : AV_LOG_WARNING;
1815
            ret = 0;
1816 1817 1818 1819 1820 1821
        } else if (tracked_method && !strcmp(tracked_method, "connect")) {
            ret = handle_connect_error(s, tmpstr);
            if (!ret) {
                rt->do_reconnect = 1;
                level = AV_LOG_VERBOSE;
            }
1822
        } else
1823
            ret = AVERROR_UNKNOWN;
1824
        av_log(s, level, "Server error: %s\n", tmpstr);
1825 1826
    }

1827 1828
    av_free(tracked_method);
    return ret;
1829 1830
}

1831 1832 1833 1834 1835 1836 1837 1838 1839
static int write_begin(URLContext *s)
{
    RTMPContext *rt = s->priv_data;
    PutByteContext pbc;
    RTMPPacket spkt = { 0 };
    int ret;

    // Send Stream Begin 1
    if ((ret = ff_rtmp_packet_create(&spkt, RTMP_NETWORK_CHANNEL,
1840
                                     RTMP_PT_USER_CONTROL, 0, 6)) < 0) {
1841 1842 1843 1844 1845 1846 1847 1848 1849
        av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
        return ret;
    }

    bytestream2_init_writer(&pbc, spkt.data, spkt.size);
    bytestream2_put_be16(&pbc, 0);          // 0 -> Stream Begin
    bytestream2_put_be32(&pbc, rt->nb_streamid);

    ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,
1850
                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893

    ff_rtmp_packet_destroy(&spkt);

    return ret;
}

static int write_status(URLContext *s, RTMPPacket *pkt,
                        const char *status, const char *filename)
{
    RTMPContext *rt = s->priv_data;
    RTMPPacket spkt = { 0 };
    char statusmsg[128];
    uint8_t *pp;
    int ret;

    if ((ret = ff_rtmp_packet_create(&spkt, RTMP_SYSTEM_CHANNEL,
                                     RTMP_PT_INVOKE, 0,
                                     RTMP_PKTDATA_DEFAULT_SIZE)) < 0) {
        av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
        return ret;
    }

    pp = spkt.data;
    spkt.extra = pkt->extra;
    ff_amf_write_string(&pp, "onStatus");
    ff_amf_write_number(&pp, 0);
    ff_amf_write_null(&pp);

    ff_amf_write_object_start(&pp);
    ff_amf_write_field_name(&pp, "level");
    ff_amf_write_string(&pp, "status");
    ff_amf_write_field_name(&pp, "code");
    ff_amf_write_string(&pp, status);
    ff_amf_write_field_name(&pp, "description");
    snprintf(statusmsg, sizeof(statusmsg),
             "%s is now published", filename);
    ff_amf_write_string(&pp, statusmsg);
    ff_amf_write_field_name(&pp, "details");
    ff_amf_write_string(&pp, filename);
    ff_amf_write_object_end(&pp);

    spkt.size = pp - spkt.data;
    ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,
1894
                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
1895 1896 1897 1898 1899
    ff_rtmp_packet_destroy(&spkt);

    return ret;
}

1900 1901 1902 1903
static int send_invoke_response(URLContext *s, RTMPPacket *pkt)
{
    RTMPContext *rt = s->priv_data;
    double seqnum;
1904
    char filename[128];
1905 1906 1907 1908 1909 1910 1911 1912 1913
    char command[64];
    int stringlen;
    char *pchar;
    const uint8_t *p = pkt->data;
    uint8_t *pp      = NULL;
    RTMPPacket spkt  = { 0 };
    GetByteContext gbc;
    int ret;

1914
    bytestream2_init(&gbc, p, pkt->size);
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
    if (ff_amf_read_string(&gbc, command, sizeof(command),
                           &stringlen)) {
        av_log(s, AV_LOG_ERROR, "Error in PT_INVOKE\n");
        return AVERROR_INVALIDDATA;
    }

    ret = ff_amf_read_number(&gbc, &seqnum);
    if (ret)
        return ret;
    ret = ff_amf_read_null(&gbc);
    if (ret)
        return ret;
    if (!strcmp(command, "FCPublish") ||
        !strcmp(command, "publish")) {
        ret = ff_amf_read_string(&gbc, filename,
                                 sizeof(filename), &stringlen);
1931 1932 1933 1934 1935 1936 1937
        if (ret) {
            if (ret == AVERROR(EINVAL))
                av_log(s, AV_LOG_ERROR, "Unable to parse stream name - name too long?\n");
            else
                av_log(s, AV_LOG_ERROR, "Unable to parse stream name\n");
            return ret;
        }
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
        // check with url
        if (s->filename) {
            pchar = strrchr(s->filename, '/');
            if (!pchar) {
                av_log(s, AV_LOG_WARNING,
                       "Unable to find / in url %s, bad format\n",
                       s->filename);
                pchar = s->filename;
            }
            pchar++;
            if (strcmp(pchar, filename))
                av_log(s, AV_LOG_WARNING, "Unexpected stream %s, expecting"
                       " %s\n", filename, pchar);
        }
        rt->state = STATE_RECEIVING;
    }

    if (!strcmp(command, "FCPublish")) {
        if ((ret = ff_rtmp_packet_create(&spkt, RTMP_SYSTEM_CHANNEL,
                                         RTMP_PT_INVOKE, 0,
                                         RTMP_PKTDATA_DEFAULT_SIZE)) < 0) {
            av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
            return ret;
        }
        pp = spkt.data;
        ff_amf_write_string(&pp, "onFCPublish");
    } else if (!strcmp(command, "publish")) {
1965
        ret = write_begin(s);
1966 1967 1968 1969
        if (ret < 0)
            return ret;

        // Send onStatus(NetStream.Publish.Start)
1970 1971
        return write_status(s, pkt, "NetStream.Publish.Start",
                           filename);
1972 1973 1974 1975 1976 1977 1978
    } else if (!strcmp(command, "play")) {
        ret = write_begin(s);
        if (ret < 0)
            return ret;
        rt->state = STATE_SENDING;
        return write_status(s, pkt, "NetStream.Play.Start",
                            filename);
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
    } else {
        if ((ret = ff_rtmp_packet_create(&spkt, RTMP_SYSTEM_CHANNEL,
                                         RTMP_PT_INVOKE, 0,
                                         RTMP_PKTDATA_DEFAULT_SIZE)) < 0) {
            av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
            return ret;
        }
        pp = spkt.data;
        ff_amf_write_string(&pp, "_result");
        ff_amf_write_number(&pp, seqnum);
        ff_amf_write_null(&pp);
        if (!strcmp(command, "createStream")) {
            rt->nb_streamid++;
            if (rt->nb_streamid == 0 || rt->nb_streamid == 2)
                rt->nb_streamid++; /* Values 0 and 2 are reserved */
            ff_amf_write_number(&pp, rt->nb_streamid);
            /* By now we don't control which streams are removed in
             * deleteStream. There is no stream creation control
             * if a client creates more than 2^32 - 2 streams. */
        }
    }
2000
    spkt.size = pp - spkt.data;
2001
    ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,
2002
                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
2003 2004 2005 2006
    ff_rtmp_packet_destroy(&spkt);
    return ret;
}

2007 2008 2009 2010 2011 2012 2013
/**
 * Read the AMF_NUMBER response ("_result") to a function call
 * (e.g. createStream()). This response should be made up of the AMF_STRING
 * "result", a NULL object and then the response encoded as AMF_NUMBER. On a
 * successful response, we will return set the value to number (otherwise number
 * will not be changed).
 *
2014
 * @return 0 if reading the value succeeds, negative value otherwise
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
 */
static int read_number_result(RTMPPacket *pkt, double *number)
{
    // We only need to fit "_result" in this.
    uint8_t strbuffer[8];
    int stringlen;
    double numbuffer;
    GetByteContext gbc;

    bytestream2_init(&gbc, pkt->data, pkt->size);

    // Value 1/4: "_result" as AMF_STRING
    if (ff_amf_read_string(&gbc, strbuffer, sizeof(strbuffer), &stringlen))
        return AVERROR_INVALIDDATA;
    if (strcmp(strbuffer, "_result"))
        return AVERROR_INVALIDDATA;
    // Value 2/4: The callee reference number
    if (ff_amf_read_number(&gbc, &numbuffer))
        return AVERROR_INVALIDDATA;
    // Value 3/4: Null
    if (ff_amf_read_null(&gbc))
        return AVERROR_INVALIDDATA;
2037
    // Value 4/4: The response as AMF_NUMBER
2038 2039 2040 2041 2042 2043 2044 2045
    if (ff_amf_read_number(&gbc, &numbuffer))
        return AVERROR_INVALIDDATA;
    else
        *number = numbuffer;

    return 0;
}

2046 2047 2048
static int handle_invoke_result(URLContext *s, RTMPPacket *pkt)
{
    RTMPContext *rt = s->priv_data;
2049 2050
    char *tracked_method = NULL;
    int ret = 0;
2051

2052
    if ((ret = find_tracked_method(s, pkt, 10, &tracked_method)) < 0)
2053
        return ret;
2054

2055 2056 2057 2058
    if (!tracked_method) {
        /* Ignore this reply when the current method is not tracked. */
        return ret;
    }
2059

2060
    if (!strcmp(tracked_method, "connect")) {
2061 2062 2063
        if (!rt->is_input) {
            if ((ret = gen_release_stream(s, rt)) < 0)
                goto fail;
2064

2065 2066 2067
            if ((ret = gen_fcpublish_stream(s, rt)) < 0)
                goto fail;
        } else {
2068
            if ((ret = gen_window_ack_size(s, rt)) < 0)
2069
                goto fail;
2070 2071
        }

2072 2073
        if ((ret = gen_create_stream(s, rt)) < 0)
            goto fail;
2074

2075 2076 2077 2078 2079 2080 2081 2082 2083
        if (rt->is_input) {
            /* Send the FCSubscribe command when the name of live
             * stream is defined by the user or if it's a live stream. */
            if (rt->subscribe) {
                if ((ret = gen_fcsubscribe_stream(s, rt, rt->subscribe)) < 0)
                    goto fail;
            } else if (rt->live == -1) {
                if ((ret = gen_fcsubscribe_stream(s, rt, rt->playpath)) < 0)
                    goto fail;
2084
            }
2085
        }
2086
    } else if (!strcmp(tracked_method, "createStream")) {
2087 2088
        double stream_id;
        if (read_number_result(pkt, &stream_id)) {
2089 2090
            av_log(s, AV_LOG_WARNING, "Unexpected reply on connect()\n");
        } else {
2091
            rt->stream_id = stream_id;
2092
        }
2093 2094 2095 2096 2097

        if (!rt->is_input) {
            if ((ret = gen_publish(s, rt)) < 0)
                goto fail;
        } else {
2098 2099 2100 2101
            if (rt->live != -1) {
                if ((ret = gen_get_stream_length(s, rt)) < 0)
                    goto fail;
            }
2102 2103 2104 2105
            if ((ret = gen_play(s, rt)) < 0)
                goto fail;
            if ((ret = gen_buffer_time(s, rt)) < 0)
                goto fail;
2106
        }
2107 2108 2109 2110
    } else if (!strcmp(tracked_method, "getStreamLength")) {
        if (read_number_result(pkt, &rt->duration)) {
            av_log(s, AV_LOG_WARNING, "Unexpected reply on getStreamLength()\n");
        }
2111 2112 2113 2114 2115 2116 2117
    }

fail:
    av_free(tracked_method);
    return ret;
}

2118
static int handle_invoke_status(URLContext *s, RTMPPacket *pkt)
2119
{
2120
    RTMPContext *rt = s->priv_data;
2121
    const uint8_t *data_end = pkt->data + pkt->size;
2122
    const uint8_t *ptr = pkt->data + RTMP_HEADER;
2123
    uint8_t tmpstr[256];
2124
    int i, t;
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134

    for (i = 0; i < 2; i++) {
        t = ff_amf_tag_size(ptr, data_end);
        if (t < 0)
            return 1;
        ptr += t;
    }

    t = ff_amf_get_field_value(ptr, data_end, "level", tmpstr, sizeof(tmpstr));
    if (!t && !strcmp(tmpstr, "error")) {
2135 2136 2137 2138 2139 2140
        t = ff_amf_get_field_value(ptr, data_end,
                                   "description", tmpstr, sizeof(tmpstr));
        if (t || !tmpstr[0])
            t = ff_amf_get_field_value(ptr, data_end, "code",
                                       tmpstr, sizeof(tmpstr));
        if (!t)
2141 2142 2143 2144 2145 2146 2147 2148 2149
            av_log(s, AV_LOG_ERROR, "Server error: %s\n", tmpstr);
        return -1;
    }

    t = ff_amf_get_field_value(ptr, data_end, "code", tmpstr, sizeof(tmpstr));
    if (!t && !strcmp(tmpstr, "NetStream.Play.Start")) rt->state = STATE_PLAYING;
    if (!t && !strcmp(tmpstr, "NetStream.Play.Stop")) rt->state = STATE_STOPPED;
    if (!t && !strcmp(tmpstr, "NetStream.Play.UnpublishNotify")) rt->state = STATE_STOPPED;
    if (!t && !strcmp(tmpstr, "NetStream.Publish.Start")) rt->state = STATE_PUBLISHING;
2150
    if (!t && !strcmp(tmpstr, "NetStream.Seek.Notify")) rt->state = STATE_PLAYING;
2151 2152 2153 2154 2155 2156 2157

    return 0;
}

static int handle_invoke(URLContext *s, RTMPPacket *pkt)
{
    RTMPContext *rt = s->priv_data;
2158
    int ret = 0;
2159

2160
    //TODO: check for the messages sent for wrong state?
2161
    if (ff_amf_match_string(pkt->data, pkt->size, "_error")) {
2162 2163
        if ((ret = handle_invoke_error(s, pkt)) < 0)
            return ret;
2164
    } else if (ff_amf_match_string(pkt->data, pkt->size, "_result")) {
2165
        if ((ret = handle_invoke_result(s, pkt)) < 0)
2166
            return ret;
2167
    } else if (ff_amf_match_string(pkt->data, pkt->size, "onStatus")) {
2168 2169
        if ((ret = handle_invoke_status(s, pkt)) < 0)
            return ret;
2170
    } else if (ff_amf_match_string(pkt->data, pkt->size, "onBWDone")) {
2171 2172
        if ((ret = gen_check_bw(s, rt)) < 0)
            return ret;
2173 2174 2175
    } else if (ff_amf_match_string(pkt->data, pkt->size, "releaseStream") ||
               ff_amf_match_string(pkt->data, pkt->size, "FCPublish")     ||
               ff_amf_match_string(pkt->data, pkt->size, "publish")       ||
2176
               ff_amf_match_string(pkt->data, pkt->size, "play")          ||
2177 2178
               ff_amf_match_string(pkt->data, pkt->size, "_checkbw")      ||
               ff_amf_match_string(pkt->data, pkt->size, "createStream")) {
2179
        if ((ret = send_invoke_response(s, pkt)) < 0)
2180
            return ret;
2181 2182
    }

2183
    return ret;
2184 2185
}

Luca Barbato's avatar
Luca Barbato committed
2186 2187 2188
static int update_offset(RTMPContext *rt, int size)
{
    int old_flv_size;
2189

2190 2191
    // generate packet header and put data into buffer for FLV demuxer
    if (rt->flv_off < rt->flv_size) {
2192
        // There is old unread data in the buffer, thus append at the end
2193
        old_flv_size  = rt->flv_size;
2194
        rt->flv_size += size;
2195
    } else {
2196
        // All data has been read, write the new data at the start of the buffer
2197
        old_flv_size = 0;
2198
        rt->flv_size = size;
2199
        rt->flv_off  = 0;
2200
    }
2201

Luca Barbato's avatar
Luca Barbato committed
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
    return old_flv_size;
}

static int append_flv_data(RTMPContext *rt, RTMPPacket *pkt, int skip)
{
    int old_flv_size, ret;
    PutByteContext pbc;
    const uint8_t *data = pkt->data + skip;
    const int size      = pkt->size - skip;
    uint32_t ts         = pkt->timestamp;

2213 2214 2215 2216 2217 2218
    if (pkt->type == RTMP_PT_AUDIO) {
        rt->has_audio = 1;
    } else if (pkt->type == RTMP_PT_VIDEO) {
        rt->has_video = 1;
    }

2219
    old_flv_size = update_offset(rt, size + 15);
Luca Barbato's avatar
Luca Barbato committed
2220

2221 2222
    if ((ret = av_reallocp(&rt->flv_data, rt->flv_size)) < 0) {
        rt->flv_size = rt->flv_off = 0;
Luca Barbato's avatar
Luca Barbato committed
2223
        return ret;
2224
    }
2225 2226 2227
    bytestream2_init_writer(&pbc, rt->flv_data, rt->flv_size);
    bytestream2_skip_p(&pbc, old_flv_size);
    bytestream2_put_byte(&pbc, pkt->type);
Luca Barbato's avatar
Luca Barbato committed
2228
    bytestream2_put_be24(&pbc, size);
2229 2230 2231
    bytestream2_put_be24(&pbc, ts);
    bytestream2_put_byte(&pbc, ts >> 24);
    bytestream2_put_be24(&pbc, 0);
Luca Barbato's avatar
Luca Barbato committed
2232
    bytestream2_put_buffer(&pbc, data, size);
2233
    bytestream2_put_be32(&pbc, size + RTMP_HEADER);
2234

2235 2236 2237
    return 0;
}

Luca Barbato's avatar
Luca Barbato committed
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
static int handle_notify(URLContext *s, RTMPPacket *pkt)
{
    RTMPContext *rt  = s->priv_data;
    uint8_t commandbuffer[64];
    char statusmsg[128];
    int stringlen, ret, skip = 0;
    GetByteContext gbc;

    bytestream2_init(&gbc, pkt->data, pkt->size);
    if (ff_amf_read_string(&gbc, commandbuffer, sizeof(commandbuffer),
                           &stringlen))
        return AVERROR_INVALIDDATA;

2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
    if (!strcmp(commandbuffer, "onMetaData")) {
        // metadata properties should be stored in a mixed array
        if (bytestream2_get_byte(&gbc) == AMF_DATA_TYPE_MIXEDARRAY) {
            // We have found a metaData Array so flv can determine the streams
            // from this.
            rt->received_metadata = 1;
            // skip 32-bit max array index
            bytestream2_skip(&gbc, 4);
            while (bytestream2_get_bytes_left(&gbc) > 3) {
                if (ff_amf_get_string(&gbc, statusmsg, sizeof(statusmsg),
                                      &stringlen))
                    return AVERROR_INVALIDDATA;
                // We do not care about the content of the property (yet).
                stringlen = ff_amf_tag_size(gbc.buffer, gbc.buffer_end);
                if (stringlen < 0)
                    return AVERROR_INVALIDDATA;
                bytestream2_skip(&gbc, stringlen);

                // The presence of the following properties indicates that the
                // respective streams are present.
                if (!strcmp(statusmsg, "videocodecid")) {
                    rt->has_video = 1;
                }
                if (!strcmp(statusmsg, "audiocodecid")) {
                    rt->has_audio = 1;
                }
            }
            if (bytestream2_get_be24(&gbc) != AMF_END_OF_OBJECT)
                return AVERROR_INVALIDDATA;
        }
    }

Luca Barbato's avatar
Luca Barbato committed
2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294
    // Skip the @setDataFrame string and validate it is a notification
    if (!strcmp(commandbuffer, "@setDataFrame")) {
        skip = gbc.buffer - pkt->data;
        ret = ff_amf_read_string(&gbc, statusmsg,
                                 sizeof(statusmsg), &stringlen);
        if (ret < 0)
            return AVERROR_INVALIDDATA;
    }

    return append_flv_data(rt, pkt, skip);
}

2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309
/**
 * Parse received packet and possibly perform some action depending on
 * the packet contents.
 * @return 0 for no errors, negative values for serious errors which prevent
 *         further communications, positive values for uncritical errors
 */
static int rtmp_parse_result(URLContext *s, RTMPContext *rt, RTMPPacket *pkt)
{
    int ret;

#ifdef DEBUG
    ff_rtmp_packet_dump(s, pkt);
#endif

    switch (pkt->type) {
2310
    case RTMP_PT_BYTES_READ:
2311
        av_log(s, AV_LOG_TRACE, "received bytes read report\n");
2312
        break;
2313 2314 2315 2316
    case RTMP_PT_CHUNK_SIZE:
        if ((ret = handle_chunk_size(s, pkt)) < 0)
            return ret;
        break;
2317 2318
    case RTMP_PT_USER_CONTROL:
        if ((ret = handle_user_control(s, pkt)) < 0)
2319 2320
            return ret;
        break;
2321 2322
    case RTMP_PT_SET_PEER_BW:
        if ((ret = handle_set_peer_bw(s, pkt)) < 0)
2323 2324
            return ret;
        break;
2325 2326
    case RTMP_PT_WINDOW_ACK_SIZE:
        if ((ret = handle_window_ack_size(s, pkt)) < 0)
2327 2328 2329 2330 2331
            return ret;
        break;
    case RTMP_PT_INVOKE:
        if ((ret = handle_invoke(s, pkt)) < 0)
            return ret;
2332
        break;
2333 2334
    case RTMP_PT_VIDEO:
    case RTMP_PT_AUDIO:
2335
    case RTMP_PT_METADATA:
2336
    case RTMP_PT_NOTIFY:
2337
        /* Audio, Video and Metadata packets are parsed in get_packet() */
2338
        break;
2339 2340 2341
    default:
        av_log(s, AV_LOG_VERBOSE, "Unknown packet type received 0x%02X\n", pkt->type);
        break;
2342 2343 2344 2345
    }
    return 0;
}

2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
static int handle_metadata(RTMPContext *rt, RTMPPacket *pkt)
{
    int ret, old_flv_size, type;
    const uint8_t *next;
    uint8_t *p;
    uint32_t size;
    uint32_t ts, cts, pts = 0;

    old_flv_size = update_offset(rt, pkt->size);

2356 2357
    if ((ret = av_reallocp(&rt->flv_data, rt->flv_size)) < 0) {
        rt->flv_size = rt->flv_off = 0;
2358
        return ret;
2359
    }
2360 2361 2362 2363 2364 2365 2366

    next = pkt->data;
    p    = rt->flv_data + old_flv_size;

    /* copy data while rewriting timestamps */
    ts = pkt->timestamp;

2367
    while (next - pkt->data < pkt->size - RTMP_HEADER) {
2368 2369 2370 2371 2372 2373 2374 2375
        type = bytestream_get_byte(&next);
        size = bytestream_get_be24(&next);
        cts  = bytestream_get_be24(&next);
        cts |= bytestream_get_byte(&next) << 24;
        if (!pts)
            pts = cts;
        ts += cts - pts;
        pts = cts;
2376 2377
        if (size + 3 + 4 > pkt->data + pkt->size - next)
            break;
2378 2379 2380 2381 2382
        bytestream_put_byte(&p, type);
        bytestream_put_be24(&p, size);
        bytestream_put_be24(&p, ts);
        bytestream_put_byte(&p, ts >> 24);
        memcpy(p, next, size + 3 + 4);
2383
        p    += size + 3;
2384
        bytestream_put_be32(&p, size + RTMP_HEADER);
2385 2386
        next += size + 3 + 4;
    }
2387
    if (p != rt->flv_data + rt->flv_size) {
2388
        av_log(rt, AV_LOG_WARNING, "Incomplete flv packets in "
2389 2390 2391
                                     "RTMP_PT_METADATA packet\n");
        rt->flv_size = p - rt->flv_data;
    }
2392 2393 2394 2395

    return 0;
}

2396
/**
2397
 * Interact with the server by receiving and sending RTMP packets until
2398 2399 2400
 * there is some significant data (media data or expected status notification).
 *
 * @param s          reading context
2401 2402 2403 2404
 * @param for_header non-zero value tells function to work until it
 * gets notification from the server that playing has been started,
 * otherwise function will work until some media data is received (or
 * an error happens)
2405 2406 2407 2408 2409 2410 2411
 * @return 0 for successful operation, negative value in case of error
 */
static int get_packet(URLContext *s, int for_header)
{
    RTMPContext *rt = s->priv_data;
    int ret;

2412 2413 2414
    if (rt->state == STATE_STOPPED)
        return AVERROR_EOF;

2415
    for (;;) {
2416
        RTMPPacket rpkt = { 0 };
2417
        if ((ret = ff_rtmp_packet_read(rt->stream, &rpkt,
2418 2419
                                       rt->in_chunk_size, &rt->prev_pkt[0],
                                       &rt->nb_prev_pkt[0])) <= 0) {
2420
            if (ret == 0) {
2421 2422 2423 2424 2425
                return AVERROR(EAGAIN);
            } else {
                return AVERROR(EIO);
            }
        }
2426 2427 2428 2429

        // Track timestamp for later use
        rt->last_timestamp = rpkt.timestamp;

2430
        rt->bytes_read += ret;
2431
        if (rt->bytes_read - rt->last_bytes_read > rt->receive_report_size) {
2432
            av_log(s, AV_LOG_DEBUG, "Sending bytes read report\n");
2433 2434
            if ((ret = gen_bytes_read(s, rt, rpkt.timestamp + 1)) < 0) {
                ff_rtmp_packet_destroy(&rpkt);
2435
                return ret;
2436
            }
2437 2438
            rt->last_bytes_read = rt->bytes_read;
        }
2439 2440

        ret = rtmp_parse_result(s, rt, &rpkt);
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451

        // At this point we must check if we are in the seek state and continue
        // with the next packet. handle_invoke will get us out of this state
        // when the right message is encountered
        if (rt->state == STATE_SEEKING) {
            ff_rtmp_packet_destroy(&rpkt);
            // We continue, let the natural flow of things happen:
            // AVERROR(EAGAIN) or handle_invoke gets us out of here
            continue;
        }

2452 2453
        if (ret < 0) {//serious error in current packet
            ff_rtmp_packet_destroy(&rpkt);
2454
            return ret;
2455
        }
2456 2457 2458 2459
        if (rt->do_reconnect && for_header) {
            ff_rtmp_packet_destroy(&rpkt);
            return 0;
        }
2460 2461 2462 2463
        if (rt->state == STATE_STOPPED) {
            ff_rtmp_packet_destroy(&rpkt);
            return AVERROR_EOF;
        }
2464 2465
        if (for_header && (rt->state == STATE_PLAYING    ||
                           rt->state == STATE_PUBLISHING ||
2466
                           rt->state == STATE_SENDING    ||
2467
                           rt->state == STATE_RECEIVING)) {
2468 2469 2470
            ff_rtmp_packet_destroy(&rpkt);
            return 0;
        }
2471
        if (!rpkt.size || !rt->is_input) {
2472 2473 2474
            ff_rtmp_packet_destroy(&rpkt);
            continue;
        }
Luca Barbato's avatar
Luca Barbato committed
2475 2476
        if (rpkt.type == RTMP_PT_VIDEO || rpkt.type == RTMP_PT_AUDIO) {
            ret = append_flv_data(rt, &rpkt, 0);
2477
            ff_rtmp_packet_destroy(&rpkt);
Luca Barbato's avatar
Luca Barbato committed
2478
            return ret;
2479 2480 2481
        } else if (rpkt.type == RTMP_PT_NOTIFY) {
            ret = handle_notify(s, &rpkt);
            ff_rtmp_packet_destroy(&rpkt);
Luca Barbato's avatar
Luca Barbato committed
2482
            return ret;
2483
        } else if (rpkt.type == RTMP_PT_METADATA) {
2484
            ret = handle_metadata(rt, &rpkt);
2485
            ff_rtmp_packet_destroy(&rpkt);
2486
            return ret;
2487 2488 2489 2490 2491 2492 2493 2494
        }
        ff_rtmp_packet_destroy(&rpkt);
    }
}

static int rtmp_close(URLContext *h)
{
    RTMPContext *rt = h->priv_data;
2495
    int ret = 0, i, j;
2496

2497
    if (!rt->is_input) {
2498
        rt->flv_data = NULL;
2499
        if (rt->out_pkt.size)
2500
            ff_rtmp_packet_destroy(&rt->out_pkt);
2501
        if (rt->state > STATE_FCPUBLISH)
2502
            ret = gen_fcunpublish_stream(h, rt);
2503
    }
2504
    if (rt->state > STATE_HANDSHAKED)
2505
        ret = gen_delete_stream(h, rt);
2506 2507
    for (i = 0; i < 2; i++) {
        for (j = 0; j < rt->nb_prev_pkt[i]; j++)
2508
            ff_rtmp_packet_destroy(&rt->prev_pkt[i][j]);
2509 2510
        av_freep(&rt->prev_pkt[i]);
    }
2511

2512
    free_tracked_methods(rt);
2513
    av_freep(&rt->flv_data);
2514
    ffurl_close(rt->stream);
2515
    return ret;
2516 2517
}

2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
/**
 * Insert a fake onMetadata packet into the FLV stream to notify the FLV
 * demuxer about the duration of the stream.
 *
 * This should only be done if there was no real onMetadata packet sent by the
 * server at the start of the stream and if we were able to retrieve a valid
 * duration via a getStreamLength call.
 *
 * @return 0 for successful operation, negative value in case of error
 */
static int inject_fake_duration_metadata(RTMPContext *rt)
{
2530
    // We need to insert the metadata packet directly after the FLV
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
    // header, i.e. we need to move all other already read data by the
    // size of our fake metadata packet.

    uint8_t* p;
    // Keep old flv_data pointer
    uint8_t* old_flv_data = rt->flv_data;
    // Allocate a new flv_data pointer with enough space for the additional package
    if (!(rt->flv_data = av_malloc(rt->flv_size + 55))) {
        rt->flv_data = old_flv_data;
        return AVERROR(ENOMEM);
    }

    // Copy FLV header
    memcpy(rt->flv_data, old_flv_data, 13);
    // Copy remaining packets
    memcpy(rt->flv_data + 13 + 55, old_flv_data + 13, rt->flv_size - 13);
    // Increase the size by the injected packet
    rt->flv_size += 55;
    // Delete the old FLV data
2550
    av_freep(&old_flv_data);
2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576

    p = rt->flv_data + 13;
    bytestream_put_byte(&p, FLV_TAG_TYPE_META);
    bytestream_put_be24(&p, 40); // size of data part (sum of all parts below)
    bytestream_put_be24(&p, 0);  // timestamp
    bytestream_put_be32(&p, 0);  // reserved

    // first event name as a string
    bytestream_put_byte(&p, AMF_DATA_TYPE_STRING);
    // "onMetaData" as AMF string
    bytestream_put_be16(&p, 10);
    bytestream_put_buffer(&p, "onMetaData", 10);

    // mixed array (hash) with size and string/type/data tuples
    bytestream_put_byte(&p, AMF_DATA_TYPE_MIXEDARRAY);
    bytestream_put_be32(&p, 1); // metadata_count

    // "duration" as AMF string
    bytestream_put_be16(&p, 8);
    bytestream_put_buffer(&p, "duration", 8);
    bytestream_put_byte(&p, AMF_DATA_TYPE_NUMBER);
    bytestream_put_be64(&p, av_double2int(rt->duration));

    // Finalise object
    bytestream_put_be16(&p, 0); // Empty string
    bytestream_put_byte(&p, AMF_END_OF_OBJECT);
2577
    bytestream_put_be32(&p, 40 + RTMP_HEADER); // size of data part (sum of all parts above)
2578 2579 2580 2581

    return 0;
}

2582
/**
2583
 * Open RTMP connection and verify that the stream can be played.
2584 2585 2586 2587 2588 2589 2590
 *
 * URL syntax: rtmp://server[:port][/app][/playpath]
 *             where 'app' is first one or two directories in the path
 *             (e.g. /ondemand/, /flash/live/, etc.)
 *             and 'playpath' is a file name (the rest of the path,
 *             may be prefixed with "mp4:")
 */
2591
static int rtmp_open(URLContext *s, const char *uri, int flags, AVDictionary **opts)
2592
{
2593
    RTMPContext *rt = s->priv_data;
2594
    char proto[8], hostname[256], path[1024], auth[100], *fname;
2595
    char *old_app, *qmark, *n, fname_buffer[1024];
2596
    uint8_t buf[2048];
2597
    int port;
2598 2599
    int ret;

2600 2601 2602
    if (rt->listen_timeout > 0)
        rt->listen = 1;

2603
    rt->is_input = !(flags & AVIO_FLAG_WRITE);
2604

2605 2606
    av_url_split(proto, sizeof(proto), auth, sizeof(auth),
                 hostname, sizeof(hostname), &port,
Martin Storsjö's avatar
Martin Storsjö committed
2607
                 path, sizeof(path), s->filename);
2608

2609 2610
    n = strchr(path, ' ');
    if (n) {
2611 2612 2613 2614
        av_log(s, AV_LOG_WARNING,
               "Detected librtmp style URL parameters, these aren't supported "
               "by the libavformat internal RTMP handler currently enabled. "
               "See the documentation for the correct way to pass parameters.\n");
2615
        *n = '\0'; // Trim not supported part
2616 2617
    }

2618 2619 2620 2621 2622 2623 2624 2625 2626
    if (auth[0]) {
        char *ptr = strchr(auth, ':');
        if (ptr) {
            *ptr = '\0';
            av_strlcpy(rt->username, auth, sizeof(rt->username));
            av_strlcpy(rt->password, ptr + 1, sizeof(rt->password));
        }
    }

2627 2628 2629 2630 2631
    if (rt->listen && strcmp(proto, "rtmp")) {
        av_log(s, AV_LOG_ERROR, "rtmp_listen not available for %s\n",
               proto);
        return AVERROR(EINVAL);
    }
2632 2633
    if (!strcmp(proto, "rtmpt") || !strcmp(proto, "rtmpts")) {
        if (!strcmp(proto, "rtmpts"))
2634
            av_dict_set(opts, "ffrtmphttp_tls", "1", 1);
2635

Samuel Pitoiset's avatar
Samuel Pitoiset committed
2636
        /* open the http tunneling connection */
2637
        ff_url_join(buf, sizeof(buf), "ffrtmphttp", NULL, hostname, port, NULL);
Samuel Pitoiset's avatar
Samuel Pitoiset committed
2638 2639 2640 2641 2642
    } else if (!strcmp(proto, "rtmps")) {
        /* open the tls connection */
        if (port < 0)
            port = RTMPS_DEFAULT_PORT;
        ff_url_join(buf, sizeof(buf), "tls", NULL, hostname, port, NULL);
2643 2644
    } else if (!strcmp(proto, "rtmpe") || (!strcmp(proto, "rtmpte"))) {
        if (!strcmp(proto, "rtmpte"))
2645
            av_dict_set(opts, "ffrtmpcrypt_tunneling", "1", 1);
2646

Samuel Pitoiset's avatar
Samuel Pitoiset committed
2647 2648 2649
        /* open the encrypted connection */
        ff_url_join(buf, sizeof(buf), "ffrtmpcrypt", NULL, hostname, port, NULL);
        rt->encrypted = 1;
Samuel Pitoiset's avatar
Samuel Pitoiset committed
2650 2651 2652 2653
    } else {
        /* open the tcp connection */
        if (port < 0)
            port = RTMP_DEFAULT_PORT;
2654 2655 2656 2657 2658 2659
        if (rt->listen)
            ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port,
                        "?listen&listen_timeout=%d",
                        rt->listen_timeout * 1000);
        else
            ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
Samuel Pitoiset's avatar
Samuel Pitoiset committed
2660
    }
2661

2662
reconnect:
2663
    if ((ret = ffurl_open_whitelist(&rt->stream, buf, AVIO_FLAG_READ_WRITE,
2664
                                    &s->interrupt_callback, opts,
2665
                                    s->protocol_whitelist, s->protocol_blacklist, s)) < 0) {
2666
        av_log(s , AV_LOG_ERROR, "Cannot open connection %s\n", buf);
2667
        goto fail;
2668
    }
2669

2670 2671 2672 2673 2674
    if (rt->swfverify) {
        if ((ret = rtmp_calc_swfhash(s)) < 0)
            goto fail;
    }

2675
    rt->state = STATE_START;
2676 2677 2678
    if (!rt->listen && (ret = rtmp_handshake(s, rt)) < 0)
        goto fail;
    if (rt->listen && (ret = rtmp_server_handshake(s, rt)) < 0)
2679
        goto fail;
2680

2681 2682
    rt->out_chunk_size = 128;
    rt->in_chunk_size  = 128; // Probably overwritten later
2683
    rt->state = STATE_HANDSHAKED;
2684 2685 2686 2687 2688 2689

    // Keep the application name when it has been defined by the user.
    old_app = rt->app;

    rt->app = av_malloc(APP_MAX_LENGTH);
    if (!rt->app) {
2690 2691
        ret = AVERROR(ENOMEM);
        goto fail;
2692 2693
    }

2694
    //extract "app" part from path
2695 2696 2697
    qmark = strchr(path, '?');
    if (qmark && strstr(qmark, "slist=")) {
        char* amp;
2698 2699
        // After slist we have the playpath, the full path is used as app
        av_strlcpy(rt->app, path + 1, APP_MAX_LENGTH);
2700 2701 2702 2703
        fname = strstr(path, "slist=") + 6;
        // Strip any further query parameters from fname
        amp = strchr(fname, '&');
        if (amp) {
2704 2705
            av_strlcpy(fname_buffer, fname, FFMIN(amp - fname + 1,
                                                  sizeof(fname_buffer)));
2706 2707 2708
            fname = fname_buffer;
        }
    } else if (!strncmp(path, "/ondemand/", 10)) {
2709 2710 2711
        fname = path + 10;
        memcpy(rt->app, "ondemand", 9);
    } else {
2712 2713
        char *next = *path ? path + 1 : path;
        char *p = strchr(next, '/');
2714
        if (!p) {
2715 2716 2717 2718 2719 2720 2721 2722
            if (old_app) {
                // If name of application has been defined by the user, assume that
                // playpath is provided in the URL
                fname = next;
            } else {
                fname = NULL;
                av_strlcpy(rt->app, next, APP_MAX_LENGTH);
            }
2723
        } else {
Luca Barbato's avatar
Luca Barbato committed
2724
            // make sure we do not mismatch a playpath for an application instance
2725 2726
            char *c = strchr(p + 1, ':');
            fname = strchr(p + 1, '/');
Luca Barbato's avatar
Luca Barbato committed
2727
            if (!fname || (c && c < fname)) {
2728
                fname = p + 1;
2729
                av_strlcpy(rt->app, path + 1, FFMIN(p - path, APP_MAX_LENGTH));
2730
            } else {
2731
                fname++;
2732
                av_strlcpy(rt->app, path + 1, FFMIN(fname - path - 1, APP_MAX_LENGTH));
2733 2734
            }
        }
2735
    }
2736 2737 2738

    if (old_app) {
        // The name of application has been defined by the user, override it.
2739 2740 2741 2742
        if (strlen(old_app) >= APP_MAX_LENGTH) {
            ret = AVERROR(EINVAL);
            goto fail;
        }
2743 2744 2745 2746
        av_free(rt->app);
        rt->app = old_app;
    }

2747
    if (!rt->playpath) {
2748 2749 2750 2751
        int max_len = 1;
        if (fname)
            max_len = strlen(fname) + 5; // add prefix "mp4:"
        rt->playpath = av_malloc(max_len);
2752
        if (!rt->playpath) {
2753 2754
            ret = AVERROR(ENOMEM);
            goto fail;
2755 2756
        }

2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767
        if (fname) {
            int len = strlen(fname);
            if (!strchr(fname, ':') && len >= 4 &&
                (!strcmp(fname + len - 4, ".f4v") ||
                 !strcmp(fname + len - 4, ".mp4"))) {
                memcpy(rt->playpath, "mp4:", 5);
            } else {
                if (len >= 4 && !strcmp(fname + len - 4, ".flv"))
                    fname[len - 4] = '\0';
                rt->playpath[0] = 0;
            }
2768
            av_strlcat(rt->playpath, fname, max_len);
2769
        } else {
2770
            rt->playpath[0] = '\0';
2771
        }
2772
    }
2773

2774 2775
    if (!rt->tcurl) {
        rt->tcurl = av_malloc(TCURL_MAX_LENGTH);
2776 2777 2778 2779
        if (!rt->tcurl) {
            ret = AVERROR(ENOMEM);
            goto fail;
        }
2780 2781 2782 2783
        ff_url_join(rt->tcurl, TCURL_MAX_LENGTH, proto, NULL, hostname,
                    port, "/%s", rt->app);
    }

2784 2785
    if (!rt->flashver) {
        rt->flashver = av_malloc(FLASHVER_MAX_LENGTH);
2786 2787 2788 2789
        if (!rt->flashver) {
            ret = AVERROR(ENOMEM);
            goto fail;
        }
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799
        if (rt->is_input) {
            snprintf(rt->flashver, FLASHVER_MAX_LENGTH, "%s %d,%d,%d,%d",
                    RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1, RTMP_CLIENT_VER2,
                    RTMP_CLIENT_VER3, RTMP_CLIENT_VER4);
        } else {
            snprintf(rt->flashver, FLASHVER_MAX_LENGTH,
                    "FMLE/3.0 (compatible; %s)", LIBAVFORMAT_IDENT);
        }
    }

2800
    rt->receive_report_size = 1048576;
2801
    rt->bytes_read = 0;
2802 2803 2804
    rt->has_audio = 0;
    rt->has_video = 0;
    rt->received_metadata = 0;
2805
    rt->last_bytes_read = 0;
2806
    rt->max_sent_unacked = 2500000;
2807
    rt->duration = 0;
2808

2809
    av_log(s, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n",
2810
           proto, path, rt->app, rt->playpath);
2811 2812 2813 2814
    if (!rt->listen) {
        if ((ret = gen_connect(s, rt)) < 0)
            goto fail;
    } else {
2815
        if ((ret = read_connect(s, s->priv_data)) < 0)
2816 2817
            goto fail;
    }
2818

2819 2820
    do {
        ret = get_packet(s, 1);
2821
    } while (ret == AVERROR(EAGAIN));
2822 2823
    if (ret < 0)
        goto fail;
2824

2825
    if (rt->do_reconnect) {
2826
        int i;
2827 2828 2829 2830
        ffurl_close(rt->stream);
        rt->stream       = NULL;
        rt->do_reconnect = 0;
        rt->nb_invokes   = 0;
2831 2832 2833
        for (i = 0; i < 2; i++)
            memset(rt->prev_pkt[i], 0,
                   sizeof(**rt->prev_pkt) * rt->nb_prev_pkt[i]);
2834 2835 2836 2837
        free_tracked_methods(rt);
        goto reconnect;
    }

2838
    if (rt->is_input) {
2839 2840
        // generate FLV header for demuxer
        rt->flv_size = 13;
2841 2842
        if ((ret = av_reallocp(&rt->flv_data, rt->flv_size)) < 0)
            goto fail;
2843
        rt->flv_off  = 0;
2844 2845 2846 2847 2848 2849 2850 2851 2852
        memcpy(rt->flv_data, "FLV\1\0\0\0\0\011\0\0\0\0", rt->flv_size);

        // Read packets until we reach the first A/V packet or read metadata.
        // If there was a metadata package in front of the A/V packets, we can
        // build the FLV header from this. If we do not receive any metadata,
        // the FLV decoder will allocate the needed streams when their first
        // audio or video packet arrives.
        while (!rt->has_audio && !rt->has_video && !rt->received_metadata) {
            if ((ret = get_packet(s, 0)) < 0)
2853
               goto fail;
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
        }

        // Either after we have read the metadata or (if there is none) the
        // first packet of an A/V stream, we have a better knowledge about the
        // streams, so set the FLV header accordingly.
        if (rt->has_audio) {
            rt->flv_data[4] |= FLV_HEADER_FLAG_HASAUDIO;
        }
        if (rt->has_video) {
            rt->flv_data[4] |= FLV_HEADER_FLAG_HASVIDEO;
        }
2865 2866 2867 2868 2869 2870 2871 2872

        // If we received the first packet of an A/V stream and no metadata but
        // the server returned a valid duration, create a fake metadata packet
        // to inform the FLV decoder about the duration.
        if (!rt->received_metadata && rt->duration > 0) {
            if ((ret = inject_fake_duration_metadata(rt)) < 0)
                goto fail;
        }
2873 2874 2875 2876
    } else {
        rt->flv_size = 0;
        rt->flv_data = NULL;
        rt->flv_off  = 0;
2877
        rt->skip_bytes = 13;
2878 2879
    }

2880
    s->max_packet_size = rt->stream->max_packet_size;
2881 2882 2883 2884
    s->is_streamed     = 1;
    return 0;

fail:
2885 2886 2887
    av_freep(&rt->playpath);
    av_freep(&rt->tcurl);
    av_freep(&rt->flashver);
2888
    av_dict_free(opts);
2889
    rtmp_close(s);
2890
    return ret;
2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911
}

static int rtmp_read(URLContext *s, uint8_t *buf, int size)
{
    RTMPContext *rt = s->priv_data;
    int orig_size = size;
    int ret;

    while (size > 0) {
        int data_left = rt->flv_size - rt->flv_off;

        if (data_left >= size) {
            memcpy(buf, rt->flv_data + rt->flv_off, size);
            rt->flv_off += size;
            return orig_size;
        }
        if (data_left > 0) {
            memcpy(buf, rt->flv_data + rt->flv_off, data_left);
            buf  += data_left;
            size -= data_left;
            rt->flv_off = rt->flv_size;
2912
            return data_left;
2913 2914 2915 2916 2917 2918 2919
        }
        if ((ret = get_packet(s, 0)) < 0)
           return ret;
    }
    return orig_size;
}

2920 2921 2922 2923 2924 2925
static int64_t rtmp_seek(URLContext *s, int stream_index, int64_t timestamp,
                         int flags)
{
    RTMPContext *rt = s->priv_data;
    int ret;
    av_log(s, AV_LOG_DEBUG,
2926
           "Seek on stream index %d at timestamp %"PRId64" with flags %08x\n",
2927 2928 2929
           stream_index, timestamp, flags);
    if ((ret = gen_seek(s, rt, timestamp)) < 0) {
        av_log(s, AV_LOG_ERROR,
2930 2931
               "Unable to send seek command on stream index %d at timestamp "
               "%"PRId64" with flags %08x\n",
2932 2933 2934 2935 2936 2937 2938 2939
               stream_index, timestamp, flags);
        return ret;
    }
    rt->flv_off = rt->flv_size;
    rt->state = STATE_SEEKING;
    return timestamp;
}

2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953
static int rtmp_pause(URLContext *s, int pause)
{
    RTMPContext *rt = s->priv_data;
    int ret;
    av_log(s, AV_LOG_DEBUG, "Pause at timestamp %d\n",
           rt->last_timestamp);
    if ((ret = gen_pause(s, rt, pause, rt->last_timestamp)) < 0) {
        av_log(s, AV_LOG_ERROR, "Unable to send pause command at timestamp %d\n",
               rt->last_timestamp);
        return ret;
    }
    return 0;
}

2954
static int rtmp_write(URLContext *s, const uint8_t *buf, int size)
2955
{
2956
    RTMPContext *rt = s->priv_data;
2957
    int size_temp = size;
2958
    int pktsize, pkttype, copy;
2959 2960
    uint32_t ts;
    const uint8_t *buf_temp = buf;
2961
    uint8_t c;
2962
    int ret;
2963 2964

    do {
2965 2966 2967 2968 2969 2970 2971 2972
        if (rt->skip_bytes) {
            int skip = FFMIN(rt->skip_bytes, size_temp);
            buf_temp       += skip;
            size_temp      -= skip;
            rt->skip_bytes -= skip;
            continue;
        }

2973
        if (rt->flv_header_bytes < RTMP_HEADER) {
2974
            const uint8_t *header = rt->flv_header;
2975
            int channel = RTMP_AUDIO_CHANNEL;
2976

2977
            copy = FFMIN(RTMP_HEADER - rt->flv_header_bytes, size_temp);
2978 2979 2980
            bytestream_get_buffer(&buf_temp, rt->flv_header + rt->flv_header_bytes, copy);
            rt->flv_header_bytes += copy;
            size_temp            -= copy;
2981
            if (rt->flv_header_bytes < RTMP_HEADER)
2982
                break;
2983

2984 2985 2986 2987 2988
            pkttype = bytestream_get_byte(&header);
            pktsize = bytestream_get_be24(&header);
            ts = bytestream_get_be24(&header);
            ts |= bytestream_get_byte(&header) << 24;
            bytestream_get_be24(&header);
2989 2990
            rt->flv_size = pktsize;

2991 2992 2993
            if (pkttype == RTMP_PT_VIDEO)
                channel = RTMP_VIDEO_CHANNEL;

2994 2995
            if (((pkttype == RTMP_PT_VIDEO || pkttype == RTMP_PT_AUDIO) && ts == 0) ||
                pkttype == RTMP_PT_NOTIFY) {
2996 2997 2998 2999
                if ((ret = ff_rtmp_check_alloc_array(&rt->prev_pkt[1],
                                                     &rt->nb_prev_pkt[1],
                                                     channel)) < 0)
                    return ret;
3000
                // Force sending a full 12 bytes header by clearing the
3001 3002
                // channel id, to make it not match a potential earlier
                // packet in the same channel.
3003
                rt->prev_pkt[1][channel].channel_id = 0;
3004 3005 3006
            }

            //this can be a big packet, it's better to send it right here
3007
            if ((ret = ff_rtmp_packet_create(&rt->out_pkt, channel,
3008 3009 3010
                                             pkttype, ts, pktsize)) < 0)
                return ret;

3011
            rt->out_pkt.extra = rt->stream_id;
3012 3013 3014
            rt->flv_data = rt->out_pkt.data;
        }

3015 3016 3017 3018
        copy = FFMIN(rt->flv_size - rt->flv_off, size_temp);
        bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, copy);
        rt->flv_off += copy;
        size_temp   -= copy;
3019 3020

        if (rt->flv_off == rt->flv_size) {
3021 3022
            rt->skip_bytes = 4;

3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
            if (rt->out_pkt.type == RTMP_PT_NOTIFY) {
                // For onMetaData and |RtmpSampleAccess packets, we want
                // @setDataFrame prepended to the packet before it gets sent.
                // However, not all RTMP_PT_NOTIFY packets (e.g., onTextData
                // and onCuePoint).
                uint8_t commandbuffer[64];
                int stringlen = 0;
                GetByteContext gbc;

                bytestream2_init(&gbc, rt->flv_data, rt->flv_size);
                if (!ff_amf_read_string(&gbc, commandbuffer, sizeof(commandbuffer),
                                        &stringlen)) {
                    if (!strcmp(commandbuffer, "onMetaData") ||
                        !strcmp(commandbuffer, "|RtmpSampleAccess")) {
                        uint8_t *ptr;
                        if ((ret = av_reallocp(&rt->out_pkt.data, rt->out_pkt.size + 16)) < 0) {
                            rt->flv_size = rt->flv_off = rt->flv_header_bytes = 0;
                            return ret;
                        }
                        memmove(rt->out_pkt.data + 16, rt->out_pkt.data, rt->out_pkt.size);
                        rt->out_pkt.size += 16;
                        ptr = rt->out_pkt.data;
                        ff_amf_write_string(&ptr, "@setDataFrame");
                    }
                }
            }

3050
            if ((ret = rtmp_send_packet(rt, &rt->out_pkt, 0)) < 0)
3051
                return ret;
3052 3053
            rt->flv_size = 0;
            rt->flv_off = 0;
3054
            rt->flv_header_bytes = 0;
3055
            rt->flv_nb_packets++;
3056
        }
3057
    } while (buf_temp - buf < size);
3058

3059 3060 3061 3062
    if (rt->flv_nb_packets < rt->flush_interval)
        return size;
    rt->flv_nb_packets = 0;

3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
    /* set stream into nonblocking mode */
    rt->stream->flags |= AVIO_FLAG_NONBLOCK;

    /* try to read one byte from the stream */
    ret = ffurl_read(rt->stream, &c, 1);

    /* switch the stream back into blocking mode */
    rt->stream->flags &= ~AVIO_FLAG_NONBLOCK;

    if (ret == AVERROR(EAGAIN)) {
        /* no incoming data to handle */
        return size;
    } else if (ret < 0) {
        return ret;
    } else if (ret == 1) {
        RTMPPacket rpkt = { 0 };

        if ((ret = ff_rtmp_packet_read_internal(rt->stream, &rpkt,
3081
                                                rt->in_chunk_size,
3082 3083
                                                &rt->prev_pkt[0],
                                                &rt->nb_prev_pkt[0], c)) <= 0)
3084 3085 3086 3087 3088 3089 3090 3091
             return ret;

        if ((ret = rtmp_parse_result(s, rt, &rpkt)) < 0)
            return ret;

        ff_rtmp_packet_destroy(&rpkt);
    }

3092
    return size;
3093 3094
}

3095 3096 3097 3098 3099 3100
#define OFFSET(x) offsetof(RTMPContext, x)
#define DEC AV_OPT_FLAG_DECODING_PARAM
#define ENC AV_OPT_FLAG_ENCODING_PARAM

static const AVOption rtmp_options[] = {
    {"rtmp_app", "Name of application to connect to on the RTMP server", OFFSET(app), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
3101
    {"rtmp_buffer", "Set buffer time in milliseconds. The default is 3000.", OFFSET(client_buffer_time), AV_OPT_TYPE_INT, {.i64 = 3000}, 0, INT_MAX, DEC|ENC},
3102
    {"rtmp_conn", "Append arbitrary AMF data to the Connect message", OFFSET(conn), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
3103
    {"rtmp_flashver", "Version of the Flash plugin used to run the SWF player.", OFFSET(flashver), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
3104 3105
    {"rtmp_flush_interval", "Number of packets flushed in the same request (RTMPT only).", OFFSET(flush_interval), AV_OPT_TYPE_INT, {.i64 = 10}, 0, INT_MAX, ENC},
    {"rtmp_live", "Specify that the media is a live stream.", OFFSET(live), AV_OPT_TYPE_INT, {.i64 = -2}, INT_MIN, INT_MAX, DEC, "rtmp_live"},
3106 3107 3108
    {"any", "both", 0, AV_OPT_TYPE_CONST, {.i64 = -2}, 0, 0, DEC, "rtmp_live"},
    {"live", "live stream", 0, AV_OPT_TYPE_CONST, {.i64 = -1}, 0, 0, DEC, "rtmp_live"},
    {"recorded", "recorded stream", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, DEC, "rtmp_live"},
3109
    {"rtmp_pageurl", "URL of the web page in which the media was embedded. By default no value will be sent.", OFFSET(pageurl), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC},
3110
    {"rtmp_playpath", "Stream identifier to play or to publish", OFFSET(playpath), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
3111
    {"rtmp_subscribe", "Name of live stream to subscribe to. Defaults to rtmp_playpath.", OFFSET(subscribe), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC},
3112
    {"rtmp_swfhash", "SHA256 hash of the decompressed SWF file (32 bytes).", OFFSET(swfhash), AV_OPT_TYPE_BINARY, .flags = DEC},
3113
    {"rtmp_swfsize", "Size of the decompressed SWF file, required for SWFVerification.", OFFSET(swfsize), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC},
3114
    {"rtmp_swfurl", "URL of the SWF player. By default no value will be sent", OFFSET(swfurl), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
3115
    {"rtmp_swfverify", "URL to player swf file, compute hash/size automatically.", OFFSET(swfverify), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC},
3116
    {"rtmp_tcurl", "URL of the target stream. Defaults to proto://host[:port]/app.", OFFSET(tcurl), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
3117
    {"rtmp_listen", "Listen for incoming rtmp connections", OFFSET(listen), AV_OPT_TYPE_INT, {.i64 = 0}, INT_MIN, INT_MAX, DEC, "rtmp_listen" },
3118
    {"listen",      "Listen for incoming rtmp connections", OFFSET(listen), AV_OPT_TYPE_INT, {.i64 = 0}, INT_MIN, INT_MAX, DEC, "rtmp_listen" },
3119
    {"timeout", "Maximum timeout (in seconds) to wait for incoming connections. -1 is infinite. Implies -rtmp_listen 1",  OFFSET(listen_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, DEC, "rtmp_listen" },
3120 3121 3122
    { NULL },
};

3123 3124 3125 3126 3127 3128 3129 3130
#define RTMP_PROTOCOL(flavor)                    \
static const AVClass flavor##_class = {          \
    .class_name = #flavor,                       \
    .item_name  = av_default_item_name,          \
    .option     = rtmp_options,                  \
    .version    = LIBAVUTIL_VERSION_INT,         \
};                                               \
                                                 \
3131
const URLProtocol ff_##flavor##_protocol = {     \
3132
    .name           = #flavor,                   \
3133
    .url_open2      = rtmp_open,                 \
3134
    .url_read       = rtmp_read,                 \
3135
    .url_read_seek  = rtmp_seek,                 \
3136
    .url_read_pause = rtmp_pause,                \
3137 3138 3139 3140 3141
    .url_write      = rtmp_write,                \
    .url_close      = rtmp_close,                \
    .priv_data_size = sizeof(RTMPContext),       \
    .flags          = URL_PROTOCOL_FLAG_NETWORK, \
    .priv_data_class= &flavor##_class,           \
3142
};
Samuel Pitoiset's avatar
Samuel Pitoiset committed
3143

Samuel Pitoiset's avatar
Samuel Pitoiset committed
3144

3145 3146 3147 3148 3149 3150
RTMP_PROTOCOL(rtmp)
RTMP_PROTOCOL(rtmpe)
RTMP_PROTOCOL(rtmps)
RTMP_PROTOCOL(rtmpt)
RTMP_PROTOCOL(rtmpte)
RTMP_PROTOCOL(rtmpts)