rtmpproto.c 80.2 KB
Newer Older
1 2 3 4
/*
 * RTMP network protocol
 * Copyright (c) 2009 Kostya Shishkov
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav is free software; you can redistribute it and/or
8 9 10 11
 * 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.
 *
12
 * Libav is distributed in the hope that it will be useful,
13 14 15 16 17
 * 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
18
 * License along with Libav; if not, write to the Free Software
19 20 21 22
 * 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/intfloat.h"
30
#include "libavutil/lfg.h"
31
#include "libavutil/opt.h"
32
#include "libavutil/random_seed.h"
33 34
#include "libavutil/sha.h"
#include "avformat.h"
35
#include "internal.h"
36 37 38 39 40

#include "network.h"

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

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

49 50
//#define DEBUG

51
#define APP_MAX_LENGTH 128
52
#define PLAYPATH_MAX_LENGTH 256
53
#define TCURL_MAX_LENGTH 512
54
#define FLASHVER_MAX_LENGTH 64
55
#define RTMP_PKTDATA_DEFAULT_SIZE 4096
56

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

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

73 74
/** protocol handler context */
typedef struct RTMPContext {
75
    const AVClass *class;
76 77
    URLContext*   stream;                     ///< TCP stream used in interactions with RTMP server
    RTMPPacket    prev_pkt[2][RTMP_CHANNELS]; ///< packet history used when reading and sending packets
78 79
    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
80
    int           is_input;                   ///< input/output flag
81
    char          *playpath;                  ///< stream identifier to play (with possible "mp4:" prefix)
82
    int           live;                       ///< 0: recorded, -1: live, -2: both
83
    char          *app;                       ///< name of application
84
    char          *conn;                      ///< append arbitrary AMF data to the Connect message
85 86 87 88 89
    ClientState   state;                      ///< current state
    int           main_channel_id;            ///< an additional channel ID which is used for some invocations
    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
90
    int           flv_nb_packets;             ///< number of flv packets published
91
    RTMPPacket    out_pkt;                    ///< rtmp packet, created from flv a/v or metadata (for output)
92 93 94
    uint32_t      client_report_size;         ///< number of bytes after which client should report to server
    uint32_t      bytes_read;                 ///< number of bytes read from server
    uint32_t      last_bytes_read;            ///< number of bytes read last reported to server
95
    int           skip_bytes;                 ///< number of bytes to skip from the input FLV stream in the next write call
96 97
    uint8_t       flv_header[11];             ///< partial incoming flv packet header
    int           flv_header_bytes;           ///< number of initialized bytes in flv_header
98
    int           nb_invokes;                 ///< keeps track of invoke messages
99
    char*         tcurl;                      ///< url of the target stream
100
    char*         flashver;                   ///< version of the flash plugin
101 102 103
    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
104
    char*         swfurl;                     ///< url of the swf player
105
    char*         swfverify;                  ///< URL to player swf file, compute hash/size automatically
106
    char          swfverification[42];        ///< hash of the SWF verification
107
    char*         pageurl;                    ///< url of the web page
108
    char*         subscribe;                  ///< name of live stream to subscribe
109
    int           server_bw;                  ///< server bandwidth
110
    int           client_buffer_time;         ///< client buffer time in ms
111
    int           flush_interval;             ///< number of packets flushed in the same request (RTMPT only)
Samuel Pitoiset's avatar
Samuel Pitoiset committed
112
    int           encrypted;                  ///< use an encrypted connection (RTMPE only)
113 114 115
    TrackedMethod*tracked_methods;            ///< tracked methods buffer
    int           nb_tracked_methods;         ///< number of tracked methods
    int           tracked_methods_size;       ///< size of the tracked methods buffer
116 117 118
    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
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
} 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
};

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
static int add_tracked_method(RTMPContext *rt, const char *name, int id)
{
    void *ptr;

    if (rt->nb_tracked_methods + 1 > rt->tracked_methods_size) {
        rt->tracked_methods_size = (rt->nb_tracked_methods + 1) * 2;
        ptr = av_realloc(rt->tracked_methods,
                         rt->tracked_methods_size * sizeof(*rt->tracked_methods));
        if (!ptr)
            return AVERROR(ENOMEM);
        rt->tracked_methods = ptr;
    }

    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--;
}

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
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;

    bytestream2_init(&gbc, pkt->data + offset, pkt->data_size - offset);
    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;
}

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
static void free_tracked_methods(RTMPContext *rt)
{
    int i;

    for (i = 0; i < rt->nb_tracked_methods; i ++)
        av_free(rt->tracked_methods[i].name);
    av_free(rt->tracked_methods);
}

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;

        bytestream2_init(&gbc, pkt->data, pkt->data_size);
        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;
    }

228
    ret = ff_rtmp_packet_write(rt->stream, pkt, rt->out_chunk_size,
229 230 231 232 233 234
                               rt->prev_pkt[1]);
fail:
    ff_rtmp_packet_destroy(pkt);
    return ret;
}

235 236
static int rtmp_write_amf_data(URLContext *s, char *param, uint8_t **p)
{
237
    char *field, *value;
238 239 240 241 242 243 244 245 246 247 248 249 250 251
    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];
252 253 254 255 256 257
        field = param + 3;
        value = strchr(field, ':');
        if (!value)
            goto fail;
        *value = '\0';
        value++;
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297

        if (!field || !value)
            goto fail;

        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);
}

298
/**
299
 * Generate 'connect' call and send it to the server.
300
 */
301
static int gen_connect(URLContext *s, RTMPContext *rt)
302 303
{
    RTMPPacket pkt;
304
    uint8_t *p;
305 306 307 308 309
    int ret;

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 4096)) < 0)
        return ret;
310 311 312 313

    p = pkt.data;

    ff_amf_write_string(&p, "connect");
314
    ff_amf_write_number(&p, ++rt->nb_invokes);
315 316
    ff_amf_write_object_start(&p);
    ff_amf_write_field_name(&p, "app");
317
    ff_amf_write_string(&p, rt->app);
318

319
    if (!rt->is_input) {
320 321 322
        ff_amf_write_field_name(&p, "type");
        ff_amf_write_string(&p, "nonprivate");
    }
323
    ff_amf_write_field_name(&p, "flashVer");
324
    ff_amf_write_string(&p, rt->flashver);
325 326 327 328 329 330

    if (rt->swfurl) {
        ff_amf_write_field_name(&p, "swfUrl");
        ff_amf_write_string(&p, rt->swfurl);
    }

331
    ff_amf_write_field_name(&p, "tcUrl");
332
    ff_amf_write_string(&p, rt->tcurl);
333
    if (rt->is_input) {
334 335 336 337
        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);
338 339 340 341

        /* 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. */
342
        ff_amf_write_field_name(&p, "audioCodecs");
343
        ff_amf_write_number(&p, 4071.0);
344 345 346 347
        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);
348 349 350 351 352

        if (rt->pageurl) {
            ff_amf_write_field_name(&p, "pageUrl");
            ff_amf_write_string(&p, rt->pageurl);
        }
353
    }
354 355
    ff_amf_write_object_end(&p);

356
    if (rt->conn) {
357
        char *param = rt->conn;
358 359 360

        // Write arbitrary AMF data to the Connect message.
        while (param != NULL) {
361 362 363 364 365 366 367
            char *sep;
            param += strspn(param, " ");
            if (!*param)
                break;
            sep = strchr(param, ' ');
            if (sep)
                *sep = '\0';
368 369 370 371 372 373
            if ((ret = rtmp_write_amf_data(s, param, &p)) < 0) {
                // Invalid AMF parameter.
                ff_rtmp_packet_destroy(&pkt);
                return ret;
            }

374 375 376 377
            if (sep)
                param = sep + 1;
            else
                break;
378 379 380
        }
    }

381 382
    pkt.data_size = p - pkt.data;

383
    return rtmp_send_packet(rt, &pkt, 1);
384 385
}

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
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;

    if ((ret = ff_rtmp_packet_read(rt->stream, &pkt, rt->in_chunk_size,
                                   rt->prev_pkt[1])) < 0)
        return ret;
    cp = pkt.data;
    bytestream2_init(&gbc, cp, pkt.data_size);
    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);

    // Send Window Acknowledgement Size (as defined in speficication)
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
                                     RTMP_PT_SERVER_BW, 0, 4)) < 0)
        return ret;
    p = pkt.data;
    bytestream_put_be32(&p, rt->server_bw);
    pkt.data_size = p - pkt.data;
    ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
                               rt->prev_pkt[1]);
    ff_rtmp_packet_destroy(&pkt);
    if (ret < 0)
        return ret;
    // Send Peer Bandwidth
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
                                     RTMP_PT_CLIENT_BW, 0, 5)) < 0)
        return ret;
    p = pkt.data;
    bytestream_put_be32(&p, rt->server_bw);
    bytestream_put_byte(&p, 2); // dynamic
    pkt.data_size = p - pkt.data;
    ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
                               rt->prev_pkt[1]);
    ff_rtmp_packet_destroy(&pkt);
    if (ret < 0)
        return ret;

    // Ping request
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
                                     RTMP_PT_PING, 0, 6)) < 0)
        return ret;

    p = pkt.data;
    bytestream_put_be16(&p, 0); // 0 -> Stream Begin
    bytestream_put_be32(&p, 0);
    ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
                               rt->prev_pkt[1]);
    ff_rtmp_packet_destroy(&pkt);
    if (ret < 0)
        return ret;

    // Chunk size
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL,
                                     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,
                               rt->prev_pkt[1]);
    ff_rtmp_packet_destroy(&pkt);
    if (ret < 0)
        return ret;

    // Send result_ NetConnection.Connect.Success to connect
    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);

    pkt.data_size = p - pkt.data;
    ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
                               rt->prev_pkt[1]);
    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);
    pkt.data_size = p - pkt.data;
    ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
                               rt->prev_pkt[1]);
    ff_rtmp_packet_destroy(&pkt);

    return ret;
}

531
/**
532
 * Generate 'releaseStream' call and send it to the server. It should make
533 534
 * the server release some channel for media streams.
 */
535
static int gen_release_stream(URLContext *s, RTMPContext *rt)
536 537 538
{
    RTMPPacket pkt;
    uint8_t *p;
539
    int ret;
540

541 542 543
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 29 + strlen(rt->playpath))) < 0)
        return ret;
544

545
    av_log(s, AV_LOG_DEBUG, "Releasing stream...\n");
546 547
    p = pkt.data;
    ff_amf_write_string(&p, "releaseStream");
548
    ff_amf_write_number(&p, ++rt->nb_invokes);
549 550 551
    ff_amf_write_null(&p);
    ff_amf_write_string(&p, rt->playpath);

552
    return rtmp_send_packet(rt, &pkt, 1);
553 554 555
}

/**
556
 * Generate 'FCPublish' call and send it to the server. It should make
557 558
 * the server preapare for receiving media streams.
 */
559
static int gen_fcpublish_stream(URLContext *s, RTMPContext *rt)
560 561 562
{
    RTMPPacket pkt;
    uint8_t *p;
563
    int ret;
564

565 566 567
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 25 + strlen(rt->playpath))) < 0)
        return ret;
568

569
    av_log(s, AV_LOG_DEBUG, "FCPublish stream...\n");
570 571
    p = pkt.data;
    ff_amf_write_string(&p, "FCPublish");
572
    ff_amf_write_number(&p, ++rt->nb_invokes);
573 574 575
    ff_amf_write_null(&p);
    ff_amf_write_string(&p, rt->playpath);

576
    return rtmp_send_packet(rt, &pkt, 1);
577 578 579
}

/**
580
 * Generate 'FCUnpublish' call and send it to the server. It should make
581 582
 * the server destroy stream.
 */
583
static int gen_fcunpublish_stream(URLContext *s, RTMPContext *rt)
584 585 586
{
    RTMPPacket pkt;
    uint8_t *p;
587
    int ret;
588

589 590 591
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 27 + strlen(rt->playpath))) < 0)
        return ret;
592

593
    av_log(s, AV_LOG_DEBUG, "UnPublishing stream...\n");
594 595
    p = pkt.data;
    ff_amf_write_string(&p, "FCUnpublish");
596
    ff_amf_write_number(&p, ++rt->nb_invokes);
597 598 599
    ff_amf_write_null(&p);
    ff_amf_write_string(&p, rt->playpath);

600
    return rtmp_send_packet(rt, &pkt, 0);
601 602
}

603
/**
604
 * Generate 'createStream' call and send it to the server. It should make
605 606
 * the server allocate some channel for media streams.
 */
607
static int gen_create_stream(URLContext *s, RTMPContext *rt)
608 609 610
{
    RTMPPacket pkt;
    uint8_t *p;
611
    int ret;
612

613
    av_log(s, AV_LOG_DEBUG, "Creating stream...\n");
614 615 616 617

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 25)) < 0)
        return ret;
618 619 620

    p = pkt.data;
    ff_amf_write_string(&p, "createStream");
621
    ff_amf_write_number(&p, ++rt->nb_invokes);
622 623
    ff_amf_write_null(&p);

624
    return rtmp_send_packet(rt, &pkt, 1);
625 626 627 628
}


/**
629
 * Generate 'deleteStream' call and send it to the server. It should make
630 631
 * the server remove some channel for media streams.
 */
632
static int gen_delete_stream(URLContext *s, RTMPContext *rt)
633 634 635
{
    RTMPPacket pkt;
    uint8_t *p;
636
    int ret;
637

638
    av_log(s, AV_LOG_DEBUG, "Deleting stream...\n");
639 640 641 642

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 34)) < 0)
        return ret;
643 644 645

    p = pkt.data;
    ff_amf_write_string(&p, "deleteStream");
646
    ff_amf_write_number(&p, ++rt->nb_invokes);
647
    ff_amf_write_null(&p);
648
    ff_amf_write_number(&p, rt->main_channel_id);
649

650
    return rtmp_send_packet(rt, &pkt, 0);
651 652
}

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
/**
 * 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;

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING,
                                     1, 10)) < 0)
        return ret;

    p = pkt.data;
    bytestream_put_be16(&p, 3);
    bytestream_put_be32(&p, rt->main_channel_id);
    bytestream_put_be32(&p, rt->client_buffer_time);

671
    return rtmp_send_packet(rt, &pkt, 0);
672 673
}

674
/**
675
 * Generate 'play' call and send it to the server, then ping the server
676 677
 * to start actual playing.
 */
678
static int gen_play(URLContext *s, RTMPContext *rt)
679 680 681
{
    RTMPPacket pkt;
    uint8_t *p;
682
    int ret;
683

684
    av_log(s, AV_LOG_DEBUG, "Sending play command for '%s'\n", rt->playpath);
685 686 687 688 689

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

690 691 692 693
    pkt.extra = rt->main_channel_id;

    p = pkt.data;
    ff_amf_write_string(&p, "play");
694
    ff_amf_write_number(&p, ++rt->nb_invokes);
695 696
    ff_amf_write_null(&p);
    ff_amf_write_string(&p, rt->playpath);
697
    ff_amf_write_number(&p, rt->live);
698

699
    return rtmp_send_packet(rt, &pkt, 1);
700 701
}

702
/**
703
 * Generate 'publish' call and send it to the server.
704
 */
705
static int gen_publish(URLContext *s, RTMPContext *rt)
706 707 708
{
    RTMPPacket pkt;
    uint8_t *p;
709
    int ret;
710

711
    av_log(s, AV_LOG_DEBUG, "Sending publish command for '%s'\n", rt->playpath);
712 713 714 715 716

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

717 718 719 720
    pkt.extra = rt->main_channel_id;

    p = pkt.data;
    ff_amf_write_string(&p, "publish");
721
    ff_amf_write_number(&p, ++rt->nb_invokes);
722 723 724 725
    ff_amf_write_null(&p);
    ff_amf_write_string(&p, rt->playpath);
    ff_amf_write_string(&p, "live");

726
    return rtmp_send_packet(rt, &pkt, 1);
727 728
}

729
/**
730
 * Generate ping reply and send it to the server.
731
 */
732
static int gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
733 734 735
{
    RTMPPacket pkt;
    uint8_t *p;
736 737
    int ret;

738 739 740 741 742 743
    if (ppkt->data_size < 6) {
        av_log(s, AV_LOG_ERROR, "Too short ping packet (%d)\n",
               ppkt->data_size);
        return AVERROR_INVALIDDATA;
    }

744 745 746
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING,
                                     ppkt->timestamp + 1, 6)) < 0)
        return ret;
747 748 749

    p = pkt.data;
    bytestream_put_be16(&p, 7);
750
    bytestream_put_be32(&p, AV_RB32(ppkt->data+2));
751

752
    return rtmp_send_packet(rt, &pkt, 0);
753 754
}

755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
/**
 * 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");
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING,
                                     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);
}

776 777 778
/**
 * Generate server bandwidth message and send it to the server.
 */
779
static int gen_server_bw(URLContext *s, RTMPContext *rt)
780 781 782
{
    RTMPPacket pkt;
    uint8_t *p;
783 784 785 786 787
    int ret;

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_SERVER_BW,
                                     0, 4)) < 0)
        return ret;
788 789

    p = pkt.data;
790
    bytestream_put_be32(&p, rt->server_bw);
791

792
    return rtmp_send_packet(rt, &pkt, 0);
793 794
}

795 796 797
/**
 * Generate check bandwidth message and send it to the server.
 */
798
static int gen_check_bw(URLContext *s, RTMPContext *rt)
799 800 801
{
    RTMPPacket pkt;
    uint8_t *p;
802
    int ret;
803

804 805 806
    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
                                     0, 21)) < 0)
        return ret;
807 808 809

    p = pkt.data;
    ff_amf_write_string(&p, "_checkbw");
810
    ff_amf_write_number(&p, ++rt->nb_invokes);
811 812
    ff_amf_write_null(&p);

813
    return rtmp_send_packet(rt, &pkt, 1);
814 815
}

816
/**
817
 * Generate report on bytes read so far and send it to the server.
818
 */
819
static int gen_bytes_read(URLContext *s, RTMPContext *rt, uint32_t ts)
820 821 822
{
    RTMPPacket pkt;
    uint8_t *p;
823 824 825 826 827
    int ret;

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_BYTES_READ,
                                     ts, 4)) < 0)
        return ret;
828 829 830

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

832
    return rtmp_send_packet(rt, &pkt, 0);
833 834
}

835 836
static int gen_fcsubscribe_stream(URLContext *s, RTMPContext *rt,
                                  const char *subscribe)
837 838 839 840 841 842
{
    RTMPPacket pkt;
    uint8_t *p;
    int ret;

    if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
843
                                     0, 27 + strlen(subscribe))) < 0)
844 845 846 847 848 849
        return ret;

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

852
    return rtmp_send_packet(rt, &pkt, 1);
853 854
}

855 856
int ff_rtmp_calc_digest(const uint8_t *src, int len, int gap,
                        const uint8_t *key, int keylen, uint8_t *dst)
857 858 859 860 861 862
{
    struct AVSHA *sha;
    uint8_t hmac_buf[64+32] = {0};
    int i;

    sha = av_mallocz(av_sha_size);
863 864
    if (!sha)
        return AVERROR(ENOMEM);
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892

    if (keylen < 64) {
        memcpy(hmac_buf, key, keylen);
    } else {
        av_sha_init(sha, 256);
        av_sha_update(sha,key, keylen);
        av_sha_final(sha, hmac_buf);
    }
    for (i = 0; i < 64; i++)
        hmac_buf[i] ^= HMAC_IPAD_VAL;

    av_sha_init(sha, 256);
    av_sha_update(sha, hmac_buf, 64);
    if (gap <= 0) {
        av_sha_update(sha, src, len);
    } else { //skip 32 bytes used for storing digest
        av_sha_update(sha, src, gap);
        av_sha_update(sha, src + gap + 32, len - gap - 32);
    }
    av_sha_final(sha, hmac_buf + 64);

    for (i = 0; i < 64; i++)
        hmac_buf[i] ^= HMAC_IPAD_VAL ^ HMAC_OPAD_VAL; //reuse XORed key for opad
    av_sha_init(sha, 256);
    av_sha_update(sha, hmac_buf, 64+32);
    av_sha_final(sha, dst);

    av_free(sha);
893 894

    return 0;
895 896
}

897 898 899 900 901 902 903 904 905 906 907 908
int ff_rtmp_calc_digest_pos(const uint8_t *buf, int off, int mod_val,
                            int add_val)
{
    int i, digest_pos = 0;

    for (i = 0; i < 4; i++)
        digest_pos += buf[i + off];
    digest_pos = digest_pos % mod_val + add_val;

    return digest_pos;
}

909
/**
910
 * Put HMAC-SHA2 digest of packet data (except for the bytes where this digest
911 912 913
 * will be stored) into that packet.
 *
 * @param buf handshake data (1536 bytes)
Samuel Pitoiset's avatar
Samuel Pitoiset committed
914
 * @param encrypted use an encrypted connection (RTMPE)
915 916
 * @return offset to the digest inside input data
 */
Samuel Pitoiset's avatar
Samuel Pitoiset committed
917
static int rtmp_handshake_imprint_with_digest(uint8_t *buf, int encrypted)
918
{
919
    int ret, digest_pos;
920

Samuel Pitoiset's avatar
Samuel Pitoiset committed
921 922 923 924
    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);
925

926 927 928
    ret = ff_rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
                              rtmp_player_key, PLAYER_KEY_OPEN_PART_LEN,
                              buf + digest_pos);
929 930 931
    if (ret < 0)
        return ret;

932 933 934 935
    return digest_pos;
}

/**
936
 * Verify that the received server response has the expected digest value.
937 938 939 940 941 942 943 944
 *
 * @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];
945
    int ret, digest_pos;
946

947
    digest_pos = ff_rtmp_calc_digest_pos(buf, off, 728, off + 4);
948

949 950 951
    ret = ff_rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
                              rtmp_server_key, SERVER_KEY_OPEN_PART_LEN,
                              digest);
952 953 954
    if (ret < 0)
        return ret;

955 956 957 958 959
    if (!memcmp(digest, buf + digest_pos, 32))
        return digest_pos;
    return 0;
}

960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
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;
}

984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 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
#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;
    int64_t in_size, out_size;
    URLContext *stream;
    char swfhash[32];
    int swfsize;
    int ret = 0;

    /* Get the SWF player file. */
    if ((ret = ffurl_open(&stream, rt->swfverify, AVIO_FLAG_READ,
                          &s->interrupt_callback, NULL)) < 0) {
        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)) {
        /* 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 CONFIG_ZLIB
        if ((ret = rtmp_uncompress_swfplayer(in_data + 8, in_size - 8,
                                             &out_data, &out_size)) < 0)
            goto fail;
#else
        av_log(s, AV_LOG_ERROR,
               "Zlib is required for decompressing the SWF player file.\n");
        ret = AVERROR(EINVAL);
        goto fail;
#endif
        swfsize = out_size;
        swfdata = out_data;
    } 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;
}

1107
/**
1108
 * Perform handshake with the server by means of exchanging pseudorandom data
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
 * 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
        RTMP_CLIENT_VER1,
        RTMP_CLIENT_VER2,
        RTMP_CLIENT_VER3,
        RTMP_CLIENT_VER4,
    };
    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
1128 1129
    uint8_t digest[32], signature[32];
    int ret, type = 0;
1130

1131
    av_log(s, AV_LOG_DEBUG, "Handshaking...\n");
1132 1133 1134 1135 1136

    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
1137

1138
    if (rt->encrypted && CONFIG_FFRTMPCRYPT_PROTOCOL) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
        /* 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;
    }

1154
    client_pos = rtmp_handshake_imprint_with_digest(tosend + 1, rt->encrypted);
1155 1156
    if (client_pos < 0)
        return client_pos;
1157

1158 1159 1160 1161 1162 1163
    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;
    }

1164 1165
    if ((ret = ffurl_read_complete(rt->stream, serverdata,
                                   RTMP_HANDSHAKE_PACKET_SIZE + 1)) < 0) {
1166
        av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
1167
        return ret;
1168
    }
1169 1170 1171

    if ((ret = ffurl_read_complete(rt->stream, clientdata,
                                   RTMP_HANDSHAKE_PACKET_SIZE)) < 0) {
1172
        av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
1173
        return ret;
1174 1175
    }

Samuel Pitoiset's avatar
Samuel Pitoiset committed
1176
    av_log(s, AV_LOG_DEBUG, "Type answer %d\n", serverdata[0]);
1177
    av_log(s, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n",
1178 1179
           serverdata[5], serverdata[6], serverdata[7], serverdata[8]);

1180
    if (rt->is_input && serverdata[5] >= 3) {
1181
        server_pos = rtmp_validate_digest(serverdata + 1, 772);
1182 1183 1184
        if (server_pos < 0)
            return server_pos;

1185
        if (!server_pos) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1186
            type = 1;
1187
            server_pos = rtmp_validate_digest(serverdata + 1, 8);
1188 1189 1190
            if (server_pos < 0)
                return server_pos;

1191
            if (!server_pos) {
1192
                av_log(s, AV_LOG_ERROR, "Server response validating failed\n");
1193
                return AVERROR(EIO);
1194
            }
1195 1196
        }

1197 1198 1199 1200 1201 1202 1203 1204
        /* 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;
        }

1205 1206 1207
        ret = ff_rtmp_calc_digest(tosend + 1 + client_pos, 32, 0,
                                  rtmp_server_key, sizeof(rtmp_server_key),
                                  digest);
1208 1209 1210
        if (ret < 0)
            return ret;

1211
        ret = ff_rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE - 32,
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1212
                                  0, digest, 32, signature);
1213 1214 1215
        if (ret < 0)
            return ret;

1216
        if (rt->encrypted && CONFIG_FFRTMPCRYPT_PROTOCOL) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
            /* 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)) {
1228
            av_log(s, AV_LOG_ERROR, "Signature mismatch\n");
1229
            return AVERROR(EIO);
1230
        }
1231

1232 1233
        for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++)
            tosend[i] = av_lfg_get(&rnd) >> 24;
1234 1235 1236
        ret = ff_rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0,
                                  rtmp_player_key, sizeof(rtmp_player_key),
                                  digest);
1237 1238 1239
        if (ret < 0)
            return ret;

1240 1241 1242
        ret = ff_rtmp_calc_digest(tosend, RTMP_HANDSHAKE_PACKET_SIZE - 32, 0,
                                  digest, 32,
                                  tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
1243 1244
        if (ret < 0)
            return ret;
1245

1246
        if (rt->encrypted && CONFIG_FFRTMPCRYPT_PROTOCOL) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1247 1248 1249 1250 1251 1252
            /* Encrypt the signature to be send to the server. */
            ff_rtmpe_encrypt_sig(rt->stream, tosend +
                                 RTMP_HANDSHAKE_PACKET_SIZE - 32, digest,
                                 serverdata[0]);
        }

1253
        // write reply back to the server
1254 1255 1256
        if ((ret = ffurl_write(rt->stream, tosend,
                               RTMP_HANDSHAKE_PACKET_SIZE)) < 0)
            return ret;
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1257

1258
        if (rt->encrypted && CONFIG_FFRTMPCRYPT_PROTOCOL) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1259 1260 1261 1262
            /* Set RC4 keys for encryption and update the keystreams. */
            if ((ret = ff_rtmpe_update_keystream(rt->stream)) < 0)
                return ret;
        }
1263
    } else {
1264
        if (rt->encrypted && CONFIG_FFRTMPCRYPT_PROTOCOL) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
            /* 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]);
            }
        }

1278 1279 1280
        if ((ret = ffurl_write(rt->stream, serverdata + 1,
                               RTMP_HANDSHAKE_PACKET_SIZE)) < 0)
            return ret;
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1281

1282
        if (rt->encrypted && CONFIG_FFRTMPCRYPT_PROTOCOL) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1283 1284 1285 1286
            /* Set RC4 keys for encryption and update the keystreams. */
            if ((ret = ff_rtmpe_update_keystream(rt->stream)) < 0)
                return ret;
        }
1287 1288
    }

1289 1290 1291
    return 0;
}

1292 1293 1294 1295
static int rtmp_receive_hs_packet(RTMPContext* rt, uint32_t *first_int,
                                  uint32_t *second_int, char *arraydata,
                                  int size)
{
1296
    int inoutsize;
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315

    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)
{
1316
    int inoutsize;
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342

    AV_WB32(arraydata, first_int);
    AV_WB32(arraydata + 4, first_int);
    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;
1343
    int inoutsize       = 0;
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
    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;
    }
    if (zeroes)
        av_log(s, AV_LOG_WARNING, "Erroneous C1 Message zero != 0\n");
    /* Send S1 */
    /* By now same epoch will be sent */
    hs_my_epoch = hs_epoch;
    /* Generate random */
    for (randomidx = 0; randomidx < (RTMP_HANDSHAKE_PACKET_SIZE);
         randomidx += 4)
        AV_WB32(hs_s1 + 8 + randomidx, av_get_random_seed());

    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;
}

1409 1410 1411 1412 1413
static int handle_chunk_size(URLContext *s, RTMPPacket *pkt)
{
    RTMPContext *rt = s->priv_data;
    int ret;

1414
    if (pkt->data_size < 4) {
1415
        av_log(s, AV_LOG_ERROR,
1416
               "Too short chunk size change packet (%d)\n",
1417
               pkt->data_size);
1418
        return AVERROR_INVALIDDATA;
1419 1420 1421
    }

    if (!rt->is_input) {
1422 1423 1424
        /* 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,
1425 1426
                                        rt->prev_pkt[1])) < 0)
            return ret;
1427
        rt->out_chunk_size = AV_RB32(pkt->data);
1428 1429
    }

1430 1431 1432 1433
    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);
1434
        return AVERROR_INVALIDDATA;
1435
    }
1436 1437
    av_log(s, AV_LOG_DEBUG, "New incoming chunk size = %d\n",
           rt->in_chunk_size);
1438 1439 1440 1441

    return 0;
}

1442 1443 1444 1445 1446
static int handle_ping(URLContext *s, RTMPPacket *pkt)
{
    RTMPContext *rt = s->priv_data;
    int t, ret;

1447 1448 1449 1450 1451 1452
    if (pkt->data_size < 2) {
        av_log(s, AV_LOG_ERROR, "Too short ping packet (%d)\n",
               pkt->data_size);
        return AVERROR_INVALIDDATA;
    }

1453 1454 1455 1456
    t = AV_RB16(pkt->data);
    if (t == 6) {
        if ((ret = gen_pong(s, rt, pkt)) < 0)
            return ret;
1457 1458 1459 1460 1461 1462 1463
    } 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");
        }
1464 1465 1466 1467 1468
    }

    return 0;
}

1469 1470 1471 1472 1473 1474 1475 1476
static int handle_client_bw(URLContext *s, RTMPPacket *pkt)
{
    RTMPContext *rt = s->priv_data;

    if (pkt->data_size < 4) {
        av_log(s, AV_LOG_ERROR,
               "Client bandwidth report packet is less than 4 bytes long (%d)\n",
               pkt->data_size);
1477
        return AVERROR_INVALIDDATA;
1478
    }
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488

    rt->client_report_size = AV_RB32(pkt->data);
    if (rt->client_report_size <= 0) {
        av_log(s, AV_LOG_ERROR, "Incorrect client bandwidth %d\n",
                rt->client_report_size);
        return AVERROR_INVALIDDATA;

    }
    av_log(s, AV_LOG_DEBUG, "Client bandwidth = %d\n", rt->client_report_size);
    rt->client_report_size >>= 1;
1489 1490 1491 1492

    return 0;
}

1493 1494 1495 1496
static int handle_server_bw(URLContext *s, RTMPPacket *pkt)
{
    RTMPContext *rt = s->priv_data;

1497 1498 1499 1500 1501 1502 1503
    if (pkt->data_size < 4) {
        av_log(s, AV_LOG_ERROR,
               "Too short server bandwidth report packet (%d)\n",
               pkt->data_size);
        return AVERROR_INVALIDDATA;
    }

1504 1505 1506 1507
    rt->server_bw = AV_RB32(pkt->data);
    if (rt->server_bw <= 0) {
        av_log(s, AV_LOG_ERROR, "Incorrect server bandwidth %d\n",
               rt->server_bw);
1508
        return AVERROR_INVALIDDATA;
1509 1510 1511 1512 1513 1514
    }
    av_log(s, AV_LOG_DEBUG, "Server bandwidth = %d\n", rt->server_bw);

    return 0;
}

1515 1516 1517
static int handle_invoke_error(URLContext *s, RTMPPacket *pkt)
{
    const uint8_t *data_end = pkt->data + pkt->data_size;
1518 1519
    char *tracked_method = NULL;
    int level = AV_LOG_ERROR;
1520
    uint8_t tmpstr[256];
1521 1522 1523 1524
    int ret;

    if ((ret = find_tracked_method(s, pkt, 9, &tracked_method)) < 0)
        return ret;
1525 1526 1527

    if (!ff_amf_get_field_value(pkt->data + 9, data_end,
                                "description", tmpstr, sizeof(tmpstr))) {
1528 1529 1530 1531 1532
        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. */
1533 1534 1535 1536 1537
            level = AV_LOG_WARNING;