diff -Nur xbmc-trunk-28276-orig/xbmc/cores/dvdplayer/DVDDemuxers/DVDDemuxFFmpeg.cpp xbmc-trunk-28276/xbmc/cores/dvdplayer/DVDDemuxers/DVDDemuxFFmpeg.cpp --- xbmc-trunk-28276-orig/xbmc/cores/dvdplayer/DVDDemuxers/DVDDemuxFFmpeg.cpp 2010-04-04 11:42:49.000000000 +0100 +++ xbmc-trunk-28276/xbmc/cores/dvdplayer/DVDDemuxers/DVDDemuxFFmpeg.cpp 2010-04-04 22:57:37.512130259 +0100 @@ -556,6 +556,9 @@ if (m_pFormatContext) m_dllAvFormat.av_read_frame_flush(m_pFormatContext); + if (m_ioContext) + m_ioContext->buf_ptr = m_ioContext->buf_end; + m_iCurrentPts = DVD_NOPTS_VALUE; } diff -Nur xbmc-trunk-28276-orig/xbmc/cores/dvdplayer/DVDInputStreams/DllDvdNav.h xbmc-trunk-28276/xbmc/cores/dvdplayer/DVDInputStreams/DllDvdNav.h --- xbmc-trunk-28276-orig/xbmc/cores/dvdplayer/DVDInputStreams/DllDvdNav.h 2010-04-04 11:43:45.000000000 +0100 +++ xbmc-trunk-28276/xbmc/cores/dvdplayer/DVDInputStreams/DllDvdNav.h 2010-04-04 22:57:29.922119172 +0100 @@ -27,9 +27,11 @@ #include "dvdnav/dvdnav.h" +#if 0 #ifndef WIN32 #define WIN32 #endif // WIN32 +#endif #ifndef HAVE_CONFIG_H #define HAVE_CONFIG_H diff -Nur xbmc-trunk-28276-orig/xbmc/cores/dvdplayer/DVDInputStreams/DVDFactoryInputStream.cpp xbmc-trunk-28276/xbmc/cores/dvdplayer/DVDInputStreams/DVDFactoryInputStream.cpp --- xbmc-trunk-28276-orig/xbmc/cores/dvdplayer/DVDInputStreams/DVDFactoryInputStream.cpp 2010-04-04 11:43:45.000000000 +0100 +++ xbmc-trunk-28276/xbmc/cores/dvdplayer/DVDInputStreams/DVDFactoryInputStream.cpp 2010-04-04 22:57:31.142119822 +0100 @@ -72,7 +72,11 @@ else if(file.substr(0, 8) == "stack://") return new CDVDInputStreamStack(); #endif - else if(file.substr(0, 7) == "rtmp://") + else if(file.substr(0, 7) == "rtmp://" + || file.substr(0, 8) == "rtmpt://" + || file.substr(0, 8) == "rtmpe://" + || file.substr(0, 9) == "rtmpte://" + || file.substr(0, 8) == "rtmps://") return new CDVDInputStreamRTMP(); #ifdef HAS_FILESYSTEM_HTSP else if(file.substr(0, 7) == "htsp://") diff -Nur xbmc-trunk-28276-orig/xbmc/cores/dvdplayer/DVDInputStreams/DVDInputStreamRTMP.cpp xbmc-trunk-28276/xbmc/cores/dvdplayer/DVDInputStreams/DVDInputStreamRTMP.cpp --- xbmc-trunk-28276-orig/xbmc/cores/dvdplayer/DVDInputStreams/DVDInputStreamRTMP.cpp 2010-04-04 11:43:45.000000000 +0100 +++ xbmc-trunk-28276/xbmc/cores/dvdplayer/DVDInputStreams/DVDInputStreamRTMP.cpp 2010-04-04 22:57:26.414670250 +0100 @@ -41,15 +41,9 @@ CDVDInputStreamRTMP::CDVDInputStreamRTMP() : CDVDInputStream(DVDSTREAM_TYPE_RTMP) { - m_rtmp = NULL; - m_rtmp = new RTMP_LIB::CRTMP; + RTMP_Init(&m_rtmp); m_eof = true; m_bPaused = false; - m_prevTagSize = 0; - m_bSentHeader = false; - m_leftOver = NULL; - m_leftOverSize = 0; - m_leftOverConsumed = 0; m_sStreamPlaying = NULL; } @@ -62,16 +56,6 @@ } Close(); - - CSingleLock lock(m_RTMPSection); - if (m_rtmp) - { - CLog::Log(LOGNOTICE,"Deleted CRTMP"); - delete m_rtmp; - m_rtmp = NULL; - } - - m_bPaused = false; } bool CDVDInputStreamRTMP::IsEOF() @@ -79,8 +63,26 @@ return m_eof; } +#define SetAVal(av, cstr) av.av_val = (char *)cstr.c_str(); av.av_len = cstr.length() +#undef AVC +#define AVC(str) {(char *)str,sizeof(str)-1} + +/* librtmp option names are slightly different */ +static const struct { + const char *name; + AVal key; +} options[] = { + { "SWFPlayer", AVC("swfUrl") }, + { "PageURL", AVC("pageUrl") }, + { "PlayPath", AVC("playpath") }, + { "TcUrl", AVC("tcUrl") }, + { "IsLive", AVC("live") }, + { NULL } +}; + bool CDVDInputStreamRTMP::Open(const char* strFile, const std::string& content) { + int i; if (m_sStreamPlaying) { free(m_sStreamPlaying); @@ -89,22 +91,28 @@ if (!CDVDInputStream::Open(strFile, "video/x-flv")) return false; - CSingleLock lock(m_RTMPSection); - if (!m_rtmp) return false; + i = strlen(strFile); + m_sStreamPlaying = (char*)malloc(i+1); + memcpy(m_sStreamPlaying,strFile,i); + m_sStreamPlaying[i] = '\0'; + if (!RTMP_SetupURL(&m_rtmp, m_sStreamPlaying)) return false; + + for (i=0; options[i].name; i++) + { + std::string tmp = m_item.GetProperty(options[i].name); + if (tmp.length()) + { + AVal av_tmp; + SetAVal(av_tmp, tmp); + RTMP_SetOpt(&m_rtmp, &options[i].key, &av_tmp); + } + } - m_rtmp->SetPlayer(m_item.GetProperty("SWFPlayer")); - m_rtmp->SetPageUrl(m_item.GetProperty("PageURL")); - m_rtmp->SetPlayPath(m_item.GetProperty("PlayPath")); - m_rtmp->SetTcUrl(m_item.GetProperty("TcUrl")); - if (!m_item.GetProperty("IsLive").compare("true")) - m_rtmp->SetLive(); - m_rtmp->SetBufferMS(20000); + CSingleLock lock(m_RTMPSection); - if (!m_rtmp->Connect(strFile)) + if (!RTMP_Connect(&m_rtmp, NULL) || !RTMP_ConnectStream(&m_rtmp, 0)) return false; - m_sStreamPlaying = (char*)calloc(strlen(strFile)+1,sizeof(char)); - strncpy(m_sStreamPlaying,strFile,strlen(strFile)); m_eof = false; return true; } @@ -114,136 +122,20 @@ { CSingleLock lock(m_RTMPSection); CDVDInputStream::Close(); - if (m_rtmp) m_rtmp->Close(); + RTMP_Close(&m_rtmp); m_eof = true; + m_bPaused = false; } int CDVDInputStreamRTMP::Read(BYTE* buf, int buf_size) { - int nRead = 0; - if (m_leftOver) - { - int nToConsume = m_leftOverSize - m_leftOverConsumed; - if (nToConsume > buf_size) - nToConsume = buf_size; - - memcpy(buf, m_leftOver + m_leftOverConsumed, nToConsume); - buf_size -= nToConsume; - m_leftOverConsumed += nToConsume; - nRead += nToConsume; - - if (m_leftOverConsumed == m_leftOverSize) - { - m_leftOverConsumed = m_leftOverSize = 0; - delete [] m_leftOver; - m_leftOver = NULL; - } - - if (buf_size == 0) - return nRead; - } - - RTMP_LIB::RTMPPacket packet; + int i; CSingleLock lock(m_RTMPSection); - while (buf_size > nRead && m_rtmp && m_rtmp->GetNextMediaPacket(packet)) - { - - if (!m_bSentHeader) - { - if (buf_size < 9) - return -1; - - char header[] = { 'F', 'L', 'V', 0x01, - 0x05, // video + audio - 0x00, 0x00, 0x00, 0x09}; - memcpy(buf, header, 9); - buf_size -= 9; - nRead += 9; - m_bSentHeader = true; - } - - if (buf_size < 4) - return nRead; - - // skip video info/command packets - // if we keep these it chokes the dvdplayer - if ( packet.m_packetType == 0x09 && - packet.m_nBodySize == 2 && - ( (*packet.m_body & 0xf0) == 0x50) ) - { - continue; - } - - // write footer of previous FLV tag - if ( m_prevTagSize != -1 ) - { - RTMP_LIB::CRTMP::EncodeInt32((char*)buf + nRead, m_prevTagSize); - nRead += 4; - buf_size -= 4; - } - - char *ptr = (char*)buf + nRead; - - // audio (0x08), video (0x09) or metadata (0x12) packets : - // construct 11 byte header then add rtmp packet's data - if ( packet.m_packetType == 0x08 || packet.m_packetType == 0x09 || packet.m_packetType == 0x12 ) - { - m_prevTagSize = 11 + packet.m_nBodySize; - - if (buf_size < 11) - return nRead; - - *ptr = packet.m_packetType; - ptr++; - ptr += RTMP_LIB::CRTMP::EncodeInt24(ptr, packet.m_nBodySize); - - ptr += RTMP_LIB::CRTMP::EncodeInt24(ptr, packet.m_nInfoField1); - *ptr = (char)((packet.m_nInfoField1 & 0xFF000000) >> 24); - ptr++; - - ptr += RTMP_LIB::CRTMP::EncodeInt24(ptr, 0); - - nRead += 11; - buf_size -= 11; - - if (buf_size == 0) - return nRead; - - } - else if (packet.m_packetType == 0x16) - { - // FLV tag(s) packet - // contains it's own tagsize footer, don't write another - m_prevTagSize = -1; - } - - int nBodyLen = packet.m_nBodySize; - if (nBodyLen > buf_size) - { - memcpy(ptr, packet.m_body, buf_size); - nRead += buf_size; - - m_leftOver = new char[packet.m_nBodySize - buf_size]; - memcpy(m_leftOver, packet.m_body + buf_size, packet.m_nBodySize - buf_size); - m_leftOverSize = packet.m_nBodySize - buf_size; - m_leftOverConsumed = 0; - break; - } - else - { - memcpy(ptr, packet.m_body, nBodyLen); - nRead += nBodyLen; - buf_size -= nBodyLen; - } - - } - - - if (m_rtmp && m_rtmp->IsConnected()) - return nRead; - - return -1; + i = RTMP_Read(&m_rtmp, (char *)buf, buf_size); + if (i < 0) + m_eof = true; + return i; } __int64 CDVDInputStreamRTMP::Seek(__int64 offset, int whence) @@ -257,7 +149,7 @@ bool CDVDInputStreamRTMP::SeekTime(int iTimeInMsec) { CLog::Log(LOGNOTICE, "RTMP Seek to %i requested", iTimeInMsec); - if (m_rtmp->Seek((double)iTimeInMsec)) + if (RTMP_SendSeek(&m_rtmp, (double)iTimeInMsec)) { return true; } @@ -277,27 +169,9 @@ bool CDVDInputStreamRTMP::Pause(double dTime) { - if (m_bPaused) - { - CSingleLock lock(m_RTMPSection); - /*m_rtmp = new RTMP_LIB::CRTMP; - m_rtmp->Connect(m_sStreamPlaying, dTime); - m_bPaused = false; - CLog::Log(LOGNOTICE,"Created new CRTMP - %s : %f ms", m_sStreamPlaying, dTime);*/ - m_bPaused = false; - m_rtmp->SendPause(m_bPaused, dTime); - } - else - { - CSingleLock lock(m_RTMPSection); - /*Close(); - delete m_rtmp; - m_bPaused = true; - CLog::Log(LOGNOTICE,"Deleted CRTMP");*/ - m_bPaused = true; - m_rtmp->SendPause(m_bPaused, dTime); - } - + m_bPaused = !m_bPaused; + CSingleLock lock(m_RTMPSection); + RTMP_SendPause(&m_rtmp, m_bPaused, dTime); return true; } diff -Nur xbmc-trunk-28276-orig/xbmc/cores/dvdplayer/DVDInputStreams/DVDInputStreamRTMP.h xbmc-trunk-28276/xbmc/cores/dvdplayer/DVDInputStreams/DVDInputStreamRTMP.h --- xbmc-trunk-28276-orig/xbmc/cores/dvdplayer/DVDInputStreams/DVDInputStreamRTMP.h 2010-04-04 11:43:45.000000000 +0100 +++ xbmc-trunk-28276/xbmc/cores/dvdplayer/DVDInputStreams/DVDInputStreamRTMP.h 2010-04-04 22:57:31.182128748 +0100 @@ -44,12 +44,7 @@ protected: bool m_eof; bool m_bPaused; - RTMP_LIB::CRTMP *m_rtmp; - int m_prevTagSize; - bool m_bSentHeader; - char *m_leftOver; + RTMP m_rtmp; char* m_sStreamPlaying; - unsigned int m_leftOverSize; - unsigned int m_leftOverConsumed; }; diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/amf.c xbmc-trunk-28276/xbmc/lib/libRTMP/amf.c --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/amf.c 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/amf.c 2010-04-04 22:58:14.512144576 +0100 @@ -0,0 +1,1181 @@ +/* + * Copyright (C) 2005-2008 Team XBMC + * http://www.xbmc.org + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#include +#include + +#include "amf.h" +#include "log.h" +#include "bytes.h" + +static const AMFObjectProperty AMFProp_Invalid = { {0, 0}, AMF_INVALID }; +static const AVal AV_empty = { 0, 0 }; + +/* Data is Big-Endian */ +unsigned short +AMF_DecodeInt16(const char *data) +{ + unsigned char *c = (unsigned char *) data; + unsigned short val; + val = (c[0] << 8) | c[1]; + return val; +} + +unsigned int +AMF_DecodeInt24(const char *data) +{ + unsigned char *c = (unsigned char *) data; + unsigned int val; + val = (c[0] << 16) | (c[1] << 8) | c[2]; + return val; +} + +unsigned int +AMF_DecodeInt32(const char *data) +{ + unsigned char *c = (unsigned char *)data; + unsigned int val; + val = (c[0] << 24) | (c[1] << 16) | (c[2] << 8) | c[3]; + return val; +} + +void +AMF_DecodeString(const char *data, AVal *bv) +{ + bv->av_len = AMF_DecodeInt16(data); + bv->av_val = (bv->av_len > 0) ? (char *)data + 2 : NULL; +} + +void +AMF_DecodeLongString(const char *data, AVal *bv) +{ + bv->av_len = AMF_DecodeInt32(data); + bv->av_val = (bv->av_len > 0) ? (char *)data + 4 : NULL; +} + +double +AMF_DecodeNumber(const char *data) +{ + double dVal; +#if __FLOAT_WORD_ORDER == __BYTE_ORDER +#if __BYTE_ORDER == __BIG_ENDIAN + memcpy(&dVal, data, 8); +#elif __BYTE_ORDER == __LITTLE_ENDIAN + unsigned char *ci, *co; + ci = (unsigned char *)data; + co = (unsigned char *)&dVal; + co[0] = ci[7]; + co[1] = ci[6]; + co[2] = ci[5]; + co[3] = ci[4]; + co[4] = ci[3]; + co[5] = ci[2]; + co[6] = ci[1]; + co[7] = ci[0]; +#endif +#else +#if __BYTE_ORDER == __LITTLE_ENDIAN // __FLOAT_WORD_ORER == __BIG_ENDIAN + unsigned char *ci, *co; + ci = (unsigned char *)data; + co = (unsigned char *)&dVal; + co[0] = ci[3]; + co[1] = ci[2]; + co[2] = ci[1]; + co[3] = ci[0]; + co[4] = ci[7]; + co[5] = ci[6]; + co[6] = ci[5]; + co[7] = ci[4]; +#else // __BYTE_ORDER == __BIG_ENDIAN && __FLOAT_WORD_ORER == __LITTLE_ENDIAN + unsigned char *ci, *co; + ci = (unsigned char *)data; + co = (unsigned char *)&dVal; + co[0] = ci[4]; + co[1] = ci[5]; + co[2] = ci[6]; + co[3] = ci[7]; + co[4] = ci[0]; + co[5] = ci[1]; + co[6] = ci[2]; + co[7] = ci[3]; +#endif +#endif + return dVal; +} + +bool +AMF_DecodeBoolean(const char *data) +{ + return *data != 0; +} + +char * +AMF_EncodeInt16(char *output, char *outend, short nVal) +{ + if (output+2 > outend) + return NULL; + + output[1] = nVal & 0xff; + output[0] = nVal >> 8; + return output+2; +} + +char * +AMF_EncodeInt24(char *output, char *outend, int nVal) +{ + if (output+3 > outend) + return NULL; + + output[2] = nVal & 0xff; + output[1] = nVal >> 8; + output[0] = nVal >> 16; + return output+3; +} + +char * +AMF_EncodeInt32(char *output, char *outend, int nVal) +{ + if (output+4 > outend) + return NULL; + + output[3] = nVal & 0xff; + output[2] = nVal >> 8; + output[1] = nVal >> 16; + output[0] = nVal >> 24; + return output+4; +} + +char * +AMF_EncodeString(char *output, char *outend, const AVal *bv) +{ + if ((bv->av_len < 65536 && output + 1 + 2 + bv->av_len > outend) || + output + 1 + 4 + bv->av_len > outend) + return NULL; + + if (bv->av_len < 65536) + { + *output++ = AMF_STRING; + + output = AMF_EncodeInt16(output, outend, bv->av_len); + } + else + { + *output++ = AMF_LONG_STRING; + + output = AMF_EncodeInt32(output, outend, bv->av_len); + } + memcpy(output, bv->av_val, bv->av_len); + output += bv->av_len; + + return output; +} + +char * +AMF_EncodeNumber(char *output, char *outend, double dVal) +{ + if (output+1+8 > outend) + return NULL; + + *output++ = AMF_NUMBER; // type: Number + +#if __FLOAT_WORD_ORDER == __BYTE_ORDER +#if __BYTE_ORDER == __BIG_ENDIAN + memcpy(output, &dVal, 8); +#elif __BYTE_ORDER == __LITTLE_ENDIAN + { + unsigned char *ci, *co; + ci = (unsigned char *)&dVal; + co = (unsigned char *)output; + co[0] = ci[7]; + co[1] = ci[6]; + co[2] = ci[5]; + co[3] = ci[4]; + co[4] = ci[3]; + co[5] = ci[2]; + co[6] = ci[1]; + co[7] = ci[0]; + } +#endif +#else +#if __BYTE_ORDER == __LITTLE_ENDIAN /* __FLOAT_WORD_ORER == __BIG_ENDIAN */ + { + unsigned char *ci, *co; + ci = (unsigned char *)&dVal; + co = (unsigned char *)output; + co[0] = ci[3]; + co[1] = ci[2]; + co[2] = ci[1]; + co[3] = ci[0]; + co[4] = ci[7]; + co[5] = ci[6]; + co[6] = ci[5]; + co[7] = ci[4]; + } +#else /* __BYTE_ORDER == __BIG_ENDIAN && __FLOAT_WORD_ORER == __LITTLE_ENDIAN */ + { + unsigned char *ci, *co; + ci = (unsigned char *)&dVal; + co = (unsigned char *)output; + co[0] = ci[4]; + co[1] = ci[5]; + co[2] = ci[6]; + co[3] = ci[7]; + co[4] = ci[0]; + co[5] = ci[1]; + co[6] = ci[2]; + co[7] = ci[3]; + } +#endif +#endif + + return output+8; +} + +char * +AMF_EncodeBoolean(char *output, char *outend, bool bVal) +{ + if (output+2 > outend) + return NULL; + + *output++ = AMF_BOOLEAN; + + *output++ = bVal ? 0x01 : 0x00; + + return output; +} + +char * +AMF_EncodeNamedString(char *output, char *outend, const AVal *strName, const AVal *strValue) +{ + if (output+2+strName->av_len > outend) + return NULL; + output = AMF_EncodeInt16(output, outend, strName->av_len); + + memcpy(output, strName->av_val, strName->av_len); + output += strName->av_len; + + return AMF_EncodeString(output, outend, strValue); +} + +char * +AMF_EncodeNamedNumber(char *output, char *outend, const AVal *strName, double dVal) +{ + if (output+2+strName->av_len > outend) + return NULL; + output = AMF_EncodeInt16(output, outend, strName->av_len); + + memcpy(output, strName->av_val, strName->av_len); + output += strName->av_len; + + return AMF_EncodeNumber(output, outend, dVal); +} + +char * +AMF_EncodeNamedBoolean(char *output, char *outend, const AVal *strName, bool bVal) +{ + if (output+2+strName->av_len > outend) + return NULL; + output = AMF_EncodeInt16(output, outend, strName->av_len); + + memcpy(output, strName->av_val, strName->av_len); + output += strName->av_len; + + return AMF_EncodeBoolean(output, outend, bVal); +} + +void +AMFProp_GetName(AMFObjectProperty *prop, AVal *name) +{ + *name = prop->p_name; +} + +void +AMFProp_SetName(AMFObjectProperty *prop, AVal *name) +{ + prop->p_name = *name; +} + +AMFDataType +AMFProp_GetType(AMFObjectProperty *prop) +{ + return prop->p_type; +} + +double +AMFProp_GetNumber(AMFObjectProperty *prop) +{ + return prop->p_vu.p_number; +} + +bool +AMFProp_GetBoolean(AMFObjectProperty *prop) +{ + return prop->p_vu.p_number != 0; +} + +void +AMFProp_GetString(AMFObjectProperty *prop, AVal *str) +{ + *str = prop->p_vu.p_aval; +} + +void +AMFProp_GetObject(AMFObjectProperty *prop, AMFObject *obj) +{ + *obj = prop->p_vu.p_object; +} + +bool +AMFProp_IsValid(AMFObjectProperty *prop) +{ + return prop->p_type != AMF_INVALID; +} + +char * +AMFProp_Encode(AMFObjectProperty *prop, char *pBuffer, char *pBufEnd) +{ + if (prop->p_type == AMF_INVALID) + return NULL; + + if (prop->p_type != AMF_NULL && pBuffer + prop->p_name.av_len + 2 + 1 >= pBufEnd) + return NULL; + + if (prop->p_type != AMF_NULL && prop->p_name.av_len) + { + *pBuffer++ = prop->p_name.av_len >> 8; + *pBuffer++ = prop->p_name.av_len & 0xff; + memcpy(pBuffer, prop->p_name.av_val, prop->p_name.av_len); + pBuffer += prop->p_name.av_len; + } + + switch (prop->p_type) + { + case AMF_NUMBER: + pBuffer = AMF_EncodeNumber(pBuffer, pBufEnd, prop->p_vu.p_number); + break; + + case AMF_BOOLEAN: + pBuffer = AMF_EncodeBoolean(pBuffer, pBufEnd, prop->p_vu.p_number != 0); + break; + + case AMF_STRING: + pBuffer = AMF_EncodeString(pBuffer, pBufEnd, &prop->p_vu.p_aval); + break; + + case AMF_NULL: + if (pBuffer+1 >= pBufEnd) + return NULL; + *pBuffer++ = AMF_NULL; + break; + + case AMF_OBJECT: + pBuffer = AMF_Encode(&prop->p_vu.p_object, pBuffer, pBufEnd); + break; + + default: + RTMP_Log(RTMP_LOGERROR, "%s, invalid type. %d", __FUNCTION__, prop->p_type); + pBuffer = NULL; + }; + + return pBuffer; +} + +#define AMF3_INTEGER_MAX 268435455 +#define AMF3_INTEGER_MIN -268435456 + +int +AMF3ReadInteger(const char *data, int32_t *valp) +{ + int i = 0; + int32_t val = 0; + + while (i <= 2) + { /* handle first 3 bytes */ + if (data[i] & 0x80) + { // byte used + val <<= 7; // shift up + val |= (data[i] & 0x7f); // add bits + i++; + } + else + { + break; + } + } + + if (i > 2) + { // use 4th byte, all 8bits + val <<= 8; + val |= data[3]; + + // range check + if (val > AMF3_INTEGER_MAX) + val -= (1 << 29); + } + else + { // use 7bits of last unparsed byte (0xxxxxxx) + val <<= 7; + val |= data[i]; + } + + *valp = val; + + return i > 2 ? 4 : i + 1; +} + +int +AMF3ReadString(const char *data, AVal *str) +{ + assert(str != 0); + + int32_t ref = 0; + int len = AMF3ReadInteger(data, &ref); + data += len; + + if ((ref & 0x1) == 0) + { /* reference: 0xxx */ + uint32_t refIndex = (ref >> 1); + RTMP_Log(RTMP_LOGDEBUG, + "%s, string reference, index: %d, not supported, ignoring!", + __FUNCTION__, refIndex); + return len; + } + else + { + uint32_t nSize = (ref >> 1); + + str->av_val = (char *)data; + str->av_len = nSize; + + return len + nSize; + } + return len; +} + +int +AMF3Prop_Decode(AMFObjectProperty *prop, const char *pBuffer, int nSize, + bool bDecodeName) +{ + int nOriginalSize = nSize; + AMF3DataType type; + + prop->p_name.av_len = 0; + prop->p_name.av_val = NULL; + + if (nSize == 0 || !pBuffer) + { + RTMP_Log(RTMP_LOGDEBUG, "empty buffer/no buffer pointer!"); + return -1; + } + + /* decode name */ + if (bDecodeName) + { + AVal name; + int nRes = AMF3ReadString(pBuffer, &name); + + if (name.av_len <= 0) + return nRes; + + prop->p_name = name; + pBuffer += nRes; + nSize -= nRes; + } + + /* decode */ + type = *pBuffer++; + nSize--; + + switch (type) + { + case AMF3_UNDEFINED: + case AMF3_NULL: + prop->p_type = AMF_NULL; + break; + case AMF3_FALSE: + prop->p_type = AMF_BOOLEAN; + prop->p_vu.p_number = 0.0; + break; + case AMF3_TRUE: + prop->p_type = AMF_BOOLEAN; + prop->p_vu.p_number = 1.0; + break; + case AMF3_INTEGER: + { + int32_t res = 0; + int len = AMF3ReadInteger(pBuffer, &res); + prop->p_vu.p_number = (double)res; + prop->p_type = AMF_NUMBER; + nSize -= len; + break; + } + case AMF3_DOUBLE: + if (nSize < 8) + return -1; + prop->p_vu.p_number = AMF_DecodeNumber(pBuffer); + prop->p_type = AMF_NUMBER; + nSize -= 8; + break; + case AMF3_STRING: + case AMF3_XML_DOC: + case AMF3_XML: + { + int len = AMF3ReadString(pBuffer, &prop->p_vu.p_aval); + prop->p_type = AMF_STRING; + nSize -= len; + break; + } + case AMF3_DATE: + { + int32_t res = 0; + int len = AMF3ReadInteger(pBuffer, &res); + + nSize -= len; + pBuffer += len; + + if ((res & 0x1) == 0) + { /* reference */ + uint32_t nIndex = (res >> 1); + RTMP_Log(RTMP_LOGDEBUG, "AMF3_DATE reference: %d, not supported!", nIndex); + } + else + { + if (nSize < 8) + return -1; + + prop->p_vu.p_number = AMF_DecodeNumber(pBuffer); + nSize -= 8; + prop->p_type = AMF_NUMBER; + } + break; + } + case AMF3_OBJECT: + { + int nRes = AMF3_Decode(&prop->p_vu.p_object, pBuffer, nSize, true); + if (nRes == -1) + return -1; + nSize -= nRes; + prop->p_type = AMF_OBJECT; + break; + } + case AMF3_ARRAY: + case AMF3_BYTE_ARRAY: + default: + RTMP_Log(RTMP_LOGDEBUG, "%s - AMF3 unknown/unsupported datatype 0x%02x, @0x%08X", + __FUNCTION__, (unsigned char)(*pBuffer), pBuffer); + return -1; + } + + return nOriginalSize - nSize; +} + +int +AMFProp_Decode(AMFObjectProperty *prop, const char *pBuffer, int nSize, + bool bDecodeName) +{ + int nOriginalSize = nSize; + + prop->p_name.av_len = 0; + prop->p_name.av_val = NULL; + + if (nSize == 0 || !pBuffer) + { + RTMP_Log(RTMP_LOGDEBUG, "%s: Empty buffer/no buffer pointer!", __FUNCTION__); + return -1; + } + + if (bDecodeName && nSize < 4) + { /* at least name (length + at least 1 byte) and 1 byte of data */ + RTMP_Log(RTMP_LOGDEBUG, + "%s: Not enough data for decoding with name, less than 4 bytes!", + __FUNCTION__); + return -1; + } + + if (bDecodeName) + { + unsigned short nNameSize = AMF_DecodeInt16(pBuffer); + if (nNameSize > nSize - 2) + { + RTMP_Log(RTMP_LOGDEBUG, + "%s: Name size out of range: namesize (%d) > len (%d) - 2", + __FUNCTION__, nNameSize, nSize); + return -1; + } + + AMF_DecodeString(pBuffer, &prop->p_name); + nSize -= 2 + nNameSize; + pBuffer += 2 + nNameSize; + } + + if (nSize == 0) + { + return -1; + } + + nSize--; + + prop->p_type = *pBuffer++; + switch (prop->p_type) + { + case AMF_NUMBER: + if (nSize < 8) + return -1; + prop->p_vu.p_number = AMF_DecodeNumber(pBuffer); + nSize -= 8; + break; + case AMF_BOOLEAN: + if (nSize < 1) + return -1; + prop->p_vu.p_number = (double)AMF_DecodeBoolean(pBuffer); + nSize--; + break; + case AMF_STRING: + { + unsigned short nStringSize = AMF_DecodeInt16(pBuffer); + + if (nSize < (long)nStringSize + 2) + return -1; + AMF_DecodeString(pBuffer, &prop->p_vu.p_aval); + nSize -= (2 + nStringSize); + break; + } + case AMF_OBJECT: + { + int nRes = AMF_Decode(&prop->p_vu.p_object, pBuffer, nSize, true); + if (nRes == -1) + return -1; + nSize -= nRes; + break; + } + case AMF_MOVIECLIP: + { + RTMP_Log(RTMP_LOGERROR, "AMF_MOVIECLIP reserved!"); + return -1; + break; + } + case AMF_NULL: + case AMF_UNDEFINED: + case AMF_UNSUPPORTED: + prop->p_type = AMF_NULL; + break; + case AMF_REFERENCE: + { + RTMP_Log(RTMP_LOGERROR, "AMF_REFERENCE not supported!"); + return -1; + break; + } + case AMF_ECMA_ARRAY: + { + nSize -= 4; + + /* next comes the rest, mixed array has a final 0x000009 mark and names, so its an object */ + int nRes = AMF_Decode(&prop->p_vu.p_object, pBuffer + 4, nSize, true); + if (nRes == -1) + return -1; + nSize -= nRes; + prop->p_type = AMF_OBJECT; + break; + } + case AMF_OBJECT_END: + { + return -1; + break; + } + case AMF_STRICT_ARRAY: + { + unsigned int nArrayLen = AMF_DecodeInt32(pBuffer); + nSize -= 4; + + int nRes = AMF_DecodeArray(&prop->p_vu.p_object, pBuffer + 4, nSize, + nArrayLen, false); + if (nRes == -1) + return -1; + nSize -= nRes; + prop->p_type = AMF_OBJECT; + break; + } + case AMF_DATE: + { + RTMP_Log(RTMP_LOGDEBUG, "AMF_DATE"); + + if (nSize < 10) + return -1; + + prop->p_vu.p_number = AMF_DecodeNumber(pBuffer); + prop->p_UTCoffset = AMF_DecodeInt16(pBuffer + 8); + + nSize -= 10; + break; + } + case AMF_LONG_STRING: + { + unsigned int nStringSize = AMF_DecodeInt32(pBuffer); + if (nSize < (long)nStringSize + 4) + return -1; + AMF_DecodeLongString(pBuffer, &prop->p_vu.p_aval); + nSize -= (4 + nStringSize); + prop->p_type = AMF_STRING; + break; + } + case AMF_RECORDSET: + { + RTMP_Log(RTMP_LOGERROR, "AMF_RECORDSET reserved!"); + return -1; + break; + } + case AMF_XML_DOC: + { + RTMP_Log(RTMP_LOGERROR, "AMF_XML_DOC not supported!"); + return -1; + break; + } + case AMF_TYPED_OBJECT: + { + RTMP_Log(RTMP_LOGERROR, "AMF_TYPED_OBJECT not supported!"); + return -1; + break; + } + case AMF_AVMPLUS: + { + int nRes = AMF3_Decode(&prop->p_vu.p_object, pBuffer, nSize, true); + if (nRes == -1) + return -1; + nSize -= nRes; + prop->p_type = AMF_OBJECT; + break; + } + default: + RTMP_Log(RTMP_LOGDEBUG, "%s - unknown datatype 0x%02x, @0x%08X", __FUNCTION__, + prop->p_type, pBuffer - 1); + return -1; + } + + return nOriginalSize - nSize; +} + +void +AMFProp_Dump(AMFObjectProperty *prop) +{ + char strRes[256]; + char str[256]; + AVal name; + + if (prop->p_type == AMF_INVALID) + { + RTMP_Log(RTMP_LOGDEBUG, "Property: INVALID"); + return; + } + + if (prop->p_type == AMF_NULL) + { + RTMP_Log(RTMP_LOGDEBUG, "Property: NULL"); + return; + } + + if (prop->p_name.av_len) + { + name = prop->p_name; + } + else + { + name.av_val = "no-name."; + name.av_len = sizeof("no-name.") - 1; + } + if (name.av_len > 25) + name.av_len = 25; + + snprintf(strRes, 255, "Name: %25.*s, ", name.av_len, name.av_val); + + if (prop->p_type == AMF_OBJECT) + { + RTMP_Log(RTMP_LOGDEBUG, "Property: <%sOBJECT>", strRes); + AMF_Dump(&prop->p_vu.p_object); + return; + } + + switch (prop->p_type) + { + case AMF_NUMBER: + snprintf(str, 255, "NUMBER:\t%.2f", prop->p_vu.p_number); + break; + case AMF_BOOLEAN: + snprintf(str, 255, "BOOLEAN:\t%s", + prop->p_vu.p_number != 0.0 ? "TRUE" : "FALSE"); + break; + case AMF_STRING: + snprintf(str, 255, "STRING:\t%.*s", prop->p_vu.p_aval.av_len, + prop->p_vu.p_aval.av_val); + break; + case AMF_DATE: + snprintf(str, 255, "DATE:\ttimestamp: %.2f, UTC offset: %d", + prop->p_vu.p_number, prop->p_UTCoffset); + break; + default: + snprintf(str, 255, "INVALID TYPE 0x%02x", (unsigned char)prop->p_type); + } + + RTMP_Log(RTMP_LOGDEBUG, "Property: <%s%s>", strRes, str); +} + +void +AMFProp_Reset(AMFObjectProperty *prop) +{ + if (prop->p_type == AMF_OBJECT) + AMF_Reset(&prop->p_vu.p_object); + else + { + prop->p_vu.p_aval.av_len = 0; + prop->p_vu.p_aval.av_val = NULL; + } + prop->p_type = AMF_INVALID; +} + +/* AMFObject */ + +char * +AMF_Encode(AMFObject *obj, char *pBuffer, char *pBufEnd) +{ + int i; + + if (pBuffer+4 >= pBufEnd) + return NULL; + + *pBuffer++ = AMF_OBJECT; + + for (i = 0; i < obj->o_num; i++) + { + char *res = AMFProp_Encode(&obj->o_props[i], pBuffer, pBufEnd); + if (res == NULL) + { + RTMP_Log(RTMP_LOGERROR, "AMF_Encode - failed to encode property in index %d", + i); + break; + } + else + { + pBuffer = res; + } + } + + if (pBuffer + 3 >= pBufEnd) + return NULL; // no room for the end marker + + pBuffer = AMF_EncodeInt24(pBuffer, pBufEnd, AMF_OBJECT_END); + + return pBuffer; +} + +int +AMF_DecodeArray(AMFObject *obj, const char *pBuffer, int nSize, + int nArrayLen, bool bDecodeName) +{ + int nOriginalSize = nSize; + bool bError = false; + + obj->o_num = 0; + obj->o_props = NULL; + while (nArrayLen > 0) + { + nArrayLen--; + + AMFObjectProperty prop; + int nRes = AMFProp_Decode(&prop, pBuffer, nSize, bDecodeName); + if (nRes == -1) + bError = true; + else + { + nSize -= nRes; + pBuffer += nRes; + AMF_AddProp(obj, &prop); + } + } + if (bError) + return -1; + + return nOriginalSize - nSize; +} + +int +AMF3_Decode(AMFObject *obj, const char *pBuffer, int nSize, bool bAMFData) +{ + int nOriginalSize = nSize; + int32_t ref; + int len; + + obj->o_num = 0; + obj->o_props = NULL; + if (bAMFData) + { + if (*pBuffer != AMF3_OBJECT) + RTMP_Log(RTMP_LOGERROR, + "AMF3 Object encapsulated in AMF stream does not start with AMF3_OBJECT!"); + pBuffer++; + nSize--; + } + + ref = 0; + len = AMF3ReadInteger(pBuffer, &ref); + pBuffer += len; + nSize -= len; + + if ((ref & 1) == 0) + { /* object reference, 0xxx */ + uint32_t objectIndex = (ref >> 1); + + RTMP_Log(RTMP_LOGDEBUG, "Object reference, index: %d", objectIndex); + } + else /* object instance */ + { + int32_t classRef = (ref >> 1); + + AMF3ClassDef cd = { {0, 0} + }; + AMFObjectProperty prop; + + if ((classRef & 0x1) == 0) + { /* class reference */ + uint32_t classIndex = (classRef >> 1); + RTMP_Log(RTMP_LOGDEBUG, "Class reference: %d", classIndex); + } + else + { + int32_t classExtRef = (classRef >> 1); + int i; + + cd.cd_externalizable = (classExtRef & 0x1) == 1; + cd.cd_dynamic = ((classExtRef >> 1) & 0x1) == 1; + + cd.cd_num = classExtRef >> 2; + + // class name + + len = AMF3ReadString(pBuffer, &cd.cd_name); + nSize -= len; + pBuffer += len; + + //std::string str = className; + + RTMP_Log(RTMP_LOGDEBUG, + "Class name: %s, externalizable: %d, dynamic: %d, classMembers: %d", + cd.cd_name.av_val, cd.cd_externalizable, cd.cd_dynamic, + cd.cd_num); + + for (i = 0; i < cd.cd_num; i++) + { + AVal memberName; + len = AMF3ReadString(pBuffer, &memberName); + RTMP_Log(RTMP_LOGDEBUG, "Member: %s", memberName.av_val); + AMF3CD_AddProp(&cd, &memberName); + nSize -= len; + pBuffer += len; + } + } + + /* add as referencable object */ + + if (cd.cd_externalizable) + { + int nRes; + AVal name = AVC("DEFAULT_ATTRIBUTE"); + + RTMP_Log(RTMP_LOGDEBUG, "Externalizable, TODO check"); + + nRes = AMF3Prop_Decode(&prop, pBuffer, nSize, false); + if (nRes == -1) + RTMP_Log(RTMP_LOGDEBUG, "%s, failed to decode AMF3 property!", + __FUNCTION__); + else + { + nSize -= nRes; + pBuffer += nRes; + } + + AMFProp_SetName(&prop, &name); + AMF_AddProp(obj, &prop); + } + else + { + int nRes, i; + for (i = 0; i < cd.cd_num; i++) /* non-dynamic */ + { + nRes = AMF3Prop_Decode(&prop, pBuffer, nSize, false); + if (nRes == -1) + RTMP_Log(RTMP_LOGDEBUG, "%s, failed to decode AMF3 property!", + __FUNCTION__); + + AMFProp_SetName(&prop, AMF3CD_GetProp(&cd, i)); + AMF_AddProp(obj, &prop); + + pBuffer += nRes; + nSize -= nRes; + } + if (cd.cd_dynamic) + { + int len = 0; + + do + { + nRes = AMF3Prop_Decode(&prop, pBuffer, nSize, true); + AMF_AddProp(obj, &prop); + + pBuffer += nRes; + nSize -= nRes; + + len = prop.p_name.av_len; + } + while (len > 0); + } + } + RTMP_Log(RTMP_LOGDEBUG, "class object!"); + } + return nOriginalSize - nSize; +} + +int +AMF_Decode(AMFObject *obj, const char *pBuffer, int nSize, bool bDecodeName) +{ + int nOriginalSize = nSize; + bool bError = false; /* if there is an error while decoding - try to at least find the end mark AMF_OBJECT_END */ + + obj->o_num = 0; + obj->o_props = NULL; + while (nSize > 0) + { + AMFObjectProperty prop; + int nRes; + + if (nSize >=3 && AMF_DecodeInt24(pBuffer) == AMF_OBJECT_END) + { + nSize -= 3; + bError = false; + break; + } + + if (bError) + { + RTMP_Log(RTMP_LOGERROR, + "DECODING ERROR, IGNORING BYTES UNTIL NEXT KNOWN PATTERN!"); + nSize--; + pBuffer++; + continue; + } + + nRes = AMFProp_Decode(&prop, pBuffer, nSize, bDecodeName); + if (nRes == -1) + bError = true; + else + { + nSize -= nRes; + pBuffer += nRes; + AMF_AddProp(obj, &prop); + } + } + + if (bError) + return -1; + + return nOriginalSize - nSize; +} + +void +AMF_AddProp(AMFObject *obj, const AMFObjectProperty *prop) +{ + if (!(obj->o_num & 0x0f)) + obj->o_props = + realloc(obj->o_props, (obj->o_num + 16) * sizeof(AMFObjectProperty)); + obj->o_props[obj->o_num++] = *prop; +} + +int +AMF_CountProp(AMFObject *obj) +{ + return obj->o_num; +} + +AMFObjectProperty * +AMF_GetProp(AMFObject *obj, const AVal *name, int nIndex) +{ + if (nIndex >= 0) + { + if (nIndex <= obj->o_num) + return &obj->o_props[nIndex]; + } + else + { + int n; + for (n = 0; n < obj->o_num; n++) + { + if (AVMATCH(&obj->o_props[n].p_name, name)) + return &obj->o_props[n]; + } + } + + return (AMFObjectProperty *)&AMFProp_Invalid; +} + +void +AMF_Dump(AMFObject *obj) +{ + int n; + RTMP_Log(RTMP_LOGDEBUG, "(object begin)"); + for (n = 0; n < obj->o_num; n++) + { + AMFProp_Dump(&obj->o_props[n]); + } + RTMP_Log(RTMP_LOGDEBUG, "(object end)"); +} + +void +AMF_Reset(AMFObject *obj) +{ + int n; + for (n = 0; n < obj->o_num; n++) + { + AMFProp_Reset(&obj->o_props[n]); + } + free(obj->o_props); + obj->o_props = NULL; + obj->o_num = 0; +} + + +/* AMF3ClassDefinition */ + +void +AMF3CD_AddProp(AMF3ClassDef *cd, AVal *prop) +{ + if (!(cd->cd_num & 0x0f)) + cd->cd_props = realloc(cd->cd_props, (cd->cd_num + 16) * sizeof(AVal)); + cd->cd_props[cd->cd_num++] = *prop; +} + +AVal * +AMF3CD_GetProp(AMF3ClassDef *cd, int nIndex) +{ + if (nIndex >= cd->cd_num) + return (AVal *)&AV_empty; + return &cd->cd_props[nIndex]; +} diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/amf.h xbmc-trunk-28276/xbmc/lib/libRTMP/amf.h --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/amf.h 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/amf.h 2010-04-04 22:58:14.382141953 +0100 @@ -0,0 +1,158 @@ +#ifndef __AMF_H__ +#define __AMF_H__ +/* + * Copyright (C) 2005-2008 Team XBMC + * http://www.xbmc.org + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#ifndef _MSC_VER +#include +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + + typedef enum + { AMF_NUMBER = 0, AMF_BOOLEAN, AMF_STRING, AMF_OBJECT, + AMF_MOVIECLIP, /* reserved, not used */ + AMF_NULL, AMF_UNDEFINED, AMF_REFERENCE, AMF_ECMA_ARRAY, AMF_OBJECT_END, + AMF_STRICT_ARRAY, AMF_DATE, AMF_LONG_STRING, AMF_UNSUPPORTED, + AMF_RECORDSET, /* reserved, not used */ + AMF_XML_DOC, AMF_TYPED_OBJECT, + AMF_AVMPLUS, /* switch to AMF3 */ + AMF_INVALID = 0xff + } AMFDataType; + + typedef enum + { AMF3_UNDEFINED = 0, AMF3_NULL, AMF3_FALSE, AMF3_TRUE, + AMF3_INTEGER, AMF3_DOUBLE, AMF3_STRING, AMF3_XML_DOC, AMF3_DATE, + AMF3_ARRAY, AMF3_OBJECT, AMF3_XML, AMF3_BYTE_ARRAY + } AMF3DataType; + + typedef struct AVal + { + char *av_val; + int av_len; + } AVal; +#define AVC(str) {str,sizeof(str)-1} +#define AVMATCH(a1,a2) ((a1)->av_len == (a2)->av_len && !memcmp((a1)->av_val,(a2)->av_val,(a1)->av_len)) + + struct AMFObjectProperty; + + typedef struct AMFObject + { + int o_num; + struct AMFObjectProperty *o_props; + } AMFObject; + + typedef struct AMFObjectProperty + { + AVal p_name; + AMFDataType p_type; + union + { + double p_number; + AVal p_aval; + AMFObject p_object; + } p_vu; + int16_t p_UTCoffset; + } AMFObjectProperty; + + char *AMF_EncodeString(char *output, char *outend, const AVal * str); + char *AMF_EncodeNumber(char *output, char *outend, double dVal); + char *AMF_EncodeInt16(char *output, char *outend, short nVal); + char *AMF_EncodeInt24(char *output, char *outend, int nVal); + char *AMF_EncodeInt32(char *output, char *outend, int nVal); + char *AMF_EncodeBoolean(char *output, char *outend, bool bVal); + + /* Shortcuts for AMFProp_Encode */ + char *AMF_EncodeNamedString(char *output, char *outend, const AVal * name, const AVal * value); + char *AMF_EncodeNamedNumber(char *output, char *outend, const AVal * name, double dVal); + char *AMF_EncodeNamedBoolean(char *output, char *outend, const AVal * name, bool bVal); + + unsigned short AMF_DecodeInt16(const char *data); + unsigned int AMF_DecodeInt24(const char *data); + unsigned int AMF_DecodeInt32(const char *data); + void AMF_DecodeString(const char *data, AVal * str); + void AMF_DecodeLongString(const char *data, AVal * str); + bool AMF_DecodeBoolean(const char *data); + double AMF_DecodeNumber(const char *data); + + char *AMF_Encode(AMFObject * obj, char *pBuffer, char *pBufEnd); + int AMF_Decode(AMFObject * obj, const char *pBuffer, int nSize, + bool bDecodeName); + int AMF_DecodeArray(AMFObject * obj, const char *pBuffer, int nSize, + int nArrayLen, bool bDecodeName); + int AMF3_Decode(AMFObject * obj, const char *pBuffer, int nSize, + bool bDecodeName); + void AMF_Dump(AMFObject * obj); + void AMF_Reset(AMFObject * obj); + + void AMF_AddProp(AMFObject * obj, const AMFObjectProperty * prop); + int AMF_CountProp(AMFObject * obj); + AMFObjectProperty *AMF_GetProp(AMFObject * obj, const AVal * name, + int nIndex); + + AMFDataType AMFProp_GetType(AMFObjectProperty * prop); + void AMFProp_SetNumber(AMFObjectProperty * prop, double dval); + void AMFProp_SetBoolean(AMFObjectProperty * prop, bool bflag); + void AMFProp_SetString(AMFObjectProperty * prop, AVal * str); + void AMFProp_SetObject(AMFObjectProperty * prop, AMFObject * obj); + + void AMFProp_GetName(AMFObjectProperty * prop, AVal * name); + void AMFProp_SetName(AMFObjectProperty * prop, AVal * name); + double AMFProp_GetNumber(AMFObjectProperty * prop); + bool AMFProp_GetBoolean(AMFObjectProperty * prop); + void AMFProp_GetString(AMFObjectProperty * prop, AVal * str); + void AMFProp_GetObject(AMFObjectProperty * prop, AMFObject * obj); + + bool AMFProp_IsValid(AMFObjectProperty * prop); + + char *AMFProp_Encode(AMFObjectProperty * prop, char *pBuffer, char *pBufEnd); + int AMF3Prop_Decode(AMFObjectProperty * prop, const char *pBuffer, + int nSize, bool bDecodeName); + int AMFProp_Decode(AMFObjectProperty * prop, const char *pBuffer, + int nSize, bool bDecodeName); + + void AMFProp_Dump(AMFObjectProperty * prop); + void AMFProp_Reset(AMFObjectProperty * prop); + + typedef struct AMF3ClassDef + { + AVal cd_name; + char cd_externalizable; + char cd_dynamic; + int cd_num; + AVal *cd_props; + } AMF3ClassDef; + + void AMF3CD_AddProp(AMF3ClassDef * cd, AVal * prop); + AVal *AMF3CD_GetProp(AMF3ClassDef * cd, int idx); + +#ifdef __cplusplus +} +#endif + +#endif /* __AMF_H__ */ diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/AMFObject.cpp xbmc-trunk-28276/xbmc/lib/libRTMP/AMFObject.cpp --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/AMFObject.cpp 2010-04-04 11:46:52.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/AMFObject.cpp 1970-01-01 01:00:00.000000000 +0100 @@ -1,424 +0,0 @@ -/* - * Copyright (C) 2005-2008 Team XBMC - * http://www.xbmc.org - * - * This file is part of libRTMP. - * - * libRTMP 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. - * - * libRTMP 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 libRTMP; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifdef _LINUX - #include - #include "linux/PlatformInclude.h" -#endif - -#include "utils/log.h" -#include "StdString.h" -#include "AMFObject.h" -#include "rtmp.h" - -RTMP_LIB::AMFObjectProperty RTMP_LIB::AMFObject::m_invalidProp; - -RTMP_LIB::AMFObjectProperty::AMFObjectProperty() -{ - Reset(); -} - -RTMP_LIB::AMFObjectProperty::AMFObjectProperty(const std::string & strName, double dValue) -{ - Reset(); -} - -RTMP_LIB::AMFObjectProperty::AMFObjectProperty(const std::string & strName, bool bValue) -{ - Reset(); -} - -RTMP_LIB::AMFObjectProperty::AMFObjectProperty(const std::string & strName, const std::string & strValue) -{ - Reset(); -} - -RTMP_LIB::AMFObjectProperty::AMFObjectProperty(const std::string & strName, const AMFObject & objValue) -{ - Reset(); -} - -RTMP_LIB::AMFObjectProperty::~ AMFObjectProperty() -{ -} - -const std::string &RTMP_LIB::AMFObjectProperty::GetPropName() const -{ - return m_strName; -} - -RTMP_LIB::AMFDataType RTMP_LIB::AMFObjectProperty::GetType() const -{ - return m_type; -} - -double RTMP_LIB::AMFObjectProperty::GetNumber() const -{ - return m_dNumVal; -} - -bool RTMP_LIB::AMFObjectProperty::GetBoolean() const -{ - return m_dNumVal != 0; -} - -const std::string &RTMP_LIB::AMFObjectProperty::GetString() const -{ - return m_strVal; -} - -const RTMP_LIB::AMFObject &RTMP_LIB::AMFObjectProperty::GetObject() const -{ - return m_objVal; -} - -bool RTMP_LIB::AMFObjectProperty::IsValid() const -{ - return (m_type != AMF_INVALID); -} - -int RTMP_LIB::AMFObjectProperty::Encode(char * pBuffer, int nSize) const -{ - int nBytes = 0; - - if (m_type == AMF_INVALID) - return -1; - - if (m_type != AMF_NULL && nSize < (int)m_strName.size() + (int)sizeof(short) + 1) - return -1; - - if (m_type != AMF_NULL && !m_strName.empty()) - { - nBytes += EncodeName(pBuffer); - pBuffer += nBytes; - nSize -= nBytes; - } - - switch (m_type) - { - case AMF_NUMBER: - if (nSize < 9) - return -1; - nBytes += RTMP_LIB::CRTMP::EncodeNumber(pBuffer, GetNumber()); - break; - - case AMF_BOOLEAN: - if (nSize < 2) - return -1; - nBytes += RTMP_LIB::CRTMP::EncodeBoolean(pBuffer, GetBoolean()); - break; - - case AMF_STRING: - if (nSize < (int)m_strVal.size() + (int)sizeof(short)) - return -1; - nBytes += RTMP_LIB::CRTMP::EncodeString(pBuffer, GetString()); - break; - - case AMF_NULL: - if (nSize < 1) - return -1; - *pBuffer = 0x05; - nBytes += 1; - break; - - case AMF_OBJECT: - { - int nRes = m_objVal.Encode(pBuffer, nSize); - if (nRes == -1) - return -1; - - nBytes += nRes; - break; - } - default: - CLog::Log(LOGERROR,"%s, invalid type. %d", __FUNCTION__, m_type); - return -1; - }; - - return nBytes; -} - -int RTMP_LIB::AMFObjectProperty::Decode(const char * pBuffer, int nSize, bool bDecodeName) -{ - int nOriginalSize = nSize; - - if (nSize == 0 || !pBuffer) - return -1; - - if (*pBuffer == 0x05) - { - m_type = AMF_NULL; - return 1; - } - - if (bDecodeName && nSize < 4) // at least name (length + at least 1 byte) and 1 byte of data - return -1; - - if (bDecodeName) - { - short nNameSize = RTMP_LIB::CRTMP::ReadInt16(pBuffer); - if (nNameSize > nSize - (short)sizeof(short)) - return -1; - - m_strName = RTMP_LIB::CRTMP::ReadString(pBuffer); - nSize -= sizeof(short) + m_strName.size(); - pBuffer += sizeof(short) + m_strName.size(); - } - - if (nSize == 0) - return -1; - - nSize--; - - switch (*pBuffer) - { - case 0x00: //AMF_NUMBER: - if (nSize < (int)sizeof(double)) - return -1; - m_dNumVal = RTMP_LIB::CRTMP::ReadNumber(pBuffer+1); - nSize -= sizeof(double); - m_type = AMF_NUMBER; - break; - case 0x01: //AMF_BOOLEAN: - if (nSize < 1) - return -1; - m_dNumVal = (double)RTMP_LIB::CRTMP::ReadBool(pBuffer+1); - nSize--; - m_type = AMF_BOOLEAN; - break; - case 0x02: //AMF_STRING: - { - short nStringSize = RTMP_LIB::CRTMP::ReadInt16(pBuffer+1); - if (nSize < nStringSize + (int)sizeof(short)) - return -1; - m_strVal = RTMP_LIB::CRTMP::ReadString(pBuffer+1); - nSize -= sizeof(short) + nStringSize; - m_type = AMF_STRING; - break; - } - case 0x03: //AMF_OBJECT: - { - int nRes = m_objVal.Decode(pBuffer+1, nSize, true); - if (nRes == -1) - return -1; - nSize -= nRes; - m_type = AMF_OBJECT; - break; - } - default: - CLog::Log(LOGDEBUG,"%s - unknown datatype 0x%02x", __FUNCTION__, (unsigned char)(*pBuffer)); - return -1; - } - - return nOriginalSize - nSize; -} - -void RTMP_LIB::AMFObjectProperty::Dump() const -{ - if (m_type == AMF_INVALID) - { - CLog::Log(LOGDEBUG,"Property: INVALID"); - return; - } - - if (m_type == AMF_NULL) - { - CLog::Log(LOGDEBUG,"Property: NULL"); - return; - } - - if (m_type == AMF_OBJECT) - { - CLog::Log(LOGDEBUG,"Property: OBJECT ====>"); - m_objVal.Dump(); - return; - } - - CStdString strRes = "no-name. "; - if (!m_strName.empty()) - strRes = "Name: " + m_strName + ", "; - - CStdString strVal; - - switch(m_type) - { - case AMF_NUMBER: - strVal.Format("NUMBER: %.2f", m_dNumVal); - break; - case AMF_BOOLEAN: - strVal.Format("BOOLEAN: %s", m_dNumVal == 1.?"TRUE":"FALSE"); - break; - case AMF_STRING: - strVal.Format("STRING: %s", m_strVal.c_str()); - break; - default: - strVal.Format("INVALID TYPE 0x%02x", (unsigned char)m_type); - } - - strRes += strVal; - CLog::Log(LOGDEBUG,"Property: <%s>", strRes.c_str()); -} - -void RTMP_LIB::AMFObjectProperty::Reset() -{ - m_dNumVal = 0.; - m_strVal.clear(); - m_objVal.Reset(); - m_type = AMF_INVALID; -} - -int RTMP_LIB::AMFObjectProperty::EncodeName(char *pBuffer) const -{ - short length = htons(m_strName.size()); - memcpy(pBuffer, &length, sizeof(short)); - pBuffer += sizeof(short); - - memcpy(pBuffer, m_strName.c_str(), m_strName.size()); - return m_strName.size() + sizeof(short); -} - - -// AMFObject - -RTMP_LIB::AMFObject::AMFObject() -{ - Reset(); -} - -RTMP_LIB::AMFObject::~ AMFObject() -{ - Reset(); -} - -int RTMP_LIB::AMFObject::Encode(char * pBuffer, int nSize) const -{ - if (nSize < 4) - return -1; - - *pBuffer = 0x03; // object - - int nOriginalSize = nSize; - for (size_t i=0; i 3) - { - if (RTMP_LIB::CRTMP::ReadInt24(pBuffer) == 0x00000009) - { - nSize -= 3; - bError = false; - break; - } - - if (bError) - { - nSize--; - pBuffer++; - continue; - } - - RTMP_LIB::AMFObjectProperty prop; - int nRes = prop.Decode(pBuffer, nSize, bDecodeName); - if (nRes == -1) - bError = true; - else - { - nSize -= nRes; - pBuffer += nRes; - m_properties.push_back(prop); - } - } - - if (bError) - return -1; - - return nOriginalSize - nSize; -} - -void RTMP_LIB::AMFObject::AddProperty(const AMFObjectProperty & prop) -{ - m_properties.push_back(prop); -} - -int RTMP_LIB::AMFObject::GetPropertyCount() const -{ - return m_properties.size(); -} - -const RTMP_LIB::AMFObjectProperty & RTMP_LIB::AMFObject::GetProperty(const std::string & strName) const -{ - for (size_t n=0; n= m_properties.size()) - return m_invalidProp; - - return m_properties[nIndex]; -} - -void RTMP_LIB::AMFObject::Dump() const -{ - CLog::Log(LOGDEBUG,"START AMF Object Dump:"); - - for (size_t n=0; n -#include - -#ifdef _WIN32 -#undef GetObject // WIN32INCLUDES defined in WinGDI.h which appears to be included from _somewhere_ -#endif - -namespace RTMP_LIB -{ - typedef enum {AMF_INVALID, AMF_NUMBER, AMF_BOOLEAN, AMF_STRING, AMF_OBJECT, AMF_NULL } AMFDataType; - - class AMFObjectProperty; - class AMFObject - { - public: - AMFObject(); - virtual ~AMFObject(); - - int Encode(char *pBuffer, int nSize) const; - int Decode(const char *pBuffer, int nSize, bool bDecodeName=false); - - void AddProperty(const AMFObjectProperty &prop); - - int GetPropertyCount() const; - const AMFObjectProperty &GetProperty(const std::string &strName) const; - const AMFObjectProperty &GetProperty(size_t nIndex) const; - - void Dump() const; - void Reset(); - protected: - static AMFObjectProperty m_invalidProp; // returned when no prop matches - std::vector m_properties; - }; - - class AMFObjectProperty - { - public: - AMFObjectProperty(); - AMFObjectProperty(const std::string &strName, double dValue); - AMFObjectProperty(const std::string &strName, bool bValue); - AMFObjectProperty(const std::string &strName, const std::string &strValue); - AMFObjectProperty(const std::string &strName, const AMFObject &objValue); - - virtual ~AMFObjectProperty(); - - const std::string &GetPropName() const; - - AMFDataType GetType() const; - - bool IsValid() const; - - double GetNumber() const; - bool GetBoolean() const; - const std::string &GetString() const; - const AMFObject &GetObject() const; - - int Encode(char *pBuffer, int nSize) const; - int Decode(const char *pBuffer, int nSize, bool bDecodeName); - - void Reset(); - void Dump() const; - protected: - int EncodeName(char *pBuffer) const; - - std::string m_strName; - - AMFDataType m_type; - double m_dNumVal; - AMFObject m_objVal; - std::string m_strVal; - }; - -}; - -#endif diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/bytes.h xbmc-trunk-28276/xbmc/lib/libRTMP/bytes.h --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/bytes.h 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/bytes.h 2010-04-04 22:58:14.452140653 +0100 @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2005-2008 Team XBMC + * http://www.xbmc.org + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#ifndef __BYTES_H__ +#define __BYTES_H__ + +#include + +#ifdef WIN32 +// Windows is little endian only +#define __LITTLE_ENDIAN 1234 +#define __BIG_ENDIAN 4321 +#define __BYTE_ORDER __LITTLE_ENDIAN +#define __FLOAT_WORD_ORDER __BYTE_ORDER + +typedef unsigned char uint8_t; + +#else /* !WIN32 */ + +#include + +#if defined(BYTE_ORDER) && !defined(__BYTE_ORDER) +#define __BYTE_ORDER BYTE_ORDER +#endif + +#if defined(BIG_ENDIAN) && !defined(__BIG_ENDIAN) +#define __BIG_ENDIAN BIG_ENDIAN +#endif + +#if defined(LITTLE_ENDIAN) && !defined(__LITTLE_ENDIAN) +#define __LITTLE_ENDIAN LITTLE_ENDIAN +#endif + +#endif /* !WIN32 */ + +// define default endianness +#ifndef __LITTLE_ENDIAN +#define __LITTLE_ENDIAN 1234 +#endif + +#ifndef __BIG_ENDIAN +#define __BIG_ENDIAN 4321 +#endif + +#ifndef __BYTE_ORDER +#warning "Byte order not defined on your system, assuming little endian!" +#define __BYTE_ORDER __LITTLE_ENDIAN +#endif + +// ok, we assume to have the same float word order and byte order if float word order is not defined +#ifndef __FLOAT_WORD_ORDER +#warning "Float word order not defined, assuming the same as byte order!" +#define __FLOAT_WORD_ORDER __BYTE_ORDER +#endif + +#if !defined(__BYTE_ORDER) || !defined(__FLOAT_WORD_ORDER) +#error "Undefined byte or float word order!" +#endif + +#if __FLOAT_WORD_ORDER != __BIG_ENDIAN && __FLOAT_WORD_ORDER != __LITTLE_ENDIAN +#error "Unknown/unsupported float word order!" +#endif + +#if __BYTE_ORDER != __BIG_ENDIAN && __BYTE_ORDER != __LITTLE_ENDIAN +#error "Unknown/unsupported byte order!" +#endif + +#endif + diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/COPYING xbmc-trunk-28276/xbmc/lib/libRTMP/COPYING --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/COPYING 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/COPYING 2010-04-04 22:58:14.442139242 +0100 @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library 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. + + This library 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 this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/copying.txt xbmc-trunk-28276/xbmc/lib/libRTMP/copying.txt --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/copying.txt 2010-04-04 11:46:52.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/copying.txt 1970-01-01 01:00:00.000000000 +0100 @@ -1,504 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library 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. - - This library 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 this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - - diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/dhgroups.h xbmc-trunk-28276/xbmc/lib/libRTMP/dhgroups.h --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/dhgroups.h 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/dhgroups.h 2010-04-04 22:58:14.412143252 +0100 @@ -0,0 +1,198 @@ +/* librtmp - Diffie-Hellmann Key Exchange + * Copyright (C) 2009 Andrej Stepanchuk + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +/* from RFC 3526, see http://www.ietf.org/rfc/rfc3526.txt */ + +// 2^768 - 2 ^704 - 1 + 2^64 * { [2^638 pi] + 149686 } +#define P768 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A63A3620FFFFFFFFFFFFFFFF" + +// 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 } +#define P1024 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381" \ + "FFFFFFFFFFFFFFFF" + +// Group morder largest prime factor: +#define Q1024 \ + "7FFFFFFFFFFFFFFFE487ED5110B4611A62633145C06E0E68" \ + "948127044533E63A0105DF531D89CD9128A5043CC71A026E" \ + "F7CA8CD9E69D218D98158536F92F8A1BA7F09AB6B6A8E122" \ + "F242DABB312F3F637A262174D31BF6B585FFAE5B7A035BF6" \ + "F71C35FDAD44CFD2D74F9208BE258FF324943328F67329C0" \ + "FFFFFFFFFFFFFFFF" + +// 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 } +#define P1536 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF" + +// 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 } +#define P2048 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AACAA68FFFFFFFFFFFFFFFF" + +// 2^3072 - 2^3008 - 1 + 2^64 * { [2^2942 pi] + 1690314 } +#define P3072 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF" + +// 2^4096 - 2^4032 - 1 + 2^64 * { [2^3966 pi] + 240904 } +#define P4096 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" \ + "FFFFFFFFFFFFFFFF" + +// 2^6144 - 2^6080 - 1 + 2^64 * { [2^6014 pi] + 929484 } +#define P6144 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" \ + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD" \ + "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831" \ + "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B" \ + "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF" \ + "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6" \ + "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3" \ + "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" \ + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328" \ + "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C" \ + "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE" \ + "12BF2D5B0B7474D6E694F91E6DCC4024FFFFFFFFFFFFFFFF" + +// 2^8192 - 2^8128 - 1 + 2^64 * { [2^8062 pi] + 4743158 } +#define P8192 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" \ + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD" \ + "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831" \ + "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B" \ + "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF" \ + "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6" \ + "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3" \ + "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" \ + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328" \ + "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C" \ + "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE" \ + "12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4" \ + "38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300" \ + "741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568" \ + "3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" \ + "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B" \ + "4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A" \ + "062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36" \ + "4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1" \ + "B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92" \ + "4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47" \ + "9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" \ + "60C980DD98EDD3DFFFFFFFFFFFFFFFFF" + diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/dh.h xbmc-trunk-28276/xbmc/lib/libRTMP/dh.h --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/dh.h 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/dh.h 2010-04-04 22:58:14.482143418 +0100 @@ -0,0 +1,302 @@ +/* RTMPDump - Diffie-Hellmann Key Exchange + * Copyright (C) 2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#include +#include +#include +#include + +#ifdef USE_GNUTLS +#include +typedef gcry_mpi_t MP_t; +#define MP_new() gcry_mpi_new(1) +#define MP_set_w(mpi, w) gcry_mpi_set_ui(mpi, w) +#define MP_cmp(u, v) gcry_mpi_cmp(u, v) +#define MP_set(u, v) gcry_mpi_set(u, v) +#define MP_sub_w(mpi, w) gcry_mpi_sub_ui(mpi, mpi, w) +#define MP_cmp_1(mpi) gcry_mpi_cmp_ui(mpi, 1) +#define MP_modexp(r, y, q, p) gcry_mpi_powm(r, y, q, p) +#define MP_free(mpi) gcry_mpi_release(mpi) +#define MP_gethex(u, hex, res) res = (gcry_mpi_scan(u, GCRYMPI_FMT_HEX, hex, 0, 0) == 0) +#define MP_bytes(u) (gcry_mpi_get_nbits(u) + 7) / 8 +#define MP_setbin(u,buf,len) gcry_mpi_print(GCRYMPI_FMT_USG,buf,len,NULL,u) +#define MP_getbin(u,buf,len) gcry_mpi_scan(&u,GCRYMPI_FMT_USG,buf,len,NULL) + +typedef struct MDH { + MP_t p; + MP_t g; + MP_t pub_key; + MP_t priv_key; + long length; +} MDH; + +#define MDH_new() calloc(1,sizeof(MDH)) +#define MDH_free(dh) do {MP_free(((MDH*)(dh))->p); MP_free(((MDH*)(dh))->g); MP_free(((MDH*)(dh))->pub_key); MP_free(((MDH*)(dh))->priv_key); free(dh);} while(0) + +extern MP_t gnutls_calc_dh_secret(MP_t *priv, MP_t g, MP_t p); +extern MP_t gnutls_calc_dh_key(MP_t y, MP_t x, MP_t p); + + +#define MDH_generate_key(dh) (dh->pub_key = gnutls_calc_dh_secret(&dh->priv_key, dh->g, dh->p)) +static int MDH_compute_key(uint8_t *secret, size_t len, MP_t pub, MDH *dh) +{ + MP_t sec = gnutls_calc_dh_key(pub, dh->priv_key, dh->p); + if (sec) + { + MP_setbin(sec, secret, len); + MP_free(sec); + return 0; + } + else + return -1; +} + +#else +#include +#include + +typedef BIGNUM * MP_t; +#define MP_new() BN_new() +#define MP_set_w(mpi, w) BN_set_word(mpi, w) +#define MP_cmp(u, v) BN_cmp(u, v) +#define MP_set(u, v) BN_copy(u, v) +#define MP_sub_w(mpi, w) BN_sub_word(mpi, w) +#define MP_cmp_1(mpi) BN_cmp(mpi, BN_value_one()) +#define MP_modexp(r, y, q, p) do {BN_CTX *ctx = BN_CTX_new(); BN_mod_exp(r, y, q, p, ctx); BN_CTX_free(ctx);} while(0) +#define MP_free(mpi) BN_free(mpi) +#define MP_gethex(u, hex, res) res = BN_hex2bn(u, hex) +#define MP_bytes(u) BN_num_bytes(u) +#define MP_setbin(u,buf,len) BN_bn2bin(u,buf) +#define MP_getbin(u,buf,len) u = BN_bin2bn(buf,len,0) + +#define MDH DH +#define MDH_new() DH_new() +#define MDH_free(dh) DH_free(dh) +#define MDH_generate_key(dh) DH_generate_key(dh) +#define MDH_compute_key(secret, seclen, pub, dh) DH_compute_key(secret, pub, dh) + +#endif + +#include "log.h" +#include "dhgroups.h" + +/* +MP_t dh_shared_p = 0; // shared prime +MP_t dh_shared_g = 0; // shared base + +void dh_pg_init() +{ + int res; + if(dh_shared_p || dh_shared_g) + return; + + dh_shared_p = MP_new(); + dh_shared_g = MP_new(); + assert(dh_shared_p && dh_shared_g); + + MP_gethex(&dh_shared_p, P1024, res); // prime P1024, see dhgroups.h + assert(res); + + assert(MP_set_w(dh_shared_g, 2)); // base 2 +} +*/ + +// RFC 2631, Section 2.1.5, http://www.ietf.org/rfc/rfc2631.txt +static bool +isValidPublicKey(MP_t y, MP_t p, MP_t q) +{ + int ret = true; + assert(y); + + MP_t bn = MP_new(); + assert(bn); + + // y must lie in [2,p-1] + MP_set_w(bn, 1); + if (MP_cmp(y, bn) < 0) + { + RTMP_Log(RTMP_LOGERROR, "DH public key must be at least 2"); + ret = false; + goto failed; + } + + // bn = p-2 + MP_set(bn, p); + MP_sub_w(bn, 1); + if (MP_cmp(y, bn) > 0) + { + RTMP_Log(RTMP_LOGERROR, "DH public key must be at most p-2"); + ret = false; + goto failed; + } + + // Verify with Sophie-Germain prime + // + // This is a nice test to make sure the public key position is calculated + // correctly. This test will fail in about 50% of the cases if applied to + // random data. + // + if (q) + { + // y must fulfill y^q mod p = 1 + MP_modexp(bn, y, q, p); + + if (MP_cmp_1(bn) != 0) + { + RTMP_Log(RTMP_LOGWARNING, "DH public key does not fulfill y^q mod p = 1"); + } + } + +failed: + MP_free(bn); + return ret; +} + +static MDH * +DHInit(int nKeyBits) +{ + size_t res; + MDH *dh = MDH_new(); + + if (!dh) + goto failed; + + dh->g = MP_new(); + + if (!dh->g) + goto failed; + + MP_gethex(&dh->p, P1024, res); // prime P1024, see dhgroups.h + if (!res) + { + goto failed; + } + + if (!MP_set_w(dh->g, 2)) // base 2 + { + goto failed; + } + + dh->length = nKeyBits; + return dh; + +failed: + if (dh) + MDH_free(dh); + + return 0; +} + +static int +DHGenerateKey(MDH *dh) +{ + if (!dh) + return 0; + + size_t res = 0; + while (!res) + { + if (!MDH_generate_key(dh)) + return 0; + + MP_t q1 = NULL; + MP_gethex(&q1, Q1024, res); + assert(res); + + res = isValidPublicKey(dh->pub_key, dh->p, q1); + if (!res) + { + MP_free(dh->pub_key); + MP_free(dh->priv_key); + dh->pub_key = dh->priv_key = 0; + } + + MP_free(q1); + } + return 1; +} + +// fill pubkey with the public key in BIG ENDIAN order +// 00 00 00 00 00 x1 x2 x3 ..... + +static int +DHGetPublicKey(MDH *dh, uint8_t *pubkey, size_t nPubkeyLen) +{ + if (!dh || !dh->pub_key) + return 0; + + int len = MP_bytes(dh->pub_key); + if (len <= 0 || len > (int) nPubkeyLen) + return 0; + + memset(pubkey, 0, nPubkeyLen); + MP_setbin(dh->pub_key, pubkey + (nPubkeyLen - len), len); + return 1; +} + +#if 0 /* unused */ +static int +DHGetPrivateKey(MDH *dh, uint8_t *privkey, size_t nPrivkeyLen) +{ + if (!dh || !dh->priv_key) + return 0; + + int len = MP_bytes(dh->priv_key); + if (len <= 0 || len > (int) nPrivkeyLen) + return 0; + + memset(privkey, 0, nPrivkeyLen); + MP_setbin(dh->priv_key, privkey + (nPrivkeyLen - len), len); + return 1; +} +#endif + +// computes the shared secret key from the private MDH value and the othe parties public key (pubkey) +static int +DHComputeSharedSecretKey(MDH *dh, uint8_t *pubkey, size_t nPubkeyLen, + uint8_t *secret) +{ + MP_t q1 = NULL, pubkeyBn = NULL; + size_t len; + int res; + + if (!dh || !secret || nPubkeyLen >= INT_MAX) + return -1; + + MP_getbin(pubkeyBn, pubkey, nPubkeyLen); + if (!pubkeyBn) + return -1; + + MP_gethex(&q1, Q1024, len); + assert(len); + + if (isValidPublicKey(pubkeyBn, dh->p, q1)) + res = MDH_compute_key(secret, nPubkeyLen, pubkeyBn, dh); + else + res = -1; + + MP_free(q1); + MP_free(pubkeyBn); + + return res; +} diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/handshake.h xbmc-trunk-28276/xbmc/lib/libRTMP/handshake.h --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/handshake.h 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/handshake.h 2010-04-04 22:58:14.592118845 +0100 @@ -0,0 +1,1050 @@ +/* + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * Copyright (C) 2010 2a665470ced7adb7156fcef47f8199a6371c117b8a79e399a2771e0b36384090 + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +/* This file is #included in rtmp.c, it is not meant to be compiled alone */ + +#ifdef USE_GNUTLS +#include +#ifndef SHA256_DIGEST_LENGTH +#define SHA256_DIGEST_LENGTH 32 +#endif +#define HMAC_CTX gcry_md_hd_t +#define HMAC_setup(ctx, key, len) gcry_md_open(&ctx, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC); gcry_md_setkey(ctx, key, len) +#define HMAC_crunch(ctx, buf, len) gcry_md_write(ctx, buf, len) +#define HMAC_finish(ctx, dig, dlen) dlen = SHA256_DIGEST_LENGTH; memcpy(dig, gcry_md_read(ctx, 0), dlen); gcry_md_close(ctx) + +typedef gcry_cipher_hd_t RC4_handle; +#define RC4_setup(h) gcry_cipher_open(h, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0) +#define RC4_setkey(h,l,k) gcry_cipher_setkey(h,k,l) +#define RC4_encrypt(h,l,d) gcry_cipher_encrypt(h,(void *)d,l,NULL,0) +#define RC4_encrypt2(h,l,s,d) gcry_cipher_encrypt(h,(void *)d,l,(void *)s,l) + +#else +#include +#include +#include +#define HMAC_setup(ctx, key, len) HMAC_CTX_init(&ctx); HMAC_Init_ex(&ctx, (unsigned char *)key, len, EVP_sha256(), 0) +#define HMAC_crunch(ctx, buf, len) HMAC_Update(&ctx, (unsigned char *)buf, len) +#define HMAC_finish(ctx, dig, dlen) HMAC_Final(&ctx, (unsigned char *)dig, &dlen); HMAC_CTX_cleanup(&ctx) + +typedef RC4_KEY * RC4_handle; +#define RC4_setup(h) *h = malloc(sizeof(RC4_KEY)) +#define RC4_setkey(h,l,k) RC4_set_key(h,l,k) +#define RC4_encrypt(h,l,d) RC4(h,l,(uint8_t *)d,(uint8_t *)d) +#define RC4_encrypt2(h,l,s,d) RC4(h,l,(uint8_t *)s,(uint8_t *)d) +#endif + +#define FP10 + +#include "dh.h" + +static const char GenuineFMSKey[] = { + 0x47, 0x65, 0x6e, 0x75, 0x69, 0x6e, 0x65, 0x20, 0x41, 0x64, 0x6f, 0x62, + 0x65, 0x20, 0x46, 0x6c, + 0x61, 0x73, 0x68, 0x20, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x20, 0x53, 0x65, + 0x72, 0x76, 0x65, 0x72, + 0x20, 0x30, 0x30, 0x31, /* Genuine Adobe Flash Media Server 001 */ + + 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 +}; /* 68 */ + +static const char GenuineFPKey[] = { + 0x47, 0x65, 0x6E, 0x75, 0x69, 0x6E, 0x65, 0x20, 0x41, 0x64, 0x6F, 0x62, + 0x65, 0x20, 0x46, 0x6C, + 0x61, 0x73, 0x68, 0x20, 0x50, 0x6C, 0x61, 0x79, 0x65, 0x72, 0x20, 0x30, + 0x30, 0x31, /* Genuine Adobe Flash Player 001 */ + 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 +}; /* 62 */ + +static void InitRC4Encryption + (uint8_t * secretKey, + uint8_t * pubKeyIn, + uint8_t * pubKeyOut, RC4_handle *rc4keyIn, RC4_handle *rc4keyOut) +{ + uint8_t digest[SHA256_DIGEST_LENGTH]; + unsigned int digestLen = 0; + HMAC_CTX ctx; + + RC4_setup(rc4keyIn); + RC4_setup(rc4keyOut); + + HMAC_setup(ctx, secretKey, 128); + HMAC_crunch(ctx, pubKeyIn, 128); + HMAC_finish(ctx, digest, digestLen); + + RTMP_Log(RTMP_LOGDEBUG, "RC4 Out Key: "); + RTMP_LogHex(RTMP_LOGDEBUG, (char *) digest, 16); + + RC4_setkey(*rc4keyOut, 16, digest); + + HMAC_setup(ctx, secretKey, 128); + HMAC_crunch(ctx, pubKeyOut, 128); + HMAC_finish(ctx, digest, digestLen); + + RTMP_Log(RTMP_LOGDEBUG, "RC4 In Key: "); + RTMP_LogHex(RTMP_LOGDEBUG, (char *) digest, 16); + + RC4_setkey(*rc4keyIn, 16, digest); +} + +typedef unsigned int (getoff)(char *buf, unsigned int len); + +static unsigned int +GetDHOffset2(char *handshake, unsigned int len) +{ + unsigned int offset = 0; + unsigned char *ptr = (unsigned char *) handshake + 768; + + assert(RTMP_SIG_SIZE <= len); + + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + + unsigned int res = (offset % 632) + 8; + + if (res + 128 > 767) + { + RTMP_Log(RTMP_LOGERROR, + "%s: Couldn't calculate correct DH offset (got %d), exiting!\n", + __FUNCTION__, res); + exit(1); + } + return res; +} + +static unsigned int +GetDigestOffset2(char *handshake, unsigned int len) +{ + unsigned int offset = 0; + unsigned char *ptr = (unsigned char *) handshake + 772; + + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + + unsigned int res = (offset % 728) + 776; + + if (res + 32 > 1535) + { + RTMP_Log(RTMP_LOGERROR, + "%s: Couldn't calculate correct digest offset (got %d), exiting\n", + __FUNCTION__, res); + exit(1); + } + return res; +} + +static unsigned int +GetDHOffset1(char *handshake, unsigned int len) +{ + unsigned int offset = 0; + unsigned char *ptr = (unsigned char *) handshake + 1532; + + assert(RTMP_SIG_SIZE <= len); + + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + + unsigned int res = (offset % 632) + 772; + + if (res + 128 > 1531) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't calculate DH offset (got %d), exiting!\n", + __FUNCTION__, res); + exit(1); + } + + return res; +} + +static unsigned int +GetDigestOffset1(char *handshake, unsigned int len) +{ + unsigned int offset = 0; + unsigned char *ptr = (unsigned char *) handshake + 8; + + assert(12 <= len); + + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + + unsigned int res = (offset % 728) + 12; + + if (res + 32 > 771) + { + RTMP_Log(RTMP_LOGDEBUG, + "%s: Couldn't calculate digest offset (got %d), exiting!\n", + __FUNCTION__, res); + exit(1); + } + + return res; +} + +static void +HMACsha256(const char *message, size_t messageLen, const char *key, + size_t keylen, char *digest) +{ + unsigned int digestLen; + HMAC_CTX ctx; + + HMAC_setup(ctx, key, keylen); + HMAC_crunch(ctx, message, messageLen); + HMAC_finish(ctx, digest, digestLen); + + assert(digestLen == 32); +} + +static void +CalculateDigest(unsigned int digestPos, char *handshakeMessage, + const char *key, size_t keyLen, char *digest) +{ + const int messageLen = RTMP_SIG_SIZE - SHA256_DIGEST_LENGTH; + char message[messageLen]; + + memcpy(message, handshakeMessage, digestPos); + memcpy(message + digestPos, + &handshakeMessage[digestPos + SHA256_DIGEST_LENGTH], + messageLen - digestPos); + + HMACsha256(message, messageLen, key, keyLen, digest); +} + +static bool +VerifyDigest(unsigned int digestPos, char *handshakeMessage, const char *key, + size_t keyLen) +{ + char calcDigest[SHA256_DIGEST_LENGTH]; + + CalculateDigest(digestPos, handshakeMessage, key, keyLen, calcDigest); + + return memcmp(&handshakeMessage[digestPos], calcDigest, + SHA256_DIGEST_LENGTH) == 0; +} + +/* handshake + * + * Type = [1 bytes] plain: 0x03, encrypted: 0x06, 0x08, 0x09 + * -------------------------------------------------------------------- [1536 bytes] + * Uptime = [4 bytes] big endian unsigned number, uptime + * Version = [4 bytes] each byte represents a version number, e.g. 9.0.124.0 + * ... + * + */ + +static const uint32_t rtmpe8_keys[16][4] = { + {0xbff034b2, 0x11d9081f, 0xccdfb795, 0x748de732}, + {0x086a5eb6, 0x1743090e, 0x6ef05ab8, 0xfe5a39e2}, + {0x7b10956f, 0x76ce0521, 0x2388a73a, 0x440149a1}, + {0xa943f317, 0xebf11bb2, 0xa691a5ee, 0x17f36339}, + {0x7a30e00a, 0xb529e22c, 0xa087aea5, 0xc0cb79ac}, + {0xbdce0c23, 0x2febdeff, 0x1cfaae16, 0x1123239d}, + {0x55dd3f7b, 0x77e7e62e, 0x9bb8c499, 0xc9481ee4}, + {0x407bb6b4, 0x71e89136, 0xa7aebf55, 0xca33b839}, + {0xfcf6bdc3, 0xb63c3697, 0x7ce4f825, 0x04d959b2}, + {0x28e091fd, 0x41954c4c, 0x7fb7db00, 0xe3a066f8}, + {0x57845b76, 0x4f251b03, 0x46d45bcd, 0xa2c30d29}, + {0x0acceef8, 0xda55b546, 0x03473452, 0x5863713b}, + {0xb82075dc, 0xa75f1fee, 0xd84268e8, 0xa72a44cc}, + {0x07cf6e9e, 0xa16d7b25, 0x9fa7ae6c, 0xd92f5629}, + {0xfeb1eae4, 0x8c8c3ce1, 0x4e0064a7, 0x6a387c2a}, + {0x893a9427, 0xcc3013a2, 0xf106385b, 0xa829f927} +}; + +/* RTMPE type 8 uses XTEA on the regular signature + * http://en.wikipedia.org/wiki/XTEA + */ +static void rtmpe8_sig(unsigned char *in, unsigned char *out, int keyid) +{ + unsigned int i, num_rounds = 32; + uint32_t v0, v1, sum=0, delta=0x9E3779B9; + uint32_t const *k; + + v0 = in[0] | (in[1] << 8) | (in[2] << 16) | (in[3] << 24); + v1 = in[4] | (in[5] << 8) | (in[6] << 16) | (in[7] << 24); + k = rtmpe8_keys[keyid]; + + for (i=0; i < num_rounds; i++) { + v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]); + sum += delta; + v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]); + } + + out[0] = v0; v0 >>= 8; + out[1] = v0; v0 >>= 8; + out[2] = v0; v0 >>= 8; + out[3] = v0; + + out[4] = v1; v1 >>= 8; + out[5] = v1; v1 >>= 8; + out[6] = v1; v1 >>= 8; + out[7] = v1; +} + +static bool +HandShake(RTMP * r, bool FP9HandShake) +{ + int i; + int dhposClient = 0; + int digestPosClient = 0; + bool encrypted = r->Link.protocol & RTMP_FEATURE_ENC; + + RC4_handle keyIn = 0; + RC4_handle keyOut = 0; + + int32_t *ip; + uint32_t uptime; + + char clientbuf[RTMP_SIG_SIZE + 4], *clientsig=clientbuf+4; + char serversig[RTMP_SIG_SIZE], client2[RTMP_SIG_SIZE], *reply; + char type; + getoff *getdh, *getdig; + + if (encrypted || r->Link.SWFSize) + FP9HandShake = true; + else + FP9HandShake = false; + + r->Link.rc4keyIn = r->Link.rc4keyOut = 0; + + if (encrypted) + clientsig[-1] = 0x06; /* 0x08 is RTMPE as well */ + else + clientsig[-1] = 0x03; + + uptime = htonl(RTMP_GetTime()); + memcpy(clientsig, &uptime, 4); + + if (FP9HandShake) + { + /* set version to at least 9.0.115.0 */ +#ifdef FP10 + getdig = GetDigestOffset2; + getdh = GetDHOffset2; + + clientsig[4] = 128; + clientsig[6] = 3; +#else + getdig = GetDigestOffset1; + getdh = GetDHOffset1; + + clientsig[4] = 9; + clientsig[6] = 124; +#endif + clientsig[5] = 0; + clientsig[7] = 2; + + RTMP_Log(RTMP_LOGDEBUG, "%s: Client type: %02X\n", __FUNCTION__, clientsig[-1]); + } + else + { + memset(&clientsig[4], 0, 4); + } + + /* generate random data */ +#ifdef _DEBUG + memset(clientsig+8, 0, RTMP_SIG_SIZE-8); +#else + ip = (int32_t *)(clientsig+8); + for (i = 2; i < RTMP_SIG_SIZE/4; i++) + *ip++ = rand(); +#endif + + /* set handshake digest */ + if (FP9HandShake) + { + if (encrypted) + { + /* generate Diffie-Hellmann parameters */ + r->Link.dh = DHInit(128); /* 1024 */ + if (!r->Link.dh) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't initialize Diffie-Hellmann!", + __FUNCTION__); + return false; + } + + dhposClient = getdh(clientsig, RTMP_SIG_SIZE); + RTMP_Log(RTMP_LOGDEBUG, "%s: DH pubkey position: %d", __FUNCTION__, dhposClient); + + if (!DHGenerateKey(r->Link.dh)) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't generate Diffie-Hellmann public key!", + __FUNCTION__); + return false; + } + + if (!DHGetPublicKey + (r->Link.dh, (uint8_t *) &clientsig[dhposClient], 128)) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't write public key!", __FUNCTION__); + return false; + } + } + + digestPosClient = getdig(clientsig, RTMP_SIG_SIZE); /* reuse this value in verification */ + RTMP_Log(RTMP_LOGDEBUG, "%s: Client digest offset: %d", __FUNCTION__, + digestPosClient); + + CalculateDigest(digestPosClient, clientsig, GenuineFPKey, 30, + &clientsig[digestPosClient]); + + RTMP_Log(RTMP_LOGDEBUG, "%s: Initial client digest: ", __FUNCTION__); + RTMP_LogHex(RTMP_LOGDEBUG, (char *) clientsig + digestPosClient, + SHA256_DIGEST_LENGTH); + } + +#ifdef _DEBUG + RTMP_Log(RTMP_LOGDEBUG, "Clientsig: "); + RTMP_LogHex(RTMP_LOGDEBUG, clientsig, RTMP_SIG_SIZE); +#endif + + if (!WriteN(r, clientsig-1, RTMP_SIG_SIZE + 1)) + return false; + + if (ReadN(r, &type, 1) != 1) /* 0x03 or 0x06 */ + return false; + + RTMP_Log(RTMP_LOGDEBUG, "%s: Type Answer : %02X", __FUNCTION__, type); + + if (type != clientsig[-1]) + RTMP_Log(RTMP_LOGWARNING, "%s: Type mismatch: client sent %d, server answered %d", + __FUNCTION__, clientsig[-1], type); + + if (ReadN(r, serversig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) + return false; + + /* decode server response */ + memcpy(&uptime, serversig, 4); + uptime = ntohl(uptime); + + RTMP_Log(RTMP_LOGDEBUG, "%s: Server Uptime : %d", __FUNCTION__, uptime); + RTMP_Log(RTMP_LOGDEBUG, "%s: FMS Version : %d.%d.%d.%d", __FUNCTION__, serversig[4], + serversig[5], serversig[6], serversig[7]); + + if (FP9HandShake && type == 3 && !serversig[4]) + FP9HandShake = false; + +#ifdef _DEBUG + RTMP_Log(RTMP_LOGDEBUG, "Server signature:"); + RTMP_LogHex(RTMP_LOGDEBUG, serversig, RTMP_SIG_SIZE); +#endif + + if (FP9HandShake) + { + int dhposServer; + + /* we have to use this signature now to find the correct algorithms for getting the digest and DH positions */ + int digestPosServer = GetDigestOffset2(serversig, RTMP_SIG_SIZE); + + if (!VerifyDigest(digestPosServer, serversig, GenuineFMSKey, 36)) + { + RTMP_Log(RTMP_LOGWARNING, "Trying different position for server digest!\n"); + digestPosServer = GetDigestOffset1(serversig, RTMP_SIG_SIZE); + + if (!VerifyDigest(digestPosServer, serversig, GenuineFMSKey, 36)) + { + RTMP_Log(RTMP_LOGERROR, "Couldn't verify the server digest\n"); /* continuing anyway will probably fail */ + return false; + } + dhposServer = GetDHOffset1(serversig, RTMP_SIG_SIZE); + } + else + { + dhposServer = GetDHOffset2(serversig, RTMP_SIG_SIZE); + } + + RTMP_Log(RTMP_LOGDEBUG, "%s: Server DH public key offset: %d", __FUNCTION__, + dhposServer); + + /* generate SWFVerification token (SHA256 HMAC hash of decompressed SWF, key are the last 32 bytes of the server handshake) */ + if (r->Link.SWFSize) + { + const char swfVerify[] = { 0x01, 0x01 }; + char *vend = r->Link.SWFVerificationResponse+sizeof(r->Link.SWFVerificationResponse); + + memcpy(r->Link.SWFVerificationResponse, swfVerify, 2); + AMF_EncodeInt32(&r->Link.SWFVerificationResponse[2], vend, r->Link.SWFSize); + AMF_EncodeInt32(&r->Link.SWFVerificationResponse[6], vend, r->Link.SWFSize); + HMACsha256(r->Link.SWFHash, SHA256_DIGEST_LENGTH, + &serversig[RTMP_SIG_SIZE - SHA256_DIGEST_LENGTH], + SHA256_DIGEST_LENGTH, &r->Link.SWFVerificationResponse[10]); + } + + /* do Diffie-Hellmann Key exchange for encrypted RTMP */ + if (encrypted) + { + /* compute secret key */ + uint8_t secretKey[128] = { 0 }; + + int len = + DHComputeSharedSecretKey(r->Link.dh, + (uint8_t *) & serversig[dhposServer], 128, + secretKey); + if (len < 0) + { + RTMP_Log(RTMP_LOGDEBUG, "%s: Wrong secret key position!", __FUNCTION__); + return false; + } + + RTMP_Log(RTMP_LOGDEBUG, "%s: Secret key: ", __FUNCTION__); + RTMP_LogHex(RTMP_LOGDEBUG, (char *) secretKey, 128); + + InitRC4Encryption(secretKey, + (uint8_t *) & serversig[dhposServer], + (uint8_t *) & clientsig[dhposClient], + &keyIn, &keyOut); + } + + + reply = client2; +#ifdef _DEBUG + memset(reply, 0xff, RTMP_SIG_SIZE); +#else + ip = (int32_t *)reply; + for (i = 0; i < RTMP_SIG_SIZE/4; i++) + *ip++ = rand(); +#endif + /* calculate response now */ + char digestResp[SHA256_DIGEST_LENGTH]; + char *signatureResp = reply+RTMP_SIG_SIZE-SHA256_DIGEST_LENGTH; + + HMACsha256(&serversig[digestPosServer], SHA256_DIGEST_LENGTH, + GenuineFPKey, sizeof(GenuineFPKey), digestResp); + HMACsha256(reply, RTMP_SIG_SIZE - SHA256_DIGEST_LENGTH, digestResp, + SHA256_DIGEST_LENGTH, signatureResp); + + /* some info output */ + RTMP_Log(RTMP_LOGDEBUG, + "%s: Calculated digest key from secure key and server digest: ", + __FUNCTION__); + RTMP_LogHex(RTMP_LOGDEBUG, digestResp, SHA256_DIGEST_LENGTH); + +#ifdef FP10 + if (type == 8 ) + { + unsigned char *dptr = (unsigned char *)digestResp; + unsigned char *sig = (unsigned char *)signatureResp; + /* encrypt signatureResp */ + for (i=0; iLink.rc4keyIn = keyIn; + r->Link.rc4keyOut = keyOut; + + char buff[RTMP_SIG_SIZE]; + + /* update the keystreams */ + if (r->Link.rc4keyIn) + { + RC4_encrypt(r->Link.rc4keyIn, RTMP_SIG_SIZE, (uint8_t *) buff); + } + + if (r->Link.rc4keyOut) + { + RC4_encrypt(r->Link.rc4keyOut, RTMP_SIG_SIZE, (uint8_t *) buff); + } + } + } + else + { + if (memcmp(serversig, clientsig, RTMP_SIG_SIZE) != 0) + { + RTMP_Log(RTMP_LOGWARNING, "%s: client signature does not match!", + __FUNCTION__); + } + } + + RTMP_Log(RTMP_LOGDEBUG, "%s: Handshaking finished....", __FUNCTION__); + return true; +} + +static bool +SHandShake(RTMP * r) +{ + int i; + int dhposClient = 0; + int dhposServer = 0; + int digestPosServer = 0; + RC4_handle keyIn = 0; + RC4_handle keyOut = 0; + bool FP9HandShake = false; + bool encrypted; + int32_t *ip; + + char clientsig[RTMP_SIG_SIZE]; + char serverbuf[RTMP_SIG_SIZE + 4], *serversig = serverbuf+4; + char type; + uint32_t uptime; + + if (ReadN(r, &type, 1) != 1) /* 0x03 or 0x06 */ + return false; + + if (ReadN(r, clientsig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) + return false; + + RTMP_Log(RTMP_LOGDEBUG, "%s: Type Requested : %02X", __FUNCTION__, type); + RTMP_LogHex(RTMP_LOGDEBUG2, clientsig, RTMP_SIG_SIZE); + + if (type == 3) + { + encrypted = false; + } + else if (type == 6 || type == 8) + { + encrypted = true; + FP9HandShake = true; + r->Link.protocol |= RTMP_FEATURE_ENC; + /* use FP10 if client is capable */ + if (clientsig[4] == 128 || clientsig[4] == -128) + type = 8; + } + else + { + RTMP_Log(RTMP_LOGERROR, "%s: Unknown version %02x", + __FUNCTION__, type); + return false; + } + + serversig[-1] = type; + + r->Link.rc4keyIn = r->Link.rc4keyOut = 0; + + uptime = htonl(RTMP_GetTime()); + memcpy(serversig, &uptime, 4); + + if (FP9HandShake) + { + /* Server version */ + serversig[4] = 3; + serversig[5] = 5; + serversig[6] = 1; + serversig[7] = 1; + } + else + { + memset(&serversig[4], 0, 4); + } + + /* generate random data */ +#ifdef _DEBUG + memset(serversig+8, 0, RTMP_SIG_SIZE-8); +#else + ip = (int32_t *)(serversig+8); + for (i = 2; i < RTMP_SIG_SIZE/4; i++) + *ip++ = rand(); +#endif + + /* set handshake digest */ + if (FP9HandShake) + { + if (encrypted) + { + /* generate Diffie-Hellmann parameters */ + r->Link.dh = DHInit(128); + if (!r->Link.dh) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't initialize Diffie-Hellmann!", + __FUNCTION__); + return false; + } + + dhposServer = GetDHOffset2(serversig, RTMP_SIG_SIZE); + RTMP_Log(RTMP_LOGDEBUG, "%s: DH pubkey position: %d", __FUNCTION__, dhposServer); + + if (!DHGenerateKey(r->Link.dh)) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't generate Diffie-Hellmann public key!", + __FUNCTION__); + return false; + } + + if (!DHGetPublicKey + (r->Link.dh, (uint8_t *) &serversig[dhposServer], 128)) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't write public key!", __FUNCTION__); + return false; + } + } + + digestPosServer = GetDigestOffset2(serversig, RTMP_SIG_SIZE); /* reuse this value in verification */ + RTMP_Log(RTMP_LOGDEBUG, "%s: Client digest offset: %d", __FUNCTION__, + digestPosServer); + + CalculateDigest(digestPosServer, serversig, GenuineFMSKey, 36, + &serversig[digestPosServer]); + + RTMP_Log(RTMP_LOGDEBUG, "%s: Initial server digest: ", __FUNCTION__); + RTMP_LogHex(RTMP_LOGDEBUG, (char *) serversig + digestPosServer, + SHA256_DIGEST_LENGTH); + } + + RTMP_Log(RTMP_LOGDEBUG2, "Serversig: "); + RTMP_LogHex(RTMP_LOGDEBUG2, serversig, RTMP_SIG_SIZE); + + if (!WriteN(r, serversig-1, RTMP_SIG_SIZE + 1)) + return false; + + /* decode client response */ + memcpy(&uptime, clientsig, 4); + uptime = ntohl(uptime); + + RTMP_Log(RTMP_LOGDEBUG, "%s: Client Uptime : %d", __FUNCTION__, uptime); + RTMP_Log(RTMP_LOGDEBUG, "%s: Player Version: %d.%d.%d.%d", __FUNCTION__, clientsig[4], + clientsig[5], clientsig[6], clientsig[7]); + + if (FP9HandShake) + { + /* we have to use this signature now to find the correct algorithms for getting the digest and DH positions */ + int digestPosClient = GetDigestOffset1(clientsig, RTMP_SIG_SIZE); + + if (!VerifyDigest(digestPosClient, clientsig, GenuineFPKey, 30)) + { + RTMP_Log(RTMP_LOGWARNING, "Trying different position for client digest!\n"); + digestPosClient = GetDigestOffset2(clientsig, RTMP_SIG_SIZE); + + if (!VerifyDigest(digestPosClient, clientsig, GenuineFPKey, 30)) + { + RTMP_Log(RTMP_LOGERROR, "Couldn't verify the client digest\n"); /* continuing anyway will probably fail */ + return false; + } + dhposClient = GetDHOffset2(clientsig, RTMP_SIG_SIZE); + } + else + { + dhposClient = GetDHOffset1(clientsig, RTMP_SIG_SIZE); + } + + RTMP_Log(RTMP_LOGDEBUG, "%s: Client DH public key offset: %d", __FUNCTION__, + dhposClient); + + /* generate SWFVerification token (SHA256 HMAC hash of decompressed SWF, key are the last 32 bytes of the server handshake) */ + if (r->Link.SWFSize) + { + const char swfVerify[] = { 0x01, 0x01 }; + char *vend = r->Link.SWFVerificationResponse+sizeof(r->Link.SWFVerificationResponse); + + memcpy(r->Link.SWFVerificationResponse, swfVerify, 2); + AMF_EncodeInt32(&r->Link.SWFVerificationResponse[2], vend, r->Link.SWFSize); + AMF_EncodeInt32(&r->Link.SWFVerificationResponse[6], vend, r->Link.SWFSize); + HMACsha256(r->Link.SWFHash, SHA256_DIGEST_LENGTH, + &serversig[RTMP_SIG_SIZE - SHA256_DIGEST_LENGTH], + SHA256_DIGEST_LENGTH, &r->Link.SWFVerificationResponse[10]); + } + + /* do Diffie-Hellmann Key exchange for encrypted RTMP */ + if (encrypted) + { + /* compute secret key */ + uint8_t secretKey[128] = { 0 }; + + int len = + DHComputeSharedSecretKey(r->Link.dh, + (uint8_t *) &clientsig[dhposClient], 128, + secretKey); + if (len < 0) + { + RTMP_Log(RTMP_LOGDEBUG, "%s: Wrong secret key position!", __FUNCTION__); + return false; + } + + RTMP_Log(RTMP_LOGDEBUG, "%s: Secret key: ", __FUNCTION__); + RTMP_LogHex(RTMP_LOGDEBUG, (char *) secretKey, 128); + + InitRC4Encryption(secretKey, + (uint8_t *) &clientsig[dhposClient], + (uint8_t *) &serversig[dhposServer], + &keyIn, &keyOut); + } + + + /* calculate response now */ + char digestResp[SHA256_DIGEST_LENGTH]; + char *signatureResp = clientsig+RTMP_SIG_SIZE-SHA256_DIGEST_LENGTH; + + HMACsha256(&clientsig[digestPosClient], SHA256_DIGEST_LENGTH, + GenuineFMSKey, sizeof(GenuineFMSKey), digestResp); + HMACsha256(clientsig, RTMP_SIG_SIZE - SHA256_DIGEST_LENGTH, digestResp, + SHA256_DIGEST_LENGTH, signatureResp); +#ifdef FP10 + if (type == 8 ) + { + unsigned char *dptr = (unsigned char *)digestResp; + unsigned char *sig = (unsigned char *)signatureResp; + /* encrypt signatureResp */ + for (i=0; iLink.rc4keyIn = keyIn; + r->Link.rc4keyOut = keyOut; + + char buff[RTMP_SIG_SIZE]; + + /* update the keystreams */ + if (r->Link.rc4keyIn) + { + RC4_encrypt(r->Link.rc4keyIn, RTMP_SIG_SIZE, (uint8_t *) buff); + } + + if (r->Link.rc4keyOut) + { + RC4_encrypt(r->Link.rc4keyOut, RTMP_SIG_SIZE, (uint8_t *) buff); + } + } + } + else + { + if (memcmp(serversig, clientsig, RTMP_SIG_SIZE) != 0) + { + RTMP_Log(RTMP_LOGWARNING, "%s: client signature does not match!", + __FUNCTION__); + } + } + + RTMP_Log(RTMP_LOGDEBUG, "%s: Handshaking finished....", __FUNCTION__); + return true; +} diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/hashswf.c xbmc-trunk-28276/xbmc/lib/libRTMP/hashswf.c --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/hashswf.c 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/hashswf.c 2010-04-04 22:58:14.382141953 +0100 @@ -0,0 +1,616 @@ +/* + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#include +#include +#include + +#include "rtmp_sys.h" +#include "log.h" +#include "http.h" + +#ifdef USE_GNUTLS +#include +#include +#ifndef SHA256_DIGEST_LENGTH +#define SHA256_DIGEST_LENGTH 32 +#endif +#define HMAC_CTX gcry_md_hd_t +#define HMAC_setup(ctx, key, len) gcry_md_open(&ctx, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC); gcry_md_setkey(ctx, key, len) +#define HMAC_crunch(ctx, buf, len) gcry_md_write(ctx, buf, len) +#define HMAC_finish(ctx, dig, dlen) dlen = SHA256_DIGEST_LENGTH; memcpy(dig, gcry_md_read(ctx, 0), dlen) +#define HMAC_close(ctx) gcry_md_close(ctx) +#else +#include +#include +#include +#include +#define HMAC_setup(ctx, key, len) HMAC_CTX_init(&ctx); HMAC_Init_ex(&ctx, (unsigned char *)key, len, EVP_sha256(), 0) +#define HMAC_crunch(ctx, buf, len) HMAC_Update(&ctx, (unsigned char *)buf, len) +#define HMAC_finish(ctx, dig, dlen) HMAC_Final(&ctx, (unsigned char *)dig, &dlen); +#define HMAC_close(ctx) HMAC_CTX_cleanup(&ctx) +#endif +#include + +struct info +{ + z_stream *zs; + HMAC_CTX ctx; + int first; + int zlib; + int size; +}; + +extern void RTMP_TLS_Init(); +extern TLS_CTX RTMP_TLS_ctx; + +#define CHUNK 16384 + +static size_t +swfcrunch(void *ptr, size_t size, size_t nmemb, void *stream) +{ + struct info *i = stream; + char *p = ptr; + size_t len = size * nmemb; + + if (i->first) + { + i->first = 0; + /* compressed? */ + if (!strncmp(p, "CWS", 3)) + { + *p = 'F'; + i->zlib = 1; + } + HMAC_crunch(i->ctx, (unsigned char *)p, 8); + p += 8; + len -= 8; + i->size = 8; + } + + if (i->zlib) + { + unsigned char out[CHUNK]; + i->zs->next_in = (unsigned char *)p; + i->zs->avail_in = len; + do + { + i->zs->avail_out = CHUNK; + i->zs->next_out = out; + inflate(i->zs, Z_NO_FLUSH); + len = CHUNK - i->zs->avail_out; + i->size += len; + HMAC_crunch(i->ctx, out, len); + } + while (i->zs->avail_out == 0); + } + else + { + i->size += len; + HMAC_crunch(i->ctx, (unsigned char *)p, len); + } + return size * nmemb; +} + +#define AGENT "Mozilla/5.0" + +HTTPResult +HTTP_get(struct HTTP_ctx *http, const char *url, HTTP_read_callback *cb) +{ + char *host, *path; + char *p1, *p2; + char hbuf[256]; + int port = 80; + int ssl = 0; + int hlen, flen = 0; + int rc, i; + int len_known; + HTTPResult ret = HTTPRES_OK; + struct sockaddr_in sa; + RTMPSockBuf sb = {0}; + + http->status = -1; + + memset(&sa, 0, sizeof(struct sockaddr_in)); + sa.sin_family = AF_INET; + + /* we only handle http here */ + if (strncasecmp(url, "http", 4)) + return HTTPRES_BAD_REQUEST; + + if (url[4] == 's') + { + ssl = 1; + port = 443; + if (!RTMP_TLS_ctx) + RTMP_TLS_Init(); + } + + p1 = strchr(url + 4, ':'); + if (!p1 || strncmp(p1, "://", 3)) + return HTTPRES_BAD_REQUEST; + + host = p1 + 3; + path = strchr(host, '/'); + hlen = path - host; + strncpy(hbuf, host, hlen); + hbuf[hlen] = '\0'; + host = hbuf; + p1 = strrchr(host, ':'); + if (p1) + { + *p1++ = '\0'; + port = atoi(p1); + } + + sa.sin_addr.s_addr = inet_addr(host); + if (sa.sin_addr.s_addr == INADDR_NONE) + { + struct hostent *hp = gethostbyname(host); + if (!hp || !hp->h_addr) + return HTTPRES_LOST_CONNECTION; + sa.sin_addr = *(struct in_addr *)hp->h_addr; + } + sa.sin_port = htons(port); + sb.sb_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (sb.sb_socket < 0) + return HTTPRES_LOST_CONNECTION; + i = + sprintf(sb.sb_buf, + "GET %s HTTP/1.0\r\nUser-Agent: %s\r\nHost: %s\r\nReferrer: %.*s\r\n", + path, AGENT, host, (int)(path - url + 1), url); + if (http->date[0]) + i += sprintf(sb.sb_buf + i, "If-Modified-Since: %s\r\n", http->date); + i += sprintf(sb.sb_buf + i, "\r\n"); + + if (connect + (sb.sb_socket, (struct sockaddr *)&sa, sizeof(struct sockaddr)) < 0) + { + ret = HTTPRES_LOST_CONNECTION; + goto leave; + } + if (ssl) + { + TLS_client(RTMP_TLS_ctx, sb.sb_ssl); + TLS_setfd(sb.sb_ssl, sb.sb_socket); + if ((i = TLS_connect(sb.sb_ssl)) < 0) + { + RTMP_Log(RTMP_LOGERROR, "%s, TLS_Connect failed", __FUNCTION__); + ret = HTTPRES_LOST_CONNECTION; + goto leave; + } + } + RTMPSockBuf_Send(&sb, sb.sb_buf, i); + + // set timeout +#define HTTP_TIMEOUT 5 + SET_RCVTIMEO(tv, HTTP_TIMEOUT); + if (setsockopt + (sb.sb_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv))) + { + RTMP_Log(RTMP_LOGERROR, "%s, Setting socket timeout to %ds failed!", + __FUNCTION__, HTTP_TIMEOUT); + } + + sb.sb_size = 0; + sb.sb_timedout = false; + if (RTMPSockBuf_Fill(&sb) < 1) + { + ret = HTTPRES_LOST_CONNECTION; + goto leave; + } + if (strncmp(sb.sb_buf, "HTTP/1", 6)) + { + ret = HTTPRES_BAD_REQUEST; + goto leave; + } + + p1 = strchr(sb.sb_buf, ' '); + rc = atoi(p1 + 1); + http->status = rc; + + if (rc >= 300) + { + if (rc == 304) + { + ret = HTTPRES_OK_NOT_MODIFIED; + goto leave; + } + else if (rc == 404) + ret = HTTPRES_NOT_FOUND; + else if (rc >= 500) + ret = HTTPRES_SERVER_ERROR; + else if (rc >= 400) + ret = HTTPRES_BAD_REQUEST; + else + ret = HTTPRES_REDIRECTED; + } + + p1 = memchr(sb.sb_buf, '\n', sb.sb_size); + if (!p1) + { + ret = HTTPRES_BAD_REQUEST; + goto leave; + } + sb.sb_start = p1 + 1; + sb.sb_size -= sb.sb_start - sb.sb_buf; + + while ((p2 = memchr(sb.sb_start, '\r', sb.sb_size))) + { + if (*sb.sb_start == '\r') + { + sb.sb_start += 2; + sb.sb_size -= 2; + break; + } + else + if (!strncasecmp + (sb.sb_start, "Content-Length: ", sizeof("Content-Length: ") - 1)) + { + flen = atoi(sb.sb_start + sizeof("Content-Length: ") - 1); + } + else + if (!strncasecmp + (sb.sb_start, "Last-Modified: ", sizeof("Last-Modified: ") - 1)) + { + *p2 = '\0'; + strcpy(http->date, sb.sb_start + sizeof("Last-Modified: ") - 1); + } + p2 += 2; + sb.sb_size -= p2 - sb.sb_start; + sb.sb_start = p2; + if (sb.sb_size < 1) + { + if (RTMPSockBuf_Fill(&sb) < 1) + { + ret = HTTPRES_LOST_CONNECTION; + goto leave; + } + } + } + + len_known = flen > 0; + while ((!len_known || flen > 0) && + (sb.sb_size > 0 || RTMPSockBuf_Fill(&sb) > 0)) + { + cb(sb.sb_start, 1, sb.sb_size, http->data); + if (len_known) + flen -= sb.sb_size; + http->size += sb.sb_size; + sb.sb_size = 0; + } + + if (flen > 0) + ret = HTTPRES_LOST_CONNECTION; + +leave: + RTMPSockBuf_Close(&sb); + return ret; +} + +static int tzoff; +static int tzchecked; + +#define JAN02_1980 318340800 + +static const char *monthtab[12] = { "Jan", "Feb", "Mar", + "Apr", "May", "Jun", + "Jul", "Aug", "Sep", + "Oct", "Nov", "Dec" +}; +static const char *days[] = + { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; + +/* Parse an HTTP datestamp into Unix time */ +static time_t +make_unix_time(char *s) +{ + struct tm time; + int i, ysub = 1900, fmt = 0; + char *month; + char *n; + time_t res; + + if (s[3] != ' ') + { + fmt = 1; + if (s[3] != ',') + ysub = 0; + } + for (n = s; *n; ++n) + if (*n == '-' || *n == ':') + *n = ' '; + + time.tm_mon = 0; + n = strchr(s, ' '); + if (fmt) + { + /* Day, DD-MMM-YYYY HH:MM:SS GMT */ + time.tm_mday = strtol(n + 1, &n, 0); + month = n + 1; + n = strchr(month, ' '); + time.tm_year = strtol(n + 1, &n, 0); + time.tm_hour = strtol(n + 1, &n, 0); + time.tm_min = strtol(n + 1, &n, 0); + time.tm_sec = strtol(n + 1, NULL, 0); + } + else + { + /* Unix ctime() format. Does not conform to HTTP spec. */ + /* Day MMM DD HH:MM:SS YYYY */ + month = n + 1; + n = strchr(month, ' '); + while (isspace(*n)) + n++; + time.tm_mday = strtol(n, &n, 0); + time.tm_hour = strtol(n + 1, &n, 0); + time.tm_min = strtol(n + 1, &n, 0); + time.tm_sec = strtol(n + 1, &n, 0); + time.tm_year = strtol(n + 1, NULL, 0); + } + if (time.tm_year > 100) + time.tm_year -= ysub; + + for (i = 0; i < 12; i++) + if (!strncasecmp(month, monthtab[i], 3)) + { + time.tm_mon = i; + break; + } + time.tm_isdst = 0; /* daylight saving is never in effect in GMT */ + + /* this is normally the value of extern int timezone, but some + * braindead C libraries don't provide it. + */ + if (!tzchecked) + { + struct tm *tc; + time_t then = JAN02_1980; + tc = localtime(&then); + tzoff = (12 - tc->tm_hour) * 3600 + tc->tm_min * 60 + tc->tm_sec; + tzchecked = 1; + } + res = mktime(&time); + /* Unfortunately, mktime() assumes the input is in local time, + * not GMT, so we have to correct it here. + */ + if (res != -1) + res += tzoff; + return res; +} + +/* Convert a Unix time to a network time string + * Weekday, DD-MMM-YYYY HH:MM:SS GMT + */ +void +strtime(time_t * t, char *s) +{ + struct tm *tm; + + tm = gmtime((time_t *) t); + sprintf(s, "%s, %02d %s %d %02d:%02d:%02d GMT", + days[tm->tm_wday], tm->tm_mday, monthtab[tm->tm_mon], + tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); +} + +#define HEX2BIN(a) (((a)&0x40)?((a)&0xf)+9:((a)&0xf)) + +int +RTMP_HashSWF(const char *url, unsigned int *size, unsigned char *hash, + int age) +{ + FILE *f = NULL; + char *path, date[64], cctim[64]; + long pos = 0; + time_t ctim = -1, cnow; + int i, got = 0, ret = 0; + unsigned int hlen; + struct info in = { 0 }; + struct HTTP_ctx http = { 0 }; + HTTPResult httpres; + z_stream zs = { 0 }; + AVal home, hpre; + + date[0] = '\0'; +#ifdef WIN32 + hpre.av_val = getenv("HOMEDRIVE"); + hpre.av_len = strlen(hpre.av_val); + home.av_val = getenv("HOMEPATH"); +#define DIRSEP "\\" +#else + hpre.av_val = ""; + hpre.av_len = 0; + home.av_val = getenv("HOME"); +#define DIRSEP "/" +#endif + if (!home.av_val) + home.av_val = "."; + home.av_len = strlen(home.av_val); + + /* SWF hash info is cached in a fixed-format file. + * url: + * ctim: HTTP datestamp of when we last checked it. + * date: HTTP datestamp of the SWF's last modification. + * size: SWF size in hex + * hash: SWF hash in hex + * + * These fields must be present in this order. All fields + * besides URL are fixed size. + */ + path = malloc(hpre.av_len + home.av_len + sizeof(DIRSEP ".swfinfo")); + sprintf(path, "%s%s" DIRSEP ".swfinfo", hpre.av_val, home.av_val); + + f = fopen(path, "r+"); + while (f) + { + char buf[4096], *file, *p; + + file = strchr(url, '/'); + if (!file) + break; + file += 2; + file = strchr(file, '/'); + if (!file) + break; + file++; + hlen = file - url; + p = strrchr(file, '/'); + if (p) + file = p; + else + file--; + + while (fgets(buf, sizeof(buf), f)) + { + char *r1; + + got = 0; + + if (strncmp(buf, "url: ", 5)) + continue; + if (strncmp(buf + 5, url, hlen)) + continue; + r1 = strrchr(buf, '/'); + i = strlen(r1); + r1[--i] = '\0'; + if (strncmp(r1, file, i)) + continue; + pos = ftell(f); + while (got < 4 && fgets(buf, sizeof(buf), f)) + { + if (!strncmp(buf, "size: ", 6)) + { + *size = strtol(buf + 6, NULL, 16); + got++; + } + else if (!strncmp(buf, "hash: ", 6)) + { + unsigned char *ptr = hash, *in = (unsigned char *)buf + 6; + int l = strlen((char *)in) - 1; + for (i = 0; i < l; i += 2) + *ptr++ = (HEX2BIN(in[i]) << 4) | HEX2BIN(in[i + 1]); + got++; + } + else if (!strncmp(buf, "date: ", 6)) + { + buf[strlen(buf) - 1] = '\0'; + strncpy(date, buf + 6, sizeof(date)); + got++; + } + else if (!strncmp(buf, "ctim: ", 6)) + { + buf[strlen(buf) - 1] = '\0'; + ctim = make_unix_time(buf + 6); + got++; + } + else if (!strncmp(buf, "url: ", 5)) + break; + } + break; + } + break; + } + + cnow = time(NULL); + /* If we got a cache time, see if it's young enough to use directly */ + if (age && ctim > 0) + { + ctim = cnow - ctim; + ctim /= 3600 * 24; /* seconds to days */ + if (ctim < age) /* ok, it's new enough */ + goto out; + } + + in.first = 1; + HMAC_setup(in.ctx, "Genuine Adobe Flash Player 001", 30); + inflateInit(&zs); + in.zs = &zs; + + http.date = date; + http.data = ∈ + + httpres = HTTP_get(&http, url, swfcrunch); + + inflateEnd(&zs); + + if (httpres != HTTPRES_OK && httpres != HTTPRES_OK_NOT_MODIFIED) + { + ret = -1; + if (httpres == HTTPRES_LOST_CONNECTION) + RTMP_Log(RTMP_LOGERROR, "%s: connection lost while downloading swfurl %s", + __FUNCTION__, url); + else if (httpres == HTTPRES_NOT_FOUND) + RTMP_Log(RTMP_LOGERROR, "%s: swfurl %s not found", __FUNCTION__, url); + else + RTMP_Log(RTMP_LOGERROR, "%s: couldn't contact swfurl %s (HTTP error %d)", + __FUNCTION__, url, http.status); + } + else + { + if (got && pos) + fseek(f, pos, SEEK_SET); + else + { + char *q; + if (!f) + f = fopen(path, "w"); + if (!f) + { + int err = errno; + RTMP_Log(RTMP_LOGERROR, + "%s: couldn't open %s for writing, errno %d (%s)", + __FUNCTION__, path, err, strerror(err)); + ret = -1; + goto out; + } + fseek(f, 0, SEEK_END); + q = strchr(url, '?'); + if (q) + i = q - url; + else + i = strlen(url); + + fprintf(f, "url: %.*s\n", i, url); + } + strtime(&cnow, cctim); + fprintf(f, "ctim: %s\n", cctim); + + if (!in.first) + { + HMAC_finish(in.ctx, hash, hlen); + *size = in.size; + + fprintf(f, "date: %s\n", date); + fprintf(f, "size: %08x\n", in.size); + fprintf(f, "hash: "); + for (i = 0; i < SHA256_DIGEST_LENGTH; i++) + fprintf(f, "%02x", hash[i]); + fprintf(f, "\n"); + } + } + HMAC_close(in.ctx); +out: + free(path); + if (f) + fclose(f); + return ret; +} diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/http.h xbmc-trunk-28276/xbmc/lib/libRTMP/http.h --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/http.h 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/http.h 2010-04-04 22:58:14.402147079 +0100 @@ -0,0 +1,46 @@ +#ifndef __RTMP_HTTP_H__ +#define __RTMP_HTTP_H__ +/* + * Copyright (C) 2010 Howard Chu + * Copyright (C) 2010 Antti Ajanki + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +typedef enum { + HTTPRES_OK, /* result OK */ + HTTPRES_OK_NOT_MODIFIED, /* not modified since last request */ + HTTPRES_NOT_FOUND, /* not found */ + HTTPRES_BAD_REQUEST, /* client error */ + HTTPRES_SERVER_ERROR, /* server reported an error */ + HTTPRES_REDIRECTED, /* resource has been moved */ + HTTPRES_LOST_CONNECTION, /* connection lost while waiting for data */ +} HTTPResult; + +struct HTTP_ctx { + char *date; + int size; + int status; + void *data; +}; + +typedef size_t (HTTP_read_callback)(void *ptr, size_t size, size_t nmemb, void *stream); + +HTTPResult HTTP_get(struct HTTP_ctx *http, const char *url, HTTP_read_callback *cb); + +#endif diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/log.c xbmc-trunk-28276/xbmc/lib/libRTMP/log.c --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/log.c 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/log.c 2010-04-04 22:58:14.482143418 +0100 @@ -0,0 +1,191 @@ +/* + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#include +#include +#include +#include + +#include "log.h" + +#define MAX_PRINT_LEN 2048 + +RTMP_LogLevel RTMP_debuglevel = RTMP_LOGERROR; + +static int neednl; + +static FILE *fmsg; + +static const char *levels[] = { + "CRIT", "ERROR", "WARNING", "INFO", + "DEBUG", "DEBUG2" +}; + +void RTMP_LogSetOutput(FILE *file) +{ + fmsg = file; +} + +void RTMP_LogSetLevel(RTMP_LogLevel level) +{ + RTMP_debuglevel = level; +} + +RTMP_LogLevel RTMP_LogGetLevel() +{ + return RTMP_debuglevel; +} + +void RTMP_LogPrintf(const char *format, ...) +{ + char str[MAX_PRINT_LEN]=""; + int len; + va_list args; + va_start(args, format); + len = vsnprintf(str, MAX_PRINT_LEN-1, format, args); + va_end(args); + + if ( RTMP_debuglevel==RTMP_LOGCRIT ) + return; + + if ( !fmsg ) fmsg = stderr; + + if (neednl) { + putc('\n', fmsg); + neednl = 0; + } + + if (len > MAX_PRINT_LEN-1) + len = MAX_PRINT_LEN-1; + fprintf(fmsg, "%s", str); + if (str[len-1] == '\n') + fflush(fmsg); +} + +void RTMP_LogStatus(const char *format, ...) +{ + char str[MAX_PRINT_LEN]=""; + va_list args; + va_start(args, format); + vsnprintf(str, MAX_PRINT_LEN-1, format, args); + va_end(args); + + if ( RTMP_debuglevel==RTMP_LOGCRIT ) + return; + + if ( !fmsg ) fmsg = stderr; + + fprintf(fmsg, "%s", str); + fflush(fmsg); + neednl = 1; +} + +void RTMP_Log(int level, const char *format, ...) +{ + char str[MAX_PRINT_LEN]=""; + va_list args; + va_start(args, format); + vsnprintf(str, MAX_PRINT_LEN-1, format, args); + va_end(args); + + // Filter out 'no-name' + if ( RTMP_debuglevel RTMP_debuglevel ) + return; + for(i=0; i RTMP_debuglevel ) + return; + + /* in case len is zero */ + line[0] = '\n'; + line[1] = '\0'; + + for ( i = 0 ; i < len ; i++ ) { + int n = i % 16; + unsigned off; + + if( !n ) { + if( i ) RTMP_LogPrintf( "%s", line ); + memset( line, ' ', sizeof(line)-2 ); + line[sizeof(line)-2] = '\n'; + line[sizeof(line)-1] = '\0'; + + off = i % 0x0ffffU; + + line[2] = hexdig[0x0f & (off >> 12)]; + line[3] = hexdig[0x0f & (off >> 8)]; + line[4] = hexdig[0x0f & (off >> 4)]; + line[5] = hexdig[0x0f & off]; + line[6] = ':'; + } + + off = BP_OFFSET + n*3 + ((n >= 8)?1:0); + line[off] = hexdig[0x0f & ( data[i] >> 4 )]; + line[off+1] = hexdig[0x0f & data[i]]; + + off = BP_GRAPH + n + ((n >= 8)?1:0); + + if ( isprint( (unsigned char) data[i] )) { + line[BP_GRAPH + n] = data[i]; + } else { + line[BP_GRAPH + n] = '.'; + } + } + + RTMP_LogPrintf( "%s", line ); +} diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/log.h xbmc-trunk-28276/xbmc/lib/libRTMP/log.h --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/log.h 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/log.h 2010-04-04 22:58:14.512144576 +0100 @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#ifndef __RTMP_LOG_H__ +#define __RTMP_LOG_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif +/* Enable this to get full debugging output */ +/* #define _DEBUG */ + +#ifdef _DEBUG +#undef NODEBUG +#endif + +typedef enum +{ RTMP_LOGCRIT=0, RTMP_LOGERROR, RTMP_LOGWARNING, RTMP_LOGINFO, + RTMP_LOGDEBUG, RTMP_LOGDEBUG2, RTMP_LOGALL +} RTMP_LogLevel; + +extern RTMP_LogLevel RTMP_debuglevel; + +void RTMP_LogSetOutput(FILE *file); +void RTMP_LogPrintf(const char *format, ...); +void RTMP_LogStatus(const char *format, ...); +void RTMP_Log(int level, const char *format, ...); +void RTMP_LogHex(int level, const char *data, unsigned long len); +void RTMP_LogHexString(int level, const char *data, unsigned long len); +void RTMP_LogSetLevel(RTMP_LogLevel lvl); +RTMP_LogLevel RTMP_LogGetLevel(void); + +#ifdef __cplusplus +} +#endif +#endif diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/Makefile xbmc-trunk-28276/xbmc/lib/libRTMP/Makefile --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/Makefile 2010-04-04 11:46:52.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/Makefile 2010-04-04 22:58:14.482143418 +0100 @@ -1,10 +1,46 @@ -INCLUDES=-I. -I../../ -I../../linux -I../../../guilib -I../../utils +VERSION=v2.2b -SRCS=rtmp.cpp \ - rtmppacket.cpp \ - AMFObject.cpp \ +prefix=/usr/local -LIB=librtmp.a +CC=$(CROSS_COMPILE)gcc +LD=$(CROSS_COMPILE)ld -include ../../../Makefile.include --include $(patsubst %.cpp,%.P,$(patsubst %.c,%.P,$(SRCS))) +CRYPTO=OPENSSL +#CRYPTO=GNUTLS +LIB_GNUTLS=-lgnutls +LIB_OPENSSL=-lssl -lcrypto +REQ_GNUTLS=gnutls +REQ_OPENSSL=libssl,libcrypto +CRYPTO_LIB=$(LIB_$(CRYPTO)) +CRYPTO_REQ=$(REQ_$(CRYPTO)) + +DEF=-DRTMPDUMP_VERSION=\"$(VERSION)\" -DUSE_$(CRYPTO) +OPT=-O2 +CFLAGS=-Wall $(XCFLAGS) $(INC) $(DEF) $(OPT) + +INCDIR=$(DESTDIR)$(prefix)/include/librtmp + +all: librtmp.a + +clean: + rm -f *.o *.a + +librtmp.a: rtmp.o log.o amf.o hashswf.o parseurl.o + $(AR) rs $@ $? + +log.o: log.c log.h Makefile +rtmp.o: rtmp.c rtmp.h rtmp_sys.h handshake.h dh.h log.h amf.h Makefile +amf.o: amf.c amf.h bytes.h log.h Makefile +hashswf.o: hashswf.c http.h rtmp.h rtmp_sys.h Makefile +parseurl.o: parseurl.c rtmp.h rtmp_sys.h log.h Makefile + +librtmp.pc: librtmp.pc.in Makefile + sed -e "s;@prefix@;$(prefix);" -e "s;@VERSION@;$(VERSION);" \ + -e "s;@CRYPTO_LIB@;$(CRYPTO_LIB);" -e "s;@CRYPTO_REQ@;$(CRYPTO_REQ);" \ + librtmp.pc.in > $@ + +install: librtmp.a librtmp.pc + -mkdir -p $(INCDIR) $(DESTDIR)$(prefix)/lib/pkgconfig + cp amf.h http.h log.h rtmp.h $(INCDIR) + cp librtmp.a $(DESTDIR)$(prefix)/lib + cp librtmp.pc $(DESTDIR)$(prefix)/lib/pkgconfig diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/parseurl.c xbmc-trunk-28276/xbmc/lib/libRTMP/parseurl.c --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/parseurl.c 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/parseurl.c 2010-04-04 22:58:14.482143418 +0100 @@ -0,0 +1,270 @@ +/* + * Copyright (C) 2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#include + +#include +#include + +#include "rtmp_sys.h" +#include "log.h" + +bool RTMP_ParseURL(const char *url, int *protocol, AVal *host, unsigned int *port, + AVal *playpath, AVal *app) +{ + char *p, *end, *col, *ques, *slash; + + RTMP_Log(RTMP_LOGDEBUG, "Parsing..."); + + *protocol = RTMP_PROTOCOL_RTMP; + *port = 0; + playpath->av_len = 0; + playpath->av_val = NULL; + app->av_len = 0; + app->av_val = NULL; + + // Old School Parsing + + // look for usual :// pattern + p = strstr(url, "://"); + if(!p) { + RTMP_Log(RTMP_LOGERROR, "RTMP URL: No :// in url!"); + return false; + } + { + int len = (int)(p-url); + + if(len == 4 && strncasecmp(url, "rtmp", 4)==0) + *protocol = RTMP_PROTOCOL_RTMP; + else if(len == 5 && strncasecmp(url, "rtmpt", 5)==0) + *protocol = RTMP_PROTOCOL_RTMPT; + else if(len == 5 && strncasecmp(url, "rtmps", 5)==0) + *protocol = RTMP_PROTOCOL_RTMPS; + else if(len == 5 && strncasecmp(url, "rtmpe", 5)==0) + *protocol = RTMP_PROTOCOL_RTMPE; + else if(len == 5 && strncasecmp(url, "rtmfp", 5)==0) + *protocol = RTMP_PROTOCOL_RTMFP; + else if(len == 6 && strncasecmp(url, "rtmpte", 6)==0) + *protocol = RTMP_PROTOCOL_RTMPTE; + else { + RTMP_Log(RTMP_LOGWARNING, "Unknown protocol!\n"); + goto parsehost; + } + } + + RTMP_Log(RTMP_LOGDEBUG, "Parsed protocol: %d", *protocol); + +parsehost: + // lets get the hostname + p+=3; + + // check for sudden death + if(*p==0) { + RTMP_Log(RTMP_LOGWARNING, "No hostname in URL!"); + return false; + } + + end = p + strlen(p); + col = strchr(p, ':'); + ques = strchr(p, '?'); + slash = strchr(p, '/'); + + { + int hostlen; + if(slash) + hostlen = slash - p; + else + hostlen = end - p; + if(col && col -p < hostlen) + hostlen = col - p; + + if(hostlen < 256) { + host->av_val = p; + host->av_len = hostlen; + RTMP_Log(RTMP_LOGDEBUG, "Parsed host : %.*s", hostlen, host->av_val); + } else { + RTMP_Log(RTMP_LOGWARNING, "Hostname exceeds 255 characters!"); + } + + p+=hostlen; + } + + // get the port number if available + if(*p == ':') { + p++; + unsigned int p2 = atoi(p); + if(p2 > 65535) { + RTMP_Log(RTMP_LOGWARNING, "Invalid port number!"); + } else { + *port = p2; + } + } + + if(!slash) { + RTMP_Log(RTMP_LOGWARNING, "No application or playpath in URL!"); + return true; + } + p = slash+1; + + { + // parse application + // + // rtmp://host[:port]/app[/appinstance][/...] + // application = app[/appinstance] + + char *slash2, *slash3 = NULL; + int applen, appnamelen; + + slash2 = strchr(p, '/'); + if(slash2) + slash3 = strchr(slash2+1, '/'); + + applen = end-p; // ondemand, pass all parameters as app + appnamelen = applen; // ondemand length + + if(ques && strstr(p, "slist=")) { // whatever it is, the '?' and slist= means we need to use everything as app and parse plapath from slist= + appnamelen = ques-p; + } + else if(strncmp(p, "ondemand/", 9)==0) { + // app = ondemand/foobar, only pass app=ondemand + applen = 8; + appnamelen = 8; + } + else { // app!=ondemand, so app is app[/appinstance] + if(slash3) + appnamelen = slash3-p; + else if(slash2) + appnamelen = slash2-p; + + applen = appnamelen; + } + + app->av_val = p; + app->av_len = applen; + RTMP_Log(RTMP_LOGDEBUG, "Parsed app : %.*s", applen, p); + + p += appnamelen; + } + + if (*p == '/') + p++; + + if (end-p) { + AVal av = {p, end-p}; + RTMP_ParsePlaypath(&av, playpath); + } + + return true; +} + +/* + * Extracts playpath from RTMP URL. playpath is the file part of the + * URL, i.e. the part that comes after rtmp://host:port/app/ + * + * Returns the stream name in a format understood by FMS. The name is + * the playpath part of the URL with formatting depending on the stream + * type: + * + * mp4 streams: prepend "mp4:", remove extension + * mp3 streams: prepend "mp3:", remove extension + * flv streams: remove extension + */ +void RTMP_ParsePlaypath(AVal *in, AVal *out) { + int addMP4 = 0; + int addMP3 = 0; + int subExt = 0; + const char *playpath = in->av_val; + const char *temp, *q, *ext = NULL; + const char *ppstart = playpath; + + int pplen = in->av_len; + + out->av_val = NULL; + out->av_len = 0; + + if ((*ppstart == '?') && + (temp=strstr(ppstart, "slist=")) != 0) { + ppstart = temp+6; + pplen = strlen(ppstart); + + temp = strchr(ppstart, '&'); + if (temp) { + pplen = temp-ppstart; + } + } + + q = strchr(ppstart, '?'); + if (pplen >= 4) { + if (q) + ext = q-4; + else + ext = &ppstart[pplen-4]; + if ((strncmp(ext, ".f4v", 4) == 0) || + (strncmp(ext, ".mp4", 4) == 0)) { + addMP4 = 1; + subExt = 1; + // Only remove .flv from rtmp URL, not slist params + } else if ((ppstart == playpath) && + (strncmp(ext, ".flv", 4) == 0)) { + subExt = 1; + } else if (strncmp(ext, ".mp3", 4) == 0) { + addMP3 = 1; + subExt = 1; + } + } + + char *streamname = (char *)malloc((pplen+4+1)*sizeof(char)); + if (!streamname) + return; + + char *destptr = streamname, *p; + if (addMP4 && (strncmp(ppstart, "mp4:", 4) != 0)) { + strcpy(destptr, "mp4:"); + destptr += 4; + } else if (addMP3 && (strncmp(ppstart, "mp3:", 4) != 0)) { + strcpy(destptr, "mp3:"); + destptr += 4; + } + + for (p=(char *)ppstart; pplen >0;) { + /* skip extension */ + if (subExt && p == ext) { + p += 4; + pplen -= 4; + } + if (*p == '%') { + int c; + sscanf(p+1, "%02x", &c); + *destptr++ = c; + pplen -= 3; + p += 3; + } else { + *destptr++ = *p++; + pplen--; + } + } + *destptr = '\0'; + + out->av_val = streamname; + out->av_len = destptr - streamname; +} diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/rtmp.c xbmc-trunk-28276/xbmc/lib/libRTMP/rtmp.c --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/rtmp.c 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/rtmp.c 2010-04-04 22:58:14.442139242 +0100 @@ -0,0 +1,4043 @@ +/* + * Copyright (C) 2005-2008 Team XBMC + * http://www.xbmc.org + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#include +#include +#include + +#include "rtmp_sys.h" +#include "log.h" + +#ifdef CRYPTO +#ifdef USE_GNUTLS +#include +#else +#include +#include +#endif +TLS_CTX RTMP_TLS_ctx; +#endif + +#define RTMP_SIG_SIZE 1536 +#define RTMP_LARGE_HEADER_SIZE 12 + +static const int packetSize[] = { 12, 8, 4, 1 }; + +bool RTMP_ctrlC; + +const char RTMPProtocolStrings[][7] = { + "RTMP", + "RTMPT", + "RTMPE", + "RTMPTE", + "", + "RTMPS", + "", + "", + "RTMFP" +}; + +const char RTMPProtocolStringsLower[][7] = { + "rtmp", + "rtmpt", + "rtmpe", + "rtmpte", + "", + "rtmps", + "", + "", + "rtmfp" +}; + +static const char *RTMPT_cmds[] = { + "open", + "send", + "idle", + "close" +}; + +typedef enum { + RTMPT_OPEN=0, RTMPT_SEND, RTMPT_IDLE, RTMPT_CLOSE +} RTMPTCmd; + +static bool DumpMetaData(AMFObject *obj); +static bool HandShake(RTMP *r, bool FP9HandShake); +static bool SocksNegotiate(RTMP *r); + +static bool SendConnectPacket(RTMP *r, RTMPPacket *cp); +static bool SendCheckBW(RTMP *r); +static bool SendCheckBWResult(RTMP *r, double txn); +static bool SendDeleteStream(RTMP *r, double dStreamId); +static bool SendFCSubscribe(RTMP *r, AVal *subscribepath); +static bool SendPlay(RTMP *r); +static bool SendBytesReceived(RTMP *r); + +#if 0 /* unused */ +static bool SendBGHasStream(RTMP *r, double dId, AVal *playpath); +#endif + +static int HandleInvoke(RTMP *r, const char *body, unsigned int nBodySize); +static bool HandleMetadata(RTMP *r, char *body, unsigned int len); +static void HandleChangeChunkSize(RTMP *r, const RTMPPacket *packet); +static void HandleAudio(RTMP *r, const RTMPPacket *packet); +static void HandleVideo(RTMP *r, const RTMPPacket *packet); +static void HandleCtrl(RTMP *r, const RTMPPacket *packet); +static void HandleServerBW(RTMP *r, const RTMPPacket *packet); +static void HandleClientBW(RTMP *r, const RTMPPacket *packet); + +static int ReadN(RTMP *r, char *buffer, int n); +static bool WriteN(RTMP *r, const char *buffer, int n); + +static void DecodeTEA(AVal *key, AVal *text); + +static int HTTP_Post(RTMP *r, RTMPTCmd cmd, const char *buf, int len); +static int HTTP_read(RTMP *r, int fill); + +#ifndef WIN32 +static int clk_tck; +#endif + +#ifdef CRYPTO +#include "handshake.h" +#endif + +uint32_t +RTMP_GetTime() +{ +#ifdef _DEBUG + return 0; +#elif defined(WIN32) + return timeGetTime(); +#else + struct tms t; + if (!clk_tck) clk_tck = sysconf(_SC_CLK_TCK); + return times(&t) * 1000 / clk_tck; +#endif +} + +void +RTMP_UserInterrupt() +{ + RTMP_ctrlC = true; +} + +void +RTMPPacket_Reset(RTMPPacket *p) +{ + p->m_headerType = 0; + p->m_packetType = 0; + p->m_nChannel = 0; + p->m_nTimeStamp = 0; + p->m_nInfoField2 = 0; + p->m_hasAbsTimestamp = false; + p->m_nBodySize = 0; + p->m_nBytesRead = 0; +} + +bool +RTMPPacket_Alloc(RTMPPacket *p, int nSize) +{ + char *ptr = calloc(1, nSize + RTMP_MAX_HEADER_SIZE); + if (!ptr) + return false; + p->m_body = ptr + RTMP_MAX_HEADER_SIZE; + p->m_nBytesRead = 0; + return true; +} + +void +RTMPPacket_Free(RTMPPacket *p) +{ + if (p->m_body) + { + free(p->m_body - RTMP_MAX_HEADER_SIZE); + p->m_body = NULL; + } +} + +void +RTMPPacket_Dump(RTMPPacket *p) +{ + RTMP_Log(RTMP_LOGDEBUG, + "RTMP PACKET: packet type: 0x%02x. channel: 0x%02x. info 1: %d info 2: %d. Body size: %lu. body: 0x%02x", + p->m_packetType, p->m_nChannel, p->m_nTimeStamp, p->m_nInfoField2, + p->m_nBodySize, p->m_body ? (unsigned char)p->m_body[0] : 0); +} + +int +RTMP_LibVersion() +{ + return RTMP_LIB_VERSION; +} + +void +RTMP_TLS_Init() +{ +#ifdef CRYPTO +#ifdef USE_GNUTLS + gnutls_global_init(); + RTMP_TLS_ctx = malloc(sizeof(struct tls_ctx)); + gnutls_certificate_allocate_credentials(&RTMP_TLS_ctx->cred); + gnutls_priority_init(&RTMP_TLS_ctx->prios, "NORMAL", NULL); + gnutls_certificate_set_x509_trust_file(RTMP_TLS_ctx->cred, + "ca.pem", GNUTLS_X509_FMT_PEM); +#else + SSL_load_error_strings(); + SSL_library_init(); + OpenSSL_add_all_digests(); + RTMP_TLS_ctx = SSL_CTX_new(SSLv23_method()); + SSL_CTX_set_options(RTMP_TLS_ctx, SSL_OP_ALL); + SSL_CTX_set_default_verify_paths(RTMP_TLS_ctx); +#endif +#endif +} + +void +RTMP_Init(RTMP *r) +{ +#ifdef CRYPTO + if (!RTMP_TLS_ctx) + RTMP_TLS_Init(); +#endif + + memset(r, 0, sizeof(RTMP)); + r->m_sb.sb_socket = -1; + r->m_inChunkSize = RTMP_DEFAULT_CHUNKSIZE; + r->m_outChunkSize = RTMP_DEFAULT_CHUNKSIZE; + r->m_nBufferMS = 30000; + r->m_nClientBW = 2500000; + r->m_nClientBW2 = 2; + r->m_nServerBW = 2500000; + r->m_fAudioCodecs = 3191.0; + r->m_fVideoCodecs = 252.0; + r->Link.timeout = 30; + r->Link.swfAge = 30; +} + +double +RTMP_GetDuration(RTMP *r) +{ + return r->m_fDuration; +} + +bool +RTMP_IsConnected(RTMP *r) +{ + return r->m_sb.sb_socket != -1; +} + +bool +RTMP_IsTimedout(RTMP *r) +{ + return r->m_sb.sb_timedout; +} + +void +RTMP_SetBufferMS(RTMP *r, int size) +{ + r->m_nBufferMS = size; +} + +void +RTMP_UpdateBufferMS(RTMP *r) +{ + RTMP_SendCtrl(r, 3, r->m_stream_id, r->m_nBufferMS); +} + +#undef OSS +#ifdef WIN32 +#define OSS "WIN" +#elif defined(__sun__) +#define OSS "SOL" +#elif defined(__APPLE__) +#define OSS "MAC" +#elif defined(__linux__) +#define OSS "LNX" +#else +#define OSS "GNU" +#endif +#define DEF_VERSTR OSS " 10,0,32,18" +static const char DEFAULT_FLASH_VER[] = DEF_VERSTR; +const AVal RTMP_DefaultFlashVer = + { (char *)DEFAULT_FLASH_VER, sizeof(DEFAULT_FLASH_VER) - 1 }; + +void +RTMP_SetupStream(RTMP *r, + int protocol, + AVal *host, + unsigned int port, + AVal *sockshost, + AVal *playpath, + AVal *tcUrl, + AVal *swfUrl, + AVal *pageUrl, + AVal *app, + AVal *auth, + AVal *swfSHA256Hash, + uint32_t swfSize, + AVal *flashVer, + AVal *subscribepath, + int dStart, + int dStop, bool bLiveStream, long int timeout) +{ + RTMP_Log(RTMP_LOGDEBUG, "Protocol : %s", RTMPProtocolStrings[protocol&7]); + RTMP_Log(RTMP_LOGDEBUG, "Hostname : %.*s", host->av_len, host->av_val); + RTMP_Log(RTMP_LOGDEBUG, "Port : %d", port); + RTMP_Log(RTMP_LOGDEBUG, "Playpath : %s", playpath->av_val); + + if (tcUrl && tcUrl->av_val) + RTMP_Log(RTMP_LOGDEBUG, "tcUrl : %s", tcUrl->av_val); + if (swfUrl && swfUrl->av_val) + RTMP_Log(RTMP_LOGDEBUG, "swfUrl : %s", swfUrl->av_val); + if (pageUrl && pageUrl->av_val) + RTMP_Log(RTMP_LOGDEBUG, "pageUrl : %s", pageUrl->av_val); + if (app && app->av_val) + RTMP_Log(RTMP_LOGDEBUG, "app : %.*s", app->av_len, app->av_val); + if (auth && auth->av_val) + RTMP_Log(RTMP_LOGDEBUG, "auth : %s", auth->av_val); + if (subscribepath && subscribepath->av_val) + RTMP_Log(RTMP_LOGDEBUG, "subscribepath : %s", subscribepath->av_val); + if (flashVer && flashVer->av_val) + RTMP_Log(RTMP_LOGDEBUG, "flashVer : %s", flashVer->av_val); + if (dStart > 0) + RTMP_Log(RTMP_LOGDEBUG, "StartTime : %d msec", dStart); + if (dStop > 0) + RTMP_Log(RTMP_LOGDEBUG, "StopTime : %d msec", dStop); + + RTMP_Log(RTMP_LOGDEBUG, "live : %s", bLiveStream ? "yes" : "no"); + RTMP_Log(RTMP_LOGDEBUG, "timeout : %d sec", timeout); + +#ifdef CRYPTO + if (swfSHA256Hash != NULL && swfSize > 0) + { + memcpy(r->Link.SWFHash, swfSHA256Hash->av_val, sizeof(r->Link.SWFHash)); + r->Link.SWFSize = swfSize; + RTMP_Log(RTMP_LOGDEBUG, "SWFSHA256:"); + RTMP_LogHex(RTMP_LOGDEBUG, r->Link.SWFHash, sizeof(r->Link.SWFHash)); + RTMP_Log(RTMP_LOGDEBUG, "SWFSize : %lu", r->Link.SWFSize); + } + else + { + r->Link.SWFSize = 0; + } +#endif + + if (sockshost->av_len) + { + const char *socksport = strchr(sockshost->av_val, ':'); + char *hostname = strdup(sockshost->av_val); + + if (socksport) + hostname[socksport - sockshost->av_val] = '\0'; + r->Link.sockshost.av_val = hostname; + r->Link.sockshost.av_len = strlen(hostname); + + r->Link.socksport = socksport ? atoi(socksport + 1) : 1080; + RTMP_Log(RTMP_LOGDEBUG, "Connecting via SOCKS proxy: %s:%d", r->Link.sockshost.av_val, + r->Link.socksport); + } + else + { + r->Link.sockshost.av_val = NULL; + r->Link.sockshost.av_len = 0; + r->Link.socksport = 0; + } + + if (tcUrl && tcUrl->av_len) + r->Link.tcUrl = *tcUrl; + if (swfUrl && swfUrl->av_len) + r->Link.swfUrl = *swfUrl; + if (pageUrl && pageUrl->av_len) + r->Link.pageUrl = *pageUrl; + if (app && app->av_len) + r->Link.app = *app; + if (auth && auth->av_len) + { + r->Link.auth = *auth; + r->Link.authflag = true; + } + if (flashVer && flashVer->av_len) + r->Link.flashVer = *flashVer; + else + r->Link.flashVer = RTMP_DefaultFlashVer; + if (subscribepath && subscribepath->av_len) + r->Link.subscribepath = *subscribepath; + r->Link.seekTime = dStart; + r->Link.stopTime = dStop; + r->Link.bLiveStream = bLiveStream; + r->Link.timeout = timeout; + + r->Link.protocol = protocol; + r->Link.hostname = *host; + r->Link.port = port; + r->Link.playpath = *playpath; + + if (r->Link.port == 0) + { + if (protocol & RTMP_FEATURE_SSL) + r->Link.port = 443; + else if (protocol & RTMP_FEATURE_HTTP) + r->Link.port = 80; + else + r->Link.port = 1935; + } +} + +enum { OPT_STR=0, OPT_INT, OPT_BOOL, OPT_CONN }; +static const char *optinfo[] = { + "string", "integer", "boolean", "AMF" }; + +#define OFF(x) offsetof(struct RTMP,x) + +static struct urlopt { + AVal name; + off_t off; + int otype; + char *use; +} options[] = { + { AVC("socks"), OFF(Link.sockshost), OPT_STR, + "Use the specified SOCKS proxy" }, + { AVC("app"), OFF(Link.app), OPT_STR, + "Name of target app on server" }, + { AVC("tcUrl"), OFF(Link.tcUrl), OPT_STR, + "URL to played stream" }, + { AVC("pageUrl"), OFF(Link.pageUrl), OPT_STR, + "URL of played media's web page" }, + { AVC("swfUrl"), OFF(Link.swfUrl), OPT_STR, + "URL to player SWF file" }, + { AVC("flashver"), OFF(Link.flashVer), OPT_STR, + "Flash version string (default " DEF_VERSTR ")" }, + { AVC("conn"), OFF(Link.extras), OPT_CONN, + "Append arbitrary AMF data to Connect message" }, + { AVC("playpath"), OFF(Link.playpath), OPT_STR, + "Path to target media on server" }, + { AVC("live"), OFF(Link.bLiveStream), OPT_BOOL, + "Stream is live, no seeking possible" }, + { AVC("subscribe"), OFF(Link.subscribepath), OPT_STR, + "Stream to subscribe to" }, + { AVC("token"), OFF(Link.token), OPT_STR, + "Key for SecureToken response" }, + { AVC("swfVfy"), OFF(Link.swfVfy), OPT_BOOL, + "Perform SWF Verification" }, + { AVC("swfAge"), OFF(Link.swfAge), OPT_INT, + "Number of days to use cached SWF hash" }, + { AVC("start"), OFF(Link.seekTime), OPT_INT, + "Stream start position in milliseconds" }, + { AVC("stop"), OFF(Link.stopTime), OPT_INT, + "Stream stop position in milliseconds" }, + { AVC("buffer"), OFF(m_nBufferMS), OPT_INT, + "Buffer time in milliseconds" }, + { AVC("timeout"), OFF(Link.timeout), OPT_INT, + "Session timeout in seconds" }, + { {NULL,0}, 0, 0} +}; + +static const AVal truth[] = { + AVC("1"), + AVC("on"), + AVC("yes"), + AVC("true"), + {0,0} +}; + +static void RTMP_OptUsage() +{ + int i; + + RTMP_LogPrintf("Valid RTMP options are:\n"); + for (i=0; options[i].name.av_len; i++) { + RTMP_LogPrintf("%10s %-7s %s\n", options[i].name.av_val, + optinfo[options[i].otype], options[i].use); + } +} + +static int +parseAMF(AMFObject *obj, AVal *av, int *depth) +{ + AMFObjectProperty prop = {{0,0}}; + int i; + char *p, *arg = av->av_val; + + if (arg[1] == ':') + { + p = (char *)arg+2; + switch(arg[0]) + { + case 'B': + prop.p_type = AMF_BOOLEAN; + prop.p_vu.p_number = atoi(p); + break; + case 'S': + prop.p_type = AMF_STRING; + prop.p_vu.p_aval.av_val = p; + prop.p_vu.p_aval.av_len = av->av_len - (p-arg); + break; + case 'N': + prop.p_type = AMF_NUMBER; + prop.p_vu.p_number = strtod(p, NULL); + break; + case 'Z': + prop.p_type = AMF_NULL; + break; + case 'O': + i = atoi(p); + if (i) + { + prop.p_type = AMF_OBJECT; + } + else + { + (*depth)--; + return 0; + } + break; + default: + return -1; + } + } + else if (arg[2] == ':' && arg[0] == 'N') + { + p = strchr(arg+3, ':'); + if (!p || !*depth) + return -1; + prop.p_name.av_val = (char *)arg+3; + prop.p_name.av_len = p - (arg+3); + + p++; + switch(arg[1]) + { + case 'B': + prop.p_type = AMF_BOOLEAN; + prop.p_vu.p_number = atoi(p); + break; + case 'S': + prop.p_type = AMF_STRING; + prop.p_vu.p_aval.av_val = p; + prop.p_vu.p_aval.av_len = av->av_len - (p-arg); + break; + case 'N': + prop.p_type = AMF_NUMBER; + prop.p_vu.p_number = strtod(p, NULL); + break; + case 'O': + prop.p_type = AMF_OBJECT; + break; + default: + return -1; + } + } + else + return -1; + + if (*depth) + { + AMFObject *o2; + for (i=0; i<*depth; i++) + { + o2 = &obj->o_props[obj->o_num-1].p_vu.p_object; + obj = o2; + } + } + AMF_AddProp(obj, &prop); + if (prop.p_type == AMF_OBJECT) + (*depth)++; + return 0; +} + +bool RTMP_SetOpt(RTMP *r, const AVal *opt, AVal *arg) +{ + int i; + void *v; + + for (i=0; options[i].name.av_len; i++) { + if (opt->av_len != options[i].name.av_len) continue; + if (strcasecmp(opt->av_val, options[i].name.av_val)) continue; + v = (char *)r + options[i].off; + switch(options[i].otype) { + case OPT_STR: { + AVal *aptr = v; + *aptr = *arg; } + break; + case OPT_INT: { + long l = strtol(arg->av_val, NULL, 0); + *(int *)v = l; } + break; + case OPT_BOOL: { + int j; + bool b = false; + for (j=0; truth[j].av_len; j++) { + if (arg->av_len != truth[j].av_len) continue; + if (strcasecmp(arg->av_val, truth[j].av_val)) continue; + b = true; break; } + *(bool *)v = b; + } + break; + case OPT_CONN: + if (parseAMF(&r->Link.extras, arg, &r->Link.edepth)) + return false; + break; + } + break; + } + if (!options[i].name.av_len) { + RTMP_Log(RTMP_LOGERROR, "Unknown option %s", opt->av_val); + RTMP_OptUsage(); + return false; + } + + return true; +} + +bool RTMP_SetupURL(RTMP *r, char *url) +{ + AVal opt, arg; + char *p1, *p2, *ptr = strchr(url, ' '); + bool ret; + unsigned int port = 0; + + if (ptr) + *ptr = '\0'; + + ret = RTMP_ParseURL(url, &r->Link.protocol, &r->Link.hostname, + &port, &r->Link.playpath0, &r->Link.app); + if (!ret) + return ret; + r->Link.port = port; + r->Link.playpath = r->Link.playpath0; + + while (ptr) { + *ptr++ = '\0'; + p1 = ptr; + p2 = strchr(p1, '='); + if (!p2) + break; + opt.av_val = p1; + opt.av_len = p2 - p1; + *p2++ = '\0'; + arg.av_val = p2; + ptr = strchr(p2, ' '); + if (ptr) { + *ptr = '\0'; + arg.av_len = ptr - p2; + } else { + arg.av_len = strlen(p2); + } + + /* unescape */ + port = arg.av_len; + for (p1=p2; port >0;) { + if (*p1 == '\\') { + int c; + if (port < 3) + return false; + sscanf(p1+1, "%02x", &c); + *p2++ = c; + port -= 3; + p1 += 3; + } else { + *p2++ = *p1++; + port--; + } + } + arg.av_len = p2 - arg.av_val; + + ret = RTMP_SetOpt(r, &opt, &arg); + if (!ret) + return ret; + } + + if (!r->Link.tcUrl.av_len) + { + r->Link.tcUrl.av_val = url; + if (r->Link.app.av_len) + r->Link.tcUrl.av_len = r->Link.app.av_len + (r->Link.app.av_val - url); + else + r->Link.tcUrl.av_len = strlen(url); + } + + if (r->Link.swfVfy && r->Link.swfUrl.av_len) + RTMP_HashSWF(r->Link.swfUrl.av_val, &r->Link.SWFSize, + (unsigned char *)r->Link.SWFHash, r->Link.swfAge); + + if (r->Link.port == 0) + { + if (r->Link.protocol & RTMP_FEATURE_SSL) + r->Link.port = 443; + else if (r->Link.protocol & RTMP_FEATURE_HTTP) + r->Link.port = 80; + else + r->Link.port = 1935; + } + return true; +} + +static bool +add_addr_info(struct sockaddr_in *service, AVal *host, int port) +{ + char *hostname; + bool ret = true; + if (host->av_val[host->av_len]) + { + hostname = malloc(host->av_len+1); + memcpy(hostname, host->av_val, host->av_len); + hostname[host->av_len] = '\0'; + } + else + { + hostname = host->av_val; + } + + service->sin_addr.s_addr = inet_addr(hostname); + if (service->sin_addr.s_addr == INADDR_NONE) + { + struct hostent *host = gethostbyname(hostname); + if (host == NULL || host->h_addr == NULL) + { + RTMP_Log(RTMP_LOGERROR, "Problem accessing the DNS. (addr: %s)", hostname); + ret = false; + goto finish; + } + service->sin_addr = *(struct in_addr *)host->h_addr; + } + + service->sin_port = htons(port); +finish: + if (hostname != host->av_val) + free(hostname); + return ret; +} + +bool +RTMP_Connect0(RTMP *r, struct sockaddr * service) +{ + r->m_sb.sb_timedout = false; + r->m_pausing = 0; + r->m_fDuration = 0.0; + + r->m_sb.sb_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (r->m_sb.sb_socket != -1) + { + if (connect(r->m_sb.sb_socket, service, sizeof(struct sockaddr)) < 0) + { + int err = GetSockError(); + RTMP_Log(RTMP_LOGERROR, "%s, failed to connect socket. %d (%s)", + __FUNCTION__, err, strerror(err)); + RTMP_Close(r); + return false; + } + + if (r->Link.socksport) + { + RTMP_Log(RTMP_LOGDEBUG, "%s ... SOCKS negotiation", __FUNCTION__); + if (!SocksNegotiate(r)) + { + RTMP_Log(RTMP_LOGERROR, "%s, SOCKS negotiation failed.", __FUNCTION__); + RTMP_Close(r); + return false; + } + } + } + else + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to create socket. Error: %d", __FUNCTION__, + GetSockError()); + return false; + } + + // set timeout + SET_RCVTIMEO(tv, r->Link.timeout); + if (setsockopt + (r->m_sb.sb_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv))) + { + RTMP_Log(RTMP_LOGERROR, "%s, Setting socket timeout to %ds failed!", + __FUNCTION__, r->Link.timeout); + } + + int on = 1; + setsockopt(r->m_sb.sb_socket, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)); + + return true; +} + +bool +RTMP_Connect1(RTMP *r, RTMPPacket *cp) +{ + if (r->Link.protocol & RTMP_FEATURE_SSL) + { +#ifdef CRYPTO + TLS_client(RTMP_TLS_ctx, r->m_sb.sb_ssl); + TLS_setfd(r->m_sb.sb_ssl, r->m_sb.sb_socket); + if (TLS_connect(r->m_sb.sb_ssl) < 0) + { + RTMP_Log(RTMP_LOGERROR, "%s, TLS_Connect failed", __FUNCTION__); + RTMP_Close(r); + return false; + } +#else + RTMP_Log(RTMP_LOGERROR, "%s, no CRYPTO support", __FUNCTION__); + RTMP_Close(r); + return false; + +#endif + } + if (r->Link.protocol & RTMP_FEATURE_HTTP) + { + r->m_msgCounter = 1; + r->m_clientID.av_val = NULL; + r->m_clientID.av_len = 0; + HTTP_Post(r, RTMPT_OPEN, "", 1); + HTTP_read(r, 1); + r->m_msgCounter = 0; + } + RTMP_Log(RTMP_LOGDEBUG, "%s, ... connected, handshaking", __FUNCTION__); + if (!HandShake(r, true)) + { + RTMP_Log(RTMP_LOGERROR, "%s, handshake failed.", __FUNCTION__); + RTMP_Close(r); + return false; + } + RTMP_Log(RTMP_LOGDEBUG, "%s, handshaked", __FUNCTION__); + + if (!SendConnectPacket(r, cp)) + { + RTMP_Log(RTMP_LOGERROR, "%s, RTMP connect failed.", __FUNCTION__); + RTMP_Close(r); + return false; + } + return true; +} + +bool +RTMP_Connect(RTMP *r, RTMPPacket *cp) +{ + struct sockaddr_in service; + if (!r->Link.hostname.av_len) + return false; + + memset(&service, 0, sizeof(struct sockaddr_in)); + service.sin_family = AF_INET; + + if (r->Link.socksport) + { + // Connect via SOCKS + if (!add_addr_info(&service, &r->Link.sockshost, r->Link.socksport)) + return false; + } + else + { + // Connect directly + if (!add_addr_info(&service, &r->Link.hostname, r->Link.port)) + return false; + } + + if (!RTMP_Connect0(r, (struct sockaddr *)&service)) + return false; + + r->m_bSendCounter = true; + + return RTMP_Connect1(r, cp); +} + +static bool +SocksNegotiate(RTMP *r) +{ + struct sockaddr_in service; + memset(&service, 0, sizeof(struct sockaddr_in)); + + add_addr_info(&service, &r->Link.hostname, r->Link.port); + unsigned long addr = htonl(service.sin_addr.s_addr); + + char packet[] = { + 4, 1, // SOCKS 4, connect + (r->Link.port >> 8) & 0xFF, + (r->Link.port) & 0xFF, + (char)(addr >> 24) & 0xFF, (char)(addr >> 16) & 0xFF, + (char)(addr >> 8) & 0xFF, (char)addr & 0xFF, + 0 + }; // NULL terminate + + WriteN(r, packet, sizeof packet); + + if (ReadN(r, packet, 8) != 8) + return false; + + if (packet[0] == 0 && packet[1] == 90) + { + return true; + } + else + { + RTMP_Log(RTMP_LOGERROR, "%s, SOCKS returned error code %d", packet[1]); + return false; + } +} + +bool +RTMP_ConnectStream(RTMP *r, int seekTime) +{ + RTMPPacket packet = { 0 }; + + /* seekTime was already set by SetupStream / SetupURL. + * This is only needed by ReconnectStream. + */ + if (seekTime > 0) + r->Link.seekTime = seekTime; + + r->m_mediaChannel = 0; + + while (!r->m_bPlaying && RTMP_IsConnected(r) && RTMP_ReadPacket(r, &packet)) + { + if (RTMPPacket_IsReady(&packet)) + { + if (!packet.m_nBodySize) + continue; + if ((packet.m_packetType == RTMP_PACKET_TYPE_AUDIO) || + (packet.m_packetType == RTMP_PACKET_TYPE_VIDEO) || + (packet.m_packetType == RTMP_PACKET_TYPE_INFO)) + { + RTMP_Log(RTMP_LOGWARNING, "Received FLV packet before play()! Ignoring."); + RTMPPacket_Free(&packet); + continue; + } + + RTMP_ClientPacket(r, &packet); + RTMPPacket_Free(&packet); + } + } + + return r->m_bPlaying; +} + +bool +RTMP_ReconnectStream(RTMP *r, int seekTime) +{ + RTMP_DeleteStream(r); + + RTMP_SendCreateStream(r); + + return RTMP_ConnectStream(r, seekTime); +} + +bool +RTMP_ToggleStream(RTMP *r) +{ + bool res; + + if (!r->m_pausing) + { + res = RTMP_SendPause(r, true, r->m_pauseStamp); + if (!res) + return res; + + r->m_pausing = 1; + sleep(1); + } + res = RTMP_SendPause(r, false, r->m_pauseStamp); + r->m_pausing = 3; + return res; +} + +void +RTMP_DeleteStream(RTMP *r) +{ + if (r->m_stream_id < 0) + return; + + r->m_bPlaying = false; + + SendDeleteStream(r, r->m_stream_id); + r->m_stream_id = -1; +} + +int +RTMP_GetNextMediaPacket(RTMP *r, RTMPPacket *packet) +{ + int bHasMediaPacket = 0; + + while (!bHasMediaPacket && RTMP_IsConnected(r) + && RTMP_ReadPacket(r, packet)) + { + if (!RTMPPacket_IsReady(packet)) + { + continue; + } + + bHasMediaPacket = RTMP_ClientPacket(r, packet); + + if (!bHasMediaPacket) + { + RTMPPacket_Free(packet); + } + else if (r->m_pausing == 3) + { + if (packet->m_nTimeStamp <= r->m_mediaStamp) + { + bHasMediaPacket = 0; +#ifdef _DEBUG + RTMP_Log(RTMP_LOGDEBUG, + "Skipped type: %02X, size: %d, TS: %d ms, abs TS: %d, pause: %d ms", + packet->m_packetType, packet->m_nBodySize, + packet->m_nTimeStamp, packet->m_hasAbsTimestamp, + r->m_mediaStamp); +#endif + continue; + } + r->m_pausing = 0; + } + } + + if (bHasMediaPacket) + r->m_bPlaying = true; + else if (r->m_sb.sb_timedout && !r->m_pausing) + r->m_pauseStamp = r->m_channelTimestamp[r->m_mediaChannel]; + + return bHasMediaPacket; +} + +int +RTMP_ClientPacket(RTMP *r, RTMPPacket *packet) +{ + int bHasMediaPacket = 0; + switch (packet->m_packetType) + { + case 0x01: + // chunk size + HandleChangeChunkSize(r, packet); + break; + + case 0x03: + // bytes read report + RTMP_Log(RTMP_LOGDEBUG, "%s, received: bytes read report", __FUNCTION__); + break; + + case 0x04: + // ctrl + HandleCtrl(r, packet); + break; + + case 0x05: + // server bw + HandleServerBW(r, packet); + break; + + case 0x06: + // client bw + HandleClientBW(r, packet); + break; + + case 0x08: + // audio data + //RTMP_Log(RTMP_LOGDEBUG, "%s, received: audio %lu bytes", __FUNCTION__, packet.m_nBodySize); + HandleAudio(r, packet); + bHasMediaPacket = 1; + if (!r->m_mediaChannel) + r->m_mediaChannel = packet->m_nChannel; + if (!r->m_pausing) + r->m_mediaStamp = packet->m_nTimeStamp; + break; + + case 0x09: + // video data + //RTMP_Log(RTMP_LOGDEBUG, "%s, received: video %lu bytes", __FUNCTION__, packet.m_nBodySize); + HandleVideo(r, packet); + bHasMediaPacket = 1; + if (!r->m_mediaChannel) + r->m_mediaChannel = packet->m_nChannel; + if (!r->m_pausing) + r->m_mediaStamp = packet->m_nTimeStamp; + break; + + case 0x0F: // flex stream send + RTMP_Log(RTMP_LOGDEBUG, + "%s, flex stream send, size %lu bytes, not supported, ignoring", + __FUNCTION__, packet->m_nBodySize); + break; + + case 0x10: // flex shared object + RTMP_Log(RTMP_LOGDEBUG, + "%s, flex shared object, size %lu bytes, not supported, ignoring", + __FUNCTION__, packet->m_nBodySize); + break; + + case 0x11: // flex message + { + RTMP_Log(RTMP_LOGDEBUG, + "%s, flex message, size %lu bytes, not fully supported", + __FUNCTION__, packet->m_nBodySize); + //RTMP_LogHex(packet.m_body, packet.m_nBodySize); + + // some DEBUG code + /*RTMP_LIB_AMFObject obj; + int nRes = obj.Decode(packet.m_body+1, packet.m_nBodySize-1); + if(nRes < 0) { + RTMP_Log(RTMP_LOGERROR, "%s, error decoding AMF3 packet", __FUNCTION__); + //return; + } + + obj.Dump(); */ + + if (HandleInvoke(r, packet->m_body + 1, packet->m_nBodySize - 1) == 1) + bHasMediaPacket = 2; + break; + } + case 0x12: + // metadata (notify) + RTMP_Log(RTMP_LOGDEBUG, "%s, received: notify %lu bytes", __FUNCTION__, + packet->m_nBodySize); + if (HandleMetadata(r, packet->m_body, packet->m_nBodySize)) + bHasMediaPacket = 1; + break; + + case 0x13: + RTMP_Log(RTMP_LOGDEBUG, "%s, shared object, not supported, ignoring", + __FUNCTION__); + break; + + case 0x14: + // invoke + RTMP_Log(RTMP_LOGDEBUG, "%s, received: invoke %lu bytes", __FUNCTION__, + packet->m_nBodySize); + //RTMP_LogHex(packet.m_body, packet.m_nBodySize); + + if (HandleInvoke(r, packet->m_body, packet->m_nBodySize) == 1) + bHasMediaPacket = 2; + break; + + case 0x16: + { + // go through FLV packets and handle metadata packets + unsigned int pos = 0; + uint32_t nTimeStamp = packet->m_nTimeStamp; + + while (pos + 11 < packet->m_nBodySize) + { + uint32_t dataSize = AMF_DecodeInt24(packet->m_body + pos + 1); // size without header (11) and prevTagSize (4) + + if (pos + 11 + dataSize + 4 > packet->m_nBodySize) + { + RTMP_Log(RTMP_LOGWARNING, "Stream corrupt?!"); + break; + } + if (packet->m_body[pos] == 0x12) + { + HandleMetadata(r, packet->m_body + pos + 11, dataSize); + } + else if (packet->m_body[pos] == 8 || packet->m_body[pos] == 9) + { + nTimeStamp = AMF_DecodeInt24(packet->m_body + pos + 4); + nTimeStamp |= (packet->m_body[pos + 7] << 24); + } + pos += (11 + dataSize + 4); + } + if (!r->m_pausing) + r->m_mediaStamp = nTimeStamp; + + // FLV tag(s) + //RTMP_Log(RTMP_LOGDEBUG, "%s, received: FLV tag(s) %lu bytes", __FUNCTION__, packet.m_nBodySize); + bHasMediaPacket = 1; + break; + } + default: + RTMP_Log(RTMP_LOGDEBUG, "%s, unknown packet type received: 0x%02x", __FUNCTION__, + packet->m_packetType); +#ifdef _DEBUG + RTMP_LogHex(RTMP_LOGDEBUG, packet->m_body, packet->m_nBodySize); +#endif + } + + return bHasMediaPacket; +} + +#ifdef _DEBUG +extern FILE *netstackdump; +extern FILE *netstackdump_read; +#endif + +static int +ReadN(RTMP *r, char *buffer, int n) +{ + int nOriginalSize = n; + int avail; + char *ptr; + + r->m_sb.sb_timedout = false; + +#ifdef _DEBUG + memset(buffer, 0, n); +#endif + + ptr = buffer; + while (n > 0) + { + int nBytes = 0, nRead; + if (r->Link.protocol & RTMP_FEATURE_HTTP) + { + while (!r->m_resplen) + { + if (r->m_sb.sb_size < 144) + { + if (!r->m_unackd) + HTTP_Post(r, RTMPT_IDLE, "", 1); + if (RTMPSockBuf_Fill(&r->m_sb) < 1) + { + if (!r->m_sb.sb_timedout) + RTMP_Close(r); + return 0; + } + } + HTTP_read(r, 0); + } + if (r->m_resplen && !r->m_sb.sb_size) + RTMPSockBuf_Fill(&r->m_sb); + avail = r->m_sb.sb_size; + if (avail > r->m_resplen) + avail = r->m_resplen; + } + else + { + avail = r->m_sb.sb_size; + if (avail == 0) + { + if (RTMPSockBuf_Fill(&r->m_sb) < 1) + { + if (!r->m_sb.sb_timedout) + RTMP_Close(r); + return 0; + } + avail = r->m_sb.sb_size; + } + } + nRead = ((n < avail) ? n : avail); + if (nRead > 0) + { + memcpy(ptr, r->m_sb.sb_start, nRead); + r->m_sb.sb_start += nRead; + r->m_sb.sb_size -= nRead; + nBytes = nRead; + r->m_nBytesIn += nRead; + if (r->m_bSendCounter + && r->m_nBytesIn > r->m_nBytesInSent + r->m_nClientBW / 2) + SendBytesReceived(r); + } + //RTMP_Log(RTMP_LOGDEBUG, "%s: %d bytes\n", __FUNCTION__, nBytes); +#ifdef _DEBUG + fwrite(ptr, 1, nBytes, netstackdump_read); +#endif + + if (nBytes == 0) + { + RTMP_Log(RTMP_LOGDEBUG, "%s, RTMP socket closed by peer", __FUNCTION__); + //goto again; + RTMP_Close(r); + break; + } + + if (r->Link.protocol & RTMP_FEATURE_HTTP) + r->m_resplen -= nBytes; + +#ifdef CRYPTO + if (r->Link.rc4keyIn) + { + RC4_encrypt(r->Link.rc4keyIn, nBytes, ptr); + } +#endif + + n -= nBytes; + ptr += nBytes; + } + + return nOriginalSize - n; +} + +static bool +WriteN(RTMP *r, const char *buffer, int n) +{ + const char *ptr = buffer; +#ifdef CRYPTO + char *encrypted = 0; + char buf[RTMP_BUFFER_CACHE_SIZE]; + + if (r->Link.rc4keyOut) + { + if (n > sizeof(buf)) + encrypted = (char *)malloc(n); + else + encrypted = (char *)buf; + ptr = encrypted; + RC4_encrypt2(r->Link.rc4keyOut, n, buffer, ptr); + } +#endif + + while (n > 0) + { + int nBytes; + + if (r->Link.protocol & RTMP_FEATURE_HTTP) + nBytes = HTTP_Post(r, RTMPT_SEND, ptr, n); + else + nBytes = RTMPSockBuf_Send(&r->m_sb, ptr, n); + //RTMP_Log(RTMP_LOGDEBUG, "%s: %d\n", __FUNCTION__, nBytes); + + if (nBytes < 0) + { + int sockerr = GetSockError(); + RTMP_Log(RTMP_LOGERROR, "%s, RTMP send error %d (%d bytes)", __FUNCTION__, + sockerr, n); + + if (sockerr == EINTR && !RTMP_ctrlC) + continue; + + RTMP_Close(r); + n = 1; + break; + } + + if (nBytes == 0) + break; + + n -= nBytes; + ptr += nBytes; + } + +#ifdef CRYPTO + if (encrypted && encrypted != buf) + free(encrypted); +#endif + + return n == 0; +} + +#define SAVC(x) static const AVal av_##x = AVC(#x) + +SAVC(app); +SAVC(connect); +SAVC(flashVer); +SAVC(swfUrl); +SAVC(pageUrl); +SAVC(tcUrl); +SAVC(fpad); +SAVC(capabilities); +SAVC(audioCodecs); +SAVC(videoCodecs); +SAVC(videoFunction); +SAVC(objectEncoding); +SAVC(secureToken); +SAVC(secureTokenResponse); +SAVC(type); +SAVC(nonprivate); + +static bool +SendConnectPacket(RTMP *r, RTMPPacket *cp) +{ + RTMPPacket packet; + char pbuf[4096], *pend = pbuf + sizeof(pbuf); + + if (cp) + return RTMP_SendPacket(r, cp, true); + + packet.m_nChannel = 0x03; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = 0x14; // INVOKE + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_connect); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_OBJECT; + + enc = AMF_EncodeNamedString(enc, pend, &av_app, &r->Link.app); + if (!enc) + return false; + if (r->Link.protocol & RTMP_FEATURE_WRITE) + { + enc = AMF_EncodeNamedString(enc, pend, &av_type, &av_nonprivate); + if (!enc) + return false; + } + if (r->Link.flashVer.av_len) + { + enc = AMF_EncodeNamedString(enc, pend, &av_flashVer, &r->Link.flashVer); + if (!enc) + return false; + } + if (r->Link.swfUrl.av_len) + { + enc = AMF_EncodeNamedString(enc, pend, &av_swfUrl, &r->Link.swfUrl); + if (!enc) + return false; + } + if (r->Link.tcUrl.av_len) + { + enc = AMF_EncodeNamedString(enc, pend, &av_tcUrl, &r->Link.tcUrl); + if (!enc) + return false; + } + if (!(r->Link.protocol & RTMP_FEATURE_WRITE)) + { + enc = AMF_EncodeNamedBoolean(enc, pend, &av_fpad, false); + if (!enc) + return false; + enc = AMF_EncodeNamedNumber(enc, pend, &av_capabilities, 15.0); + if (!enc) + return false; + enc = AMF_EncodeNamedNumber(enc, pend, &av_audioCodecs, r->m_fAudioCodecs); + if (!enc) + return false; + enc = AMF_EncodeNamedNumber(enc, pend, &av_videoCodecs, r->m_fVideoCodecs); + if (!enc) + return false; + enc = AMF_EncodeNamedNumber(enc, pend, &av_videoFunction, 1.0); + if (!enc) + return false; + if (r->Link.pageUrl.av_len) + { + enc = AMF_EncodeNamedString(enc, pend, &av_pageUrl, &r->Link.pageUrl); + if (!enc) + return false; + } + } + if (r->m_fEncoding != 0.0 || r->m_bSendEncoding) + { // AMF0, AMF3 not fully supported yet + enc = AMF_EncodeNamedNumber(enc, pend, &av_objectEncoding, r->m_fEncoding); + if (!enc) + return false; + } + if (enc + 3 >= pend) + return false; + *enc++ = 0; + *enc++ = 0; // end of object - 0x00 0x00 0x09 + *enc++ = AMF_OBJECT_END; + + // add auth string + if (r->Link.auth.av_len) + { + enc = AMF_EncodeBoolean(enc, pend, r->Link.authflag); + if (!enc) + return false; + enc = AMF_EncodeString(enc, pend, &r->Link.auth); + if (!enc) + return false; + } + if (r->Link.extras.o_num) + { + int i; + for (i = 0; i < r->Link.extras.o_num; i++) + { + enc = AMFProp_Encode(&r->Link.extras.o_props[i], enc, pend); + if (!enc) + return false; + } + } + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, true); +} + +#if 0 /* unused */ +SAVC(bgHasStream); + +static bool +SendBGHasStream(RTMP *r, double dId, AVal *playpath) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x03; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x14; // INVOKE + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_bgHasStream); + enc = AMF_EncodeNumber(enc, pend, dId); + *enc++ = AMF_NULL; + + enc = AMF_EncodeString(enc, pend, playpath); + if (enc == NULL) + return false; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, true); +} +#endif + +SAVC(createStream); + +bool +RTMP_SendCreateStream(RTMP *r) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x03; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x14; // INVOKE + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_createStream); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; // NULL + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, true); +} + +SAVC(FCSubscribe); + +static bool +SendFCSubscribe(RTMP *r, AVal *subscribepath) +{ + RTMPPacket packet; + char pbuf[512], *pend = pbuf + sizeof(pbuf); + packet.m_nChannel = 0x03; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x14; // INVOKE + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + RTMP_Log(RTMP_LOGDEBUG, "FCSubscribe: %s", subscribepath->av_val); + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_FCSubscribe); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, subscribepath); + + if (!enc) + return false; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, true); +} + +SAVC(releaseStream); + +static bool +SendReleaseStream(RTMP *r) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x03; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x14; // INVOKE + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_releaseStream); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, &r->Link.playpath); + if (!enc) + return false; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, false); +} + +SAVC(FCPublish); + +static bool +SendFCPublish(RTMP *r) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x03; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x14; // INVOKE + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_FCPublish); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, &r->Link.playpath); + if (!enc) + return false; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, false); +} + +SAVC(FCUnpublish); + +static bool +SendFCUnpublish(RTMP *r) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x03; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x14; // INVOKE + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_FCUnpublish); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, &r->Link.playpath); + if (!enc) + return false; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, false); +} + +SAVC(publish); +SAVC(live); +SAVC(record); + +static bool +SendPublish(RTMP *r) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x04; // source channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = 0x14; // INVOKE + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = r->m_stream_id; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_publish); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, &r->Link.playpath); + if (!enc) + return false; + + /* FIXME: should we choose live based on Link.bLiveStream? */ + enc = AMF_EncodeString(enc, pend, &av_live); + if (!enc) + return false; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, true); +} + +SAVC(deleteStream); + +static bool +SendDeleteStream(RTMP *r, double dStreamId) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x03; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x14; // INVOKE + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_deleteStream); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeNumber(enc, pend, dStreamId); + + packet.m_nBodySize = enc - packet.m_body; + + /* no response expected */ + return RTMP_SendPacket(r, &packet, false); +} + +SAVC(pause); + +bool +RTMP_SendPause(RTMP *r, bool DoPause, int dTime) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x08; // video channel + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x14; // invoke + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_pause); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeBoolean(enc, pend, DoPause); + enc = AMF_EncodeNumber(enc, pend, (double)dTime); + + packet.m_nBodySize = enc - packet.m_body; + + RTMP_Log(RTMP_LOGDEBUG, "%s, %d, pauseTime=%.2f", __FUNCTION__, DoPause, dTime); + return RTMP_SendPacket(r, &packet, true); +} + +SAVC(seek); + +bool +RTMP_SendSeek(RTMP *r, int dTime) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x08; // video channel + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x14; // invoke + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_seek); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeNumber(enc, pend, (double)dTime); + + packet.m_nBodySize = enc - packet.m_body; + + r->m_read.flags |= RTMP_READ_SEEKING; + r->m_read.nResumeTS = 0; + + return RTMP_SendPacket(r, &packet, true); +} + +bool +RTMP_SendServerBW(RTMP *r) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x02; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = 0x05; // Server BW + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + packet.m_nBodySize = 4; + + AMF_EncodeInt32(packet.m_body, pend, r->m_nServerBW); + return RTMP_SendPacket(r, &packet, false); +} + +bool +RTMP_SendClientBW(RTMP *r) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x02; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = 0x06; // Client BW + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + packet.m_nBodySize = 5; + + AMF_EncodeInt32(packet.m_body, pend, r->m_nClientBW); + packet.m_body[4] = r->m_nClientBW2; + return RTMP_SendPacket(r, &packet, false); +} + +static bool +SendBytesReceived(RTMP *r) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x02; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x03; // bytes in + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + packet.m_nBodySize = 4; + + AMF_EncodeInt32(packet.m_body, pend, r->m_nBytesIn); // hard coded for now + r->m_nBytesInSent = r->m_nBytesIn; + + //RTMP_Log(RTMP_LOGDEBUG, "Send bytes report. 0x%x (%d bytes)", (unsigned int)m_nBytesIn, m_nBytesIn); + return RTMP_SendPacket(r, &packet, false); +} + +SAVC(_checkbw); + +static bool +SendCheckBW(RTMP *r) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x03; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = 0x14; // INVOKE + packet.m_nTimeStamp = 0; /* RTMP_GetTime(); */ + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av__checkbw); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + + packet.m_nBodySize = enc - packet.m_body; + + // triggers _onbwcheck and eventually results in _onbwdone + return RTMP_SendPacket(r, &packet, false); +} + +SAVC(_result); + +static bool +SendCheckBWResult(RTMP *r, double txn) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x03; // control channel (invoke) + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x14; // INVOKE + packet.m_nTimeStamp = 0x16 * r->m_nBWCheckCounter; // temp inc value. till we figure it out. + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av__result); + enc = AMF_EncodeNumber(enc, pend, txn); + *enc++ = AMF_NULL; + enc = AMF_EncodeNumber(enc, pend, (double)r->m_nBWCheckCounter++); + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, false); +} + +SAVC(play); + +static bool +SendPlay(RTMP *r) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x08; // we make 8 our stream channel + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = 0x14; // INVOKE + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = r->m_stream_id; //0x01000000; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_play); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + + RTMP_Log(RTMP_LOGDEBUG, "%s, seekTime=%d, stopTime=%d, sending play: %s", + __FUNCTION__, r->Link.seekTime, r->Link.stopTime, + r->Link.playpath.av_val); + enc = AMF_EncodeString(enc, pend, &r->Link.playpath); + if (!enc) + return false; + + // Optional parameters start and len. + + // start: -2, -1, 0, positive number + // -2: looks for a live stream, then a recorded stream, if not found any open a live stream + // -1: plays a live stream + // >=0: plays a recorded streams from 'start' milliseconds + if (r->Link.bLiveStream) + enc = AMF_EncodeNumber(enc, pend, -1000.0); + else + { + if (r->Link.seekTime > 0.0) + enc = AMF_EncodeNumber(enc, pend, r->Link.seekTime); // resume from here + else + enc = AMF_EncodeNumber(enc, pend, 0.0); //-2000.0); // recorded as default, -2000.0 is not reliable since that freezes the player if the stream is not found + } + if (!enc) + return false; + + // len: -1, 0, positive number + // -1: plays live or recorded stream to the end (default) + // 0: plays a frame 'start' ms away from the beginning + // >0: plays a live or recoded stream for 'len' milliseconds + //enc += EncodeNumber(enc, -1.0); // len + if (r->Link.stopTime) + { + enc = AMF_EncodeNumber(enc, pend, r->Link.stopTime - r->Link.seekTime); + if (!enc) + return false; + } + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, true); +} + +static bool +SendSecureTokenResponse(RTMP *r, AVal *resp) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x14; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + char *enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_secureTokenResponse); + enc = AMF_EncodeNumber(enc, pend, 0.0); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, resp); + if (!enc) + return false; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, false); +} + +/* +from http://jira.red5.org/confluence/display/docs/Ping: + +Ping is the most mysterious message in RTMP and till now we haven't fully interpreted it yet. In summary, Ping message is used as a special command that are exchanged between client and server. This page aims to document all known Ping messages. Expect the list to grow. + +The type of Ping packet is 0x4 and contains two mandatory parameters and two optional parameters. The first parameter is the type of Ping and in short integer. The second parameter is the target of the ping. As Ping is always sent in Channel 2 (control channel) and the target object in RTMP header is always 0 which means the Connection object, it's necessary to put an extra parameter to indicate the exact target object the Ping is sent to. The second parameter takes this responsibility. The value has the same meaning as the target object field in RTMP header. (The second value could also be used as other purposes, like RTT Ping/Pong. It is used as the timestamp.) The third and fourth parameters are optional and could be looked upon as the parameter of the Ping packet. Below is an unexhausted list of Ping messages. + + * type 0: Clear the stream. No third and fourth parameters. The second parameter could be 0. After the connection is established, a Ping 0,0 will be sent from server to client. The message will also be sent to client on the start of Play and in response of a Seek or Pause/Resume request. This Ping tells client to re-calibrate the clock with the timestamp of the next packet server sends. + * type 1: Tell the stream to clear the playing buffer. + * type 3: Buffer time of the client. The third parameter is the buffer time in millisecond. + * type 4: Reset a stream. Used together with type 0 in the case of VOD. Often sent before type 0. + * type 6: Ping the client from server. The second parameter is the current time. + * type 7: Pong reply from client. The second parameter is the time the server sent with his ping request. + * type 26: SWFVerification request + * type 27: SWFVerification response +*/ +bool +RTMP_SendCtrl(RTMP *r, short nType, unsigned int nObject, unsigned int nTime) +{ + RTMP_Log(RTMP_LOGDEBUG, "sending ctrl. type: 0x%04x", (unsigned short)nType); + + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + int nSize; + + packet.m_nChannel = 0x02; // control channel (ping) + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = 0x04; // ctrl + packet.m_nTimeStamp = 0; /* RTMP_GetTime(); */ + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + switch(nType) { + case 0x03: nSize = 10; break; /* buffer time */ + case 0x1A: nSize = 3; break; /* SWF verify request */ + case 0x1B: nSize = 44; break; /* SWF verify response */ + default: nSize = 6; break; + } + + packet.m_nBodySize = nSize; + + char *buf = packet.m_body; + buf = AMF_EncodeInt16(buf, pend, nType); + + if (nType == 0x1B) + { +#ifdef CRYPTO + memcpy(buf, r->Link.SWFVerificationResponse, 42); + RTMP_Log(RTMP_LOGDEBUG, "Sending SWFVerification response: "); + RTMP_LogHex(RTMP_LOGDEBUG, packet.m_body, packet.m_nBodySize); +#endif + } + else if (nType == 0x1A) + { + *buf = nObject & 0xff; + } + else + { + if (nSize > 2) + buf = AMF_EncodeInt32(buf, pend, nObject); + + if (nSize > 6) + buf = AMF_EncodeInt32(buf, pend, nTime); + } + + return RTMP_SendPacket(r, &packet, false); +} + +static void +AV_erase(AVal *vals, int *num, int i, bool freeit) +{ + if (freeit) + free(vals[i].av_val); + (*num)--; + for (; i < *num; i++) + { + vals[i] = vals[i + 1]; + } + vals[i].av_val = NULL; + vals[i].av_len = 0; +} + +void +RTMP_DropRequest(RTMP *r, int i, bool freeit) +{ + AV_erase(r->m_methodCalls, &r->m_numCalls, i, freeit); +} + +static void +AV_queue(AVal **vals, int *num, AVal *av) +{ + char *tmp; + if (!(*num & 0x0f)) + *vals = realloc(*vals, (*num + 16) * sizeof(AVal)); + tmp = malloc(av->av_len + 1); + memcpy(tmp, av->av_val, av->av_len); + tmp[av->av_len] = '\0'; + (*vals)[*num].av_len = av->av_len; + (*vals)[(*num)++].av_val = tmp; +} + +static void +AV_clear(AVal *vals, int num) +{ + int i; + for (i = 0; i < num; i++) + free(vals[i].av_val); + free(vals); +} + +SAVC(onBWDone); +SAVC(onFCSubscribe); +SAVC(onFCUnsubscribe); +SAVC(_onbwcheck); +SAVC(_onbwdone); +SAVC(_error); +SAVC(close); +SAVC(code); +SAVC(level); +SAVC(onStatus); +static const AVal av_NetStream_Failed = AVC("NetStream.Failed"); +static const AVal av_NetStream_Play_Failed = AVC("NetStream.Play.Failed"); +static const AVal av_NetStream_Play_StreamNotFound = +AVC("NetStream.Play.StreamNotFound"); +static const AVal av_NetConnection_Connect_InvalidApp = +AVC("NetConnection.Connect.InvalidApp"); +static const AVal av_NetStream_Play_Start = AVC("NetStream.Play.Start"); +static const AVal av_NetStream_Play_Complete = AVC("NetStream.Play.Complete"); +static const AVal av_NetStream_Play_Stop = AVC("NetStream.Play.Stop"); +static const AVal av_NetStream_Seek_Notify = AVC("NetStream.Seek.Notify"); +static const AVal av_NetStream_Pause_Notify = AVC("NetStream.Pause.Notify"); +static const AVal av_NetStream_Play_UnpublishNotify = +AVC("NetStream.Play.UnpublishNotify"); +static const AVal av_NetStream_Publish_Start = AVC("NetStream.Publish.Start"); + +// Returns 0 for OK/Failed/error, 1 for 'Stop or Complete' +static int +HandleInvoke(RTMP *r, const char *body, unsigned int nBodySize) +{ + int ret = 0, nRes; + if (body[0] != 0x02) // make sure it is a string method name we start with + { + RTMP_Log(RTMP_LOGWARNING, "%s, Sanity failed. no string method in invoke packet", + __FUNCTION__); + return 0; + } + + AMFObject obj; + nRes = AMF_Decode(&obj, body, nBodySize, false); + if (nRes < 0) + { + RTMP_Log(RTMP_LOGERROR, "%s, error decoding invoke packet", __FUNCTION__); + return 0; + } + + AMF_Dump(&obj); + AVal method; + AMFProp_GetString(AMF_GetProp(&obj, NULL, 0), &method); + double txn = AMFProp_GetNumber(AMF_GetProp(&obj, NULL, 1)); + RTMP_Log(RTMP_LOGDEBUG, "%s, server invoking <%s>", __FUNCTION__, method.av_val); + + if (AVMATCH(&method, &av__result)) + { + AVal methodInvoked = r->m_methodCalls[0]; + AV_erase(r->m_methodCalls, &r->m_numCalls, 0, false); + + RTMP_Log(RTMP_LOGDEBUG, "%s, received result for method call <%s>", __FUNCTION__, + methodInvoked.av_val); + + if (AVMATCH(&methodInvoked, &av_connect)) + { + if (r->Link.token.av_len) + { + AMFObjectProperty p; + if (RTMP_FindFirstMatchingProperty(&obj, &av_secureToken, &p)) + { + DecodeTEA(&r->Link.token, &p.p_vu.p_aval); + SendSecureTokenResponse(r, &p.p_vu.p_aval); + } + } + if (r->Link.protocol & RTMP_FEATURE_WRITE) + { + SendReleaseStream(r); + SendFCPublish(r); + } + else + { + RTMP_SendServerBW(r); + RTMP_SendCtrl(r, 3, 0, 300); + } + RTMP_SendCreateStream(r); + + if (!(r->Link.protocol & RTMP_FEATURE_WRITE)) + { + /* Send the FCSubscribe if live stream or if subscribepath is set */ + if (r->Link.subscribepath.av_len) + SendFCSubscribe(r, &r->Link.subscribepath); + else if (r->Link.bLiveStream) + SendFCSubscribe(r, &r->Link.playpath); + } + } + else if (AVMATCH(&methodInvoked, &av_createStream)) + { + r->m_stream_id = (int)AMFProp_GetNumber(AMF_GetProp(&obj, NULL, 3)); + + if (r->Link.protocol & RTMP_FEATURE_WRITE) + { + SendPublish(r); + } + else + { + SendPlay(r); + RTMP_SendCtrl(r, 3, r->m_stream_id, r->m_nBufferMS); + } + } + else if (AVMATCH(&methodInvoked, &av_play) || + AVMATCH(&methodInvoked, &av_publish)) + { + r->m_bPlaying = true; + } + free(methodInvoked.av_val); + } + else if (AVMATCH(&method, &av_onBWDone)) + { + SendCheckBW(r); + } + else if (AVMATCH(&method, &av_onFCSubscribe)) + { + // SendOnFCSubscribe(); + } + else if (AVMATCH(&method, &av_onFCUnsubscribe)) + { + RTMP_Close(r); + ret = 1; + } + else if (AVMATCH(&method, &av__onbwcheck)) + { + SendCheckBWResult(r, txn); + } + else if (AVMATCH(&method, &av__onbwdone)) + { + int i; + for (i = 0; i < r->m_numCalls; i++) + if (AVMATCH(&r->m_methodCalls[i], &av__checkbw)) + { + AV_erase(r->m_methodCalls, &r->m_numCalls, i, true); + break; + } + } + else if (AVMATCH(&method, &av__error)) + { + RTMP_Log(RTMP_LOGERROR, "rtmp server sent error"); + } + else if (AVMATCH(&method, &av_close)) + { + RTMP_Log(RTMP_LOGERROR, "rtmp server requested close"); + RTMP_Close(r); + } + else if (AVMATCH(&method, &av_onStatus)) + { + AMFObject obj2; + AVal code, level; + AMFProp_GetObject(AMF_GetProp(&obj, NULL, 3), &obj2); + AMFProp_GetString(AMF_GetProp(&obj2, &av_code, -1), &code); + AMFProp_GetString(AMF_GetProp(&obj2, &av_level, -1), &level); + + RTMP_Log(RTMP_LOGDEBUG, "%s, onStatus: %s", __FUNCTION__, code.av_val); + if (AVMATCH(&code, &av_NetStream_Failed) + || AVMATCH(&code, &av_NetStream_Play_Failed) + || AVMATCH(&code, &av_NetStream_Play_StreamNotFound) + || AVMATCH(&code, &av_NetConnection_Connect_InvalidApp)) + { + r->m_stream_id = -1; + RTMP_Close(r); + RTMP_Log(RTMP_LOGERROR, "Closing connection: %s", code.av_val); + } + + else if (AVMATCH(&code, &av_NetStream_Play_Start)) + { + int i; + r->m_bPlaying = true; + for (i = 0; i < r->m_numCalls; i++) + { + if (AVMATCH(&r->m_methodCalls[i], &av_play)) + { + AV_erase(r->m_methodCalls, &r->m_numCalls, i, true); + break; + } + } + } + + else if (AVMATCH(&code, &av_NetStream_Publish_Start)) + { + int i; + r->m_bPlaying = true; + for (i = 0; i < r->m_numCalls; i++) + { + if (AVMATCH(&r->m_methodCalls[i], &av_publish)) + { + AV_erase(r->m_methodCalls, &r->m_numCalls, i, true); + break; + } + } + } + + // Return 1 if this is a Play.Complete or Play.Stop + else if (AVMATCH(&code, &av_NetStream_Play_Complete) + || AVMATCH(&code, &av_NetStream_Play_Stop) + || AVMATCH(&code, &av_NetStream_Play_UnpublishNotify)) + { + RTMP_Close(r); + ret = 1; + } + + else if (AVMATCH(&code, &av_NetStream_Seek_Notify)) + { + r->m_read.flags &= ~RTMP_READ_SEEKING; + } + + else if (AVMATCH(&code, &av_NetStream_Pause_Notify)) + { + if (r->m_pausing == 1 || r->m_pausing == 2) + { + RTMP_SendPause(r, false, r->m_pauseStamp); + r->m_pausing = 3; + } + } + } + else + { + + } + AMF_Reset(&obj); + return ret; +} + +bool +RTMP_FindFirstMatchingProperty(AMFObject *obj, const AVal *name, + AMFObjectProperty * p) +{ + int n; + /* this is a small object search to locate the "duration" property */ + for (n = 0; n < obj->o_num; n++) + { + AMFObjectProperty *prop = AMF_GetProp(obj, NULL, n); + + if (AVMATCH(&prop->p_name, name)) + { + *p = *prop; + return true; + } + + if (prop->p_type == AMF_OBJECT) + { + if (RTMP_FindFirstMatchingProperty(&prop->p_vu.p_object, name, p)) + return true; + } + } + return false; +} + +static bool +DumpMetaData(AMFObject *obj) +{ + AMFObjectProperty *prop; + int n; + for (n = 0; n < obj->o_num; n++) + { + prop = AMF_GetProp(obj, NULL, n); + if (prop->p_type != AMF_OBJECT) + { + char str[256] = ""; + switch (prop->p_type) + { + case AMF_NUMBER: + snprintf(str, 255, "%.2f", prop->p_vu.p_number); + break; + case AMF_BOOLEAN: + snprintf(str, 255, "%s", + prop->p_vu.p_number != 0. ? "TRUE" : "FALSE"); + break; + case AMF_STRING: + snprintf(str, 255, "%.*s", prop->p_vu.p_aval.av_len, + prop->p_vu.p_aval.av_val); + break; + case AMF_DATE: + snprintf(str, 255, "timestamp:%.2f", prop->p_vu.p_number); + break; + default: + snprintf(str, 255, "INVALID TYPE 0x%02x", + (unsigned char)prop->p_type); + } + if (prop->p_name.av_len) + { + // chomp + if (strlen(str) >= 1 && str[strlen(str) - 1] == '\n') + str[strlen(str) - 1] = '\0'; + RTMP_LogPrintf(" %-22.*s%s\n", prop->p_name.av_len, + prop->p_name.av_val, str); + } + } + else + { + if (prop->p_name.av_len) + RTMP_LogPrintf("%.*s:\n", prop->p_name.av_len, prop->p_name.av_val); + DumpMetaData(&prop->p_vu.p_object); + } + } + return false; +} + +SAVC(onMetaData); +SAVC(duration); + +static bool +HandleMetadata(RTMP *r, char *body, unsigned int len) +{ + // allright we get some info here, so parse it and print it + // also keep duration or filesize to make a nice progress bar + + AMFObject obj; + AVal metastring; + bool ret = false; + + int nRes = AMF_Decode(&obj, body, len, false); + if (nRes < 0) + { + RTMP_Log(RTMP_LOGERROR, "%s, error decoding meta data packet", __FUNCTION__); + return false; + } + + AMF_Dump(&obj); + AMFProp_GetString(AMF_GetProp(&obj, NULL, 0), &metastring); + + if (AVMATCH(&metastring, &av_onMetaData)) + { + AMFObjectProperty prop; + // Show metadata + RTMP_LogPrintf("Metadata:\n"); + DumpMetaData(&obj); + if (RTMP_FindFirstMatchingProperty(&obj, &av_duration, &prop)) + { + r->m_fDuration = prop.p_vu.p_number; + //RTMP_Log(RTMP_LOGDEBUG, "Set duration: %.2f", m_fDuration); + } + ret = true; + } + AMF_Reset(&obj); + return ret; +} + +static void +HandleChangeChunkSize(RTMP *r, const RTMPPacket *packet) +{ + if (packet->m_nBodySize >= 4) + { + r->m_inChunkSize = AMF_DecodeInt32(packet->m_body); + RTMP_Log(RTMP_LOGDEBUG, "%s, received: chunk size change to %d", __FUNCTION__, + r->m_inChunkSize); + } +} + +static void +HandleAudio(RTMP *r, const RTMPPacket *packet) +{ +} + +static void +HandleVideo(RTMP *r, const RTMPPacket *packet) +{ +} + +static void +HandleCtrl(RTMP *r, const RTMPPacket *packet) +{ + short nType = -1; + unsigned int tmp; + if (packet->m_body && packet->m_nBodySize >= 2) + nType = AMF_DecodeInt16(packet->m_body); + RTMP_Log(RTMP_LOGDEBUG, "%s, received ctrl. type: %d, len: %d", __FUNCTION__, nType, + packet->m_nBodySize); + //RTMP_LogHex(packet.m_body, packet.m_nBodySize); + + if (packet->m_nBodySize >= 6) + { + switch (nType) + { + case 0: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream Begin %d", __FUNCTION__, tmp); + break; + + case 1: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream EOF %d", __FUNCTION__, tmp); + if (r->m_pausing == 1) + r->m_pausing = 2; + break; + + case 2: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream Dry %d", __FUNCTION__, tmp); + break; + + case 4: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream IsRecorded %d", __FUNCTION__, tmp); + break; + + case 6: // server ping. reply with pong. + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Ping %d", __FUNCTION__, tmp); + RTMP_SendCtrl(r, 0x07, tmp, 0); + break; + + case 31: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream BufferEmpty %d", __FUNCTION__, tmp); + if (r->Link.bLiveStream || (r->Link.protocol & RTMP_FEATURE_HTTP)) + break; + if (!r->m_pausing) + { + r->m_pauseStamp = r->m_channelTimestamp[r->m_mediaChannel]; + RTMP_SendPause(r, true, r->m_pauseStamp); + r->m_pausing = 1; + } + else if (r->m_pausing == 2) + { + RTMP_SendPause(r, false, r->m_pauseStamp); + r->m_pausing = 3; + } + break; + + case 32: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream BufferReady %d", __FUNCTION__, tmp); + break; + + default: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream xx %d", __FUNCTION__, tmp); + break; + } + + } + + if (nType == 0x1A) + { + RTMP_Log(RTMP_LOGDEBUG, "%s, SWFVerification ping received: ", __FUNCTION__); +#ifdef CRYPTO + //RTMP_LogHex(packet.m_body, packet.m_nBodySize); + + // respond with HMAC SHA256 of decompressed SWF, key is the 30byte player key, also the last 30 bytes of the server handshake are applied + if (r->Link.SWFSize) + { + RTMP_SendCtrl(r, 0x1B, 0, 0); + } + else + { + RTMP_Log(RTMP_LOGERROR, + "%s: Ignoring SWFVerification request, use --swfVfy!", + __FUNCTION__); + } +#else + RTMP_Log(RTMP_LOGERROR, + "%s: Ignoring SWFVerification request, no CRYPTO support!", + __FUNCTION__); +#endif + } +} + +static void +HandleServerBW(RTMP *r, const RTMPPacket *packet) +{ + r->m_nServerBW = AMF_DecodeInt32(packet->m_body); + RTMP_Log(RTMP_LOGDEBUG, "%s: server BW = %d", __FUNCTION__, r->m_nServerBW); +} + +static void +HandleClientBW(RTMP *r, const RTMPPacket *packet) +{ + r->m_nClientBW = AMF_DecodeInt32(packet->m_body); + if (packet->m_nBodySize > 4) + r->m_nClientBW2 = packet->m_body[4]; + else + r->m_nClientBW2 = -1; + RTMP_Log(RTMP_LOGDEBUG, "%s: client BW = %d %d", __FUNCTION__, r->m_nClientBW, + r->m_nClientBW2); +} + +static int +DecodeInt32LE(const char *data) +{ + unsigned char *c = (unsigned char *)data; + unsigned int val; + + val = (c[3] << 24) | (c[2] << 16) | (c[1] << 8) | c[0]; + return val; +} + +static int +EncodeInt32LE(char *output, int nVal) +{ + output[0] = nVal; + nVal >>= 8; + output[1] = nVal; + nVal >>= 8; + output[2] = nVal; + nVal >>= 8; + output[3] = nVal; + return 4; +} + +bool +RTMP_ReadPacket(RTMP *r, RTMPPacket *packet) +{ + char hbuf[RTMP_MAX_HEADER_SIZE] = { 0 }, *header = hbuf; + + RTMP_Log(RTMP_LOGDEBUG2, "%s: fd=%d", __FUNCTION__, r->m_sb.sb_socket); + + if (ReadN(r, hbuf, 1) == 0) + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header", __FUNCTION__); + return false; + } + + packet->m_headerType = (hbuf[0] & 0xc0) >> 6; + packet->m_nChannel = (hbuf[0] & 0x3f); + header++; + if (packet->m_nChannel == 0) + { + if (ReadN(r, &hbuf[1], 1) != 1) + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header 2nd byte", + __FUNCTION__); + return false; + } + packet->m_nChannel = (unsigned)hbuf[1]; + packet->m_nChannel += 64; + header++; + } + else if (packet->m_nChannel == 1) + { + int tmp; + if (ReadN(r, &hbuf[1], 2) != 2) + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header 3nd byte", + __FUNCTION__); + return false; + } + tmp = (((unsigned)hbuf[2]) << 8) + (unsigned)hbuf[1]; + packet->m_nChannel = tmp + 64; + RTMP_Log(RTMP_LOGDEBUG, "%s, m_nChannel: %0x", __FUNCTION__, packet->m_nChannel); + header += 2; + } + + int nSize = packetSize[packet->m_headerType], hSize; + + if (nSize == RTMP_LARGE_HEADER_SIZE) // if we get a full header the timestamp is absolute + packet->m_hasAbsTimestamp = true; + + else if (nSize < RTMP_LARGE_HEADER_SIZE) + { // using values from the last message of this channel + if (r->m_vecChannelsIn[packet->m_nChannel]) + memcpy(packet, r->m_vecChannelsIn[packet->m_nChannel], + sizeof(RTMPPacket)); + } + + nSize--; + + if (nSize > 0 && ReadN(r, header, nSize) != nSize) + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header. type: %x", + __FUNCTION__, (unsigned int)hbuf[0]); + return false; + } + + hSize = nSize + (header - hbuf); + + if (nSize >= 3) + { + packet->m_nTimeStamp = AMF_DecodeInt24(header); + + //RTMP_Log(RTMP_LOGDEBUG, "%s, reading RTMP packet chunk on channel %x, headersz %i, timestamp %i, abs timestamp %i", __FUNCTION__, packet.m_nChannel, nSize, packet.m_nTimeStamp, packet.m_hasAbsTimestamp); + + if (nSize >= 6) + { + packet->m_nBodySize = AMF_DecodeInt24(header + 3); + packet->m_nBytesRead = 0; + RTMPPacket_Free(packet); + + if (nSize > 6) + { + packet->m_packetType = header[6]; + + if (nSize == 11) + packet->m_nInfoField2 = DecodeInt32LE(header + 7); + } + } + if (packet->m_nTimeStamp == 0xffffff) + { + if (ReadN(r, header + nSize, 4) != 4) + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to read extended timestamp", + __FUNCTION__); + return false; + } + packet->m_nTimeStamp = AMF_DecodeInt32(header + nSize); + hSize += 4; + } + } + + RTMP_LogHexString(RTMP_LOGDEBUG2, hbuf, hSize); + + bool didAlloc = false; + if (packet->m_nBodySize > 0 && packet->m_body == NULL) + { + if (!RTMPPacket_Alloc(packet, packet->m_nBodySize)) + { + RTMP_Log(RTMP_LOGDEBUG, "%s, failed to allocate packet", __FUNCTION__); + return false; + } + didAlloc = true; + packet->m_headerType = (hbuf[0] & 0xc0) >> 6; + } + + int nToRead = packet->m_nBodySize - packet->m_nBytesRead; + int nChunk = r->m_inChunkSize; + if (nToRead < nChunk) + nChunk = nToRead; + + /* Does the caller want the raw chunk? */ + if (packet->m_chunk) + { + packet->m_chunk->c_headerSize = hSize; + memcpy(packet->m_chunk->c_header, hbuf, hSize); + packet->m_chunk->c_chunk = packet->m_body + packet->m_nBytesRead; + packet->m_chunk->c_chunkSize = nChunk; + } + + if (ReadN(r, packet->m_body + packet->m_nBytesRead, nChunk) != nChunk) + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet body. len: %lu", + __FUNCTION__, packet->m_nBodySize); + return false; + } + + RTMP_LogHexString(RTMP_LOGDEBUG2, packet->m_body + packet->m_nBytesRead, nChunk); + + packet->m_nBytesRead += nChunk; + + // keep the packet as ref for other packets on this channel + if (!r->m_vecChannelsIn[packet->m_nChannel]) + r->m_vecChannelsIn[packet->m_nChannel] = malloc(sizeof(RTMPPacket)); + memcpy(r->m_vecChannelsIn[packet->m_nChannel], packet, sizeof(RTMPPacket)); + + if (RTMPPacket_IsReady(packet)) + { + // make packet's timestamp absolute + if (!packet->m_hasAbsTimestamp) + packet->m_nTimeStamp += r->m_channelTimestamp[packet->m_nChannel]; // timestamps seem to be always relative!! + + r->m_channelTimestamp[packet->m_nChannel] = packet->m_nTimeStamp; + + // reset the data from the stored packet. we keep the header since we may use it later if a new packet for this channel + // arrives and requests to re-use some info (small packet header) + r->m_vecChannelsIn[packet->m_nChannel]->m_body = NULL; + r->m_vecChannelsIn[packet->m_nChannel]->m_nBytesRead = 0; + r->m_vecChannelsIn[packet->m_nChannel]->m_hasAbsTimestamp = false; // can only be false if we reuse header + } + else + { + packet->m_body = NULL; /* so it won't be erased on free */ + } + + return true; +} + +#ifndef CRYPTO +static bool +HandShake(RTMP *r, bool FP9HandShake) +{ + int i; + char clientbuf[RTMP_SIG_SIZE + 1], *clientsig = clientbuf + 1; + char serversig[RTMP_SIG_SIZE]; + + clientbuf[0] = 0x03; // not encrypted + + uint32_t uptime = htonl(RTMP_GetTime()); + memcpy(clientsig, &uptime, 4); + + memset(&clientsig[4], 0, 4); + +#ifdef _DEBUG + for (i = 8; i < RTMP_SIG_SIZE; i++) + clientsig[i] = 0xff; +#else + for (i = 8; i < RTMP_SIG_SIZE; i++) + clientsig[i] = (char)(rand() % 256); +#endif + + if (!WriteN(r, clientbuf, RTMP_SIG_SIZE + 1)) + return false; + + char type; + if (ReadN(r, &type, 1) != 1) // 0x03 or 0x06 + return false; + + RTMP_Log(RTMP_LOGDEBUG, "%s: Type Answer : %02X", __FUNCTION__, type); + + if (type != clientbuf[0]) + RTMP_Log(RTMP_LOGWARNING, "%s: Type mismatch: client sent %d, server answered %d", + __FUNCTION__, clientbuf[0], type); + + if (ReadN(r, serversig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) + return false; + + // decode server response + uint32_t suptime; + + memcpy(&suptime, serversig, 4); + suptime = ntohl(suptime); + + RTMP_Log(RTMP_LOGDEBUG, "%s: Server Uptime : %d", __FUNCTION__, suptime); + RTMP_Log(RTMP_LOGDEBUG, "%s: FMS Version : %d.%d.%d.%d", __FUNCTION__, + serversig[4], serversig[5], serversig[6], serversig[7]); + + // 2nd part of handshake + if (!WriteN(r, serversig, RTMP_SIG_SIZE)) + return false; + + if (ReadN(r, serversig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) + return false; + + bool bMatch = (memcmp(serversig, clientsig, RTMP_SIG_SIZE) == 0); + if (!bMatch) + { + RTMP_Log(RTMP_LOGWARNING, "%s, client signature does not match!", __FUNCTION__); + } + return true; +} + +static bool +SHandShake(RTMP *r) +{ + int i; + char serverbuf[RTMP_SIG_SIZE + 1], *serversig = serverbuf + 1; + char clientsig[RTMP_SIG_SIZE]; + uint32_t uptime; + + if (ReadN(r, serverbuf, 1) != 1) // 0x03 or 0x06 + return false; + + RTMP_Log(RTMP_LOGDEBUG, "%s: Type Request : %02X", __FUNCTION__, serverbuf[0]); + + if (serverbuf[0] != 3) + { + RTMP_Log(RTMP_LOGERROR, "%s: Type unknown: client sent %02X", + __FUNCTION__, serverbuf[0]); + return false; + } + + uptime = htonl(RTMP_GetTime()); + memcpy(serversig, &uptime, 4); + + memset(&serversig[4], 0, 4); +#ifdef _DEBUG + for (i = 8; i < RTMP_SIG_SIZE; i++) + serversig[i] = 0xff; +#else + for (i = 8; i < RTMP_SIG_SIZE; i++) + serversig[i] = (char)(rand() % 256); +#endif + + if (!WriteN(r, serverbuf, RTMP_SIG_SIZE + 1)) + return false; + + if (ReadN(r, clientsig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) + return false; + + // decode client response + + memcpy(&uptime, clientsig, 4); + uptime = ntohl(uptime); + + RTMP_Log(RTMP_LOGDEBUG, "%s: Client Uptime : %d", __FUNCTION__, uptime); + RTMP_Log(RTMP_LOGDEBUG, "%s: Player Version: %d.%d.%d.%d", __FUNCTION__, + clientsig[4], clientsig[5], clientsig[6], clientsig[7]); + + // 2nd part of handshake + if (!WriteN(r, clientsig, RTMP_SIG_SIZE)) + return false; + + if (ReadN(r, clientsig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) + return false; + + bool bMatch = (memcmp(serversig, clientsig, RTMP_SIG_SIZE) == 0); + if (!bMatch) + { + RTMP_Log(RTMP_LOGWARNING, "%s, client signature does not match!", __FUNCTION__); + } + return true; +} +#endif + +bool +RTMP_SendChunk(RTMP *r, RTMPChunk *chunk) +{ + bool wrote; + char hbuf[RTMP_MAX_HEADER_SIZE]; + + RTMP_Log(RTMP_LOGDEBUG2, "%s: fd=%d, size=%d", __FUNCTION__, r->m_sb.sb_socket, + chunk->c_chunkSize); + RTMP_LogHexString(RTMP_LOGDEBUG2, chunk->c_header, chunk->c_headerSize); + if (chunk->c_chunkSize) + { + char *ptr = chunk->c_chunk - chunk->c_headerSize; + RTMP_LogHexString(RTMP_LOGDEBUG2, chunk->c_chunk, chunk->c_chunkSize); + /* save header bytes we're about to overwrite */ + memcpy(hbuf, ptr, chunk->c_headerSize); + memcpy(ptr, chunk->c_header, chunk->c_headerSize); + wrote = WriteN(r, ptr, chunk->c_headerSize + chunk->c_chunkSize); + memcpy(ptr, hbuf, chunk->c_headerSize); + } + else + wrote = WriteN(r, chunk->c_header, chunk->c_headerSize); + return wrote; +} + +bool +RTMP_SendPacket(RTMP *r, RTMPPacket *packet, bool queue) +{ + const RTMPPacket *prevPacket = r->m_vecChannelsOut[packet->m_nChannel]; + uint32_t last = 0; + if (prevPacket && packet->m_headerType != RTMP_PACKET_SIZE_LARGE) + { + // compress a bit by using the prev packet's attributes + if (prevPacket->m_nBodySize == packet->m_nBodySize + && prevPacket->m_packetType == packet->m_packetType + && packet->m_headerType == RTMP_PACKET_SIZE_MEDIUM) + packet->m_headerType = RTMP_PACKET_SIZE_SMALL; + + if (prevPacket->m_nTimeStamp == packet->m_nTimeStamp + && packet->m_headerType == RTMP_PACKET_SIZE_SMALL) + packet->m_headerType = RTMP_PACKET_SIZE_MINIMUM; + last = prevPacket->m_nTimeStamp; + } + + if (packet->m_headerType > 3) // sanity + { + RTMP_Log(RTMP_LOGERROR, "sanity failed!! trying to send header of type: 0x%02x.", + (unsigned char)packet->m_headerType); + return false; + } + + int nSize = packetSize[packet->m_headerType]; + int hSize = nSize, cSize = 0; + char *header, *hptr, *hend, hbuf[RTMP_MAX_HEADER_SIZE], c; + uint32_t t = packet->m_nTimeStamp - last; + + if (packet->m_body) + { + header = packet->m_body - nSize; + hend = packet->m_body; + } + else + { + header = hbuf + 6; + hend = hbuf + sizeof(hbuf); + } + + if (packet->m_nChannel > 319) + cSize = 2; + else if (packet->m_nChannel > 63) + cSize = 1; + if (cSize) + { + header -= cSize; + hSize += cSize; + } + + if (nSize > 1 && t >= 0xffffff) + { + header -= 4; + hSize += 4; + } + + hptr = header; + c = packet->m_headerType << 6; + switch (cSize) + { + case 0: + c |= packet->m_nChannel; + break; + case 1: + break; + case 2: + c |= 1; + break; + } + *hptr++ = c; + if (cSize) + { + int tmp = packet->m_nChannel - 64; + *hptr++ = tmp & 0xff; + if (cSize == 2) + *hptr++ = tmp >> 8; + } + + if (nSize > 1) + { + hptr = AMF_EncodeInt24(hptr, hend, t > 0xffffff ? 0xffffff : t); + } + + if (nSize > 4) + { + hptr = AMF_EncodeInt24(hptr, hend, packet->m_nBodySize); + *hptr++ = packet->m_packetType; + } + + if (nSize > 8) + hptr += EncodeInt32LE(hptr, packet->m_nInfoField2); + + if (nSize > 1 && t >= 0xffffff) + hptr = AMF_EncodeInt32(hptr, hend, t); + + nSize = packet->m_nBodySize; + char *buffer = packet->m_body, *tbuf = NULL, *toff = NULL; + int nChunkSize = r->m_outChunkSize; + int tlen; + + RTMP_Log(RTMP_LOGDEBUG2, "%s: fd=%d, size=%d", __FUNCTION__, r->m_sb.sb_socket, + nSize); + /* send all chunks in one HTTP request */ + if (r->Link.protocol & RTMP_FEATURE_HTTP) + { + int chunks = (nSize+nChunkSize-1) / nChunkSize; + if (chunks > 1) + { + tlen = chunks * (cSize + 1) + nSize + hSize; + tbuf = malloc(tlen); + if (!tbuf) + return false; + toff = tbuf; + } + } + while (nSize + hSize) + { + int wrote; + + if (nSize < nChunkSize) + nChunkSize = nSize; + + RTMP_LogHexString(RTMP_LOGDEBUG2, header, hSize); + RTMP_LogHexString(RTMP_LOGDEBUG2, buffer, nChunkSize); + if (tbuf) + { + memcpy(toff, header, nChunkSize + hSize); + toff += nChunkSize + hSize; + } + else + { + wrote = WriteN(r, header, nChunkSize + hSize); + if (!wrote) + return false; + } + nSize -= nChunkSize; + buffer += nChunkSize; + hSize = 0; + + if (nSize > 0) + { + header = buffer - 1; + hSize = 1; + if (cSize) + { + header -= cSize; + hSize += cSize; + } + *header = (0xc0 | c); + if (cSize) + { + int tmp = packet->m_nChannel - 64; + header[1] = tmp & 0xff; + if (cSize == 2) + header[2] = tmp >> 8; + } + } + } + if (tbuf) + { + int wrote = WriteN(r, tbuf, toff-tbuf); + free(tbuf); + tbuf = NULL; + if (!wrote) + return false; + } + + /* we invoked a remote method */ + if (packet->m_packetType == 0x14) + { + AVal method; + AMF_DecodeString(packet->m_body + 1, &method); + RTMP_Log(RTMP_LOGDEBUG, "Invoking %s", method.av_val); + /* keep it in call queue till result arrives */ + if (queue) + AV_queue(&r->m_methodCalls, &r->m_numCalls, &method); + } + + if (!r->m_vecChannelsOut[packet->m_nChannel]) + r->m_vecChannelsOut[packet->m_nChannel] = malloc(sizeof(RTMPPacket)); + memcpy(r->m_vecChannelsOut[packet->m_nChannel], packet, sizeof(RTMPPacket)); + return true; +} + +bool +RTMP_Serve(RTMP *r) +{ + return SHandShake(r); +} + +void +RTMP_Close(RTMP *r) +{ + int i; + + if (RTMP_IsConnected(r)) + { + if (r->m_stream_id > 0) + { + if ((r->Link.protocol & RTMP_FEATURE_WRITE)) + SendFCUnpublish(r); + i = r->m_stream_id; + r->m_stream_id = 0; + SendDeleteStream(r, i); + } + if (r->m_clientID.av_val) + { + HTTP_Post(r, RTMPT_CLOSE, "", 1); + free(r->m_clientID.av_val); + r->m_clientID.av_val = NULL; + r->m_clientID.av_len = 0; + } + RTMPSockBuf_Close(&r->m_sb); + } + + r->m_stream_id = -1; + r->m_sb.sb_socket = -1; + r->m_nBWCheckCounter = 0; + r->m_nBytesIn = 0; + r->m_nBytesInSent = 0; + + free(r->m_read.buf); + r->m_read.buf = NULL; + r->m_read.dataType = 0; + r->m_read.flags = 0; + r->m_read.status = 0; + r->m_read.nResumeTS = 0; + r->m_read.nIgnoredFrameCounter = 0; + r->m_read.nIgnoredFlvFrameCounter = 0; + + r->m_write.m_nBytesRead = 0; + RTMPPacket_Free(&r->m_write); + + for (i = 0; i < RTMP_CHANNELS; i++) + { + if (r->m_vecChannelsIn[i]) + { + RTMPPacket_Free(r->m_vecChannelsIn[i]); + free(r->m_vecChannelsIn[i]); + r->m_vecChannelsIn[i] = NULL; + } + if (r->m_vecChannelsOut[i]) + { + free(r->m_vecChannelsOut[i]); + r->m_vecChannelsOut[i] = NULL; + } + } + AV_clear(r->m_methodCalls, r->m_numCalls); + r->m_methodCalls = NULL; + r->m_numCalls = 0; + r->m_numInvokes = 0; + + r->m_bPlaying = false; + r->m_sb.sb_size = 0; + + r->m_msgCounter = 0; + r->m_resplen = 0; + r->m_unackd = 0; + + free(r->Link.playpath0.av_val); + r->Link.playpath0.av_val = NULL; + +#ifdef CRYPTO + if (r->Link.dh) + { + MDH_free(r->Link.dh); + r->Link.dh = NULL; + } + if (r->Link.rc4keyIn) + { + free(r->Link.rc4keyIn); + r->Link.rc4keyIn = NULL; + } + if (r->Link.rc4keyOut) + { + free(r->Link.rc4keyOut); + r->Link.rc4keyOut = NULL; + } +#endif +} + +int +RTMPSockBuf_Fill(RTMPSockBuf *sb) +{ + int nBytes; + + if (!sb->sb_size) + sb->sb_start = sb->sb_buf; + + while (1) + { + nBytes = sizeof(sb->sb_buf) - sb->sb_size - (sb->sb_start - sb->sb_buf); +#ifdef CRYPTO + if (sb->sb_ssl) + { + nBytes = TLS_read(sb->sb_ssl, sb->sb_start + sb->sb_size, nBytes); + } + else +#endif + { + nBytes = recv(sb->sb_socket, sb->sb_start + sb->sb_size, nBytes, 0); + } + if (nBytes != -1) + { + sb->sb_size += nBytes; + } + else + { + int sockerr = GetSockError(); + RTMP_Log(RTMP_LOGDEBUG, "%s, recv returned %d. GetSockError(): %d (%s)", + __FUNCTION__, nBytes, sockerr, strerror(sockerr)); + if (sockerr == EINTR && !RTMP_ctrlC) + continue; + + if (sockerr == EWOULDBLOCK || sockerr == EAGAIN) + { + sb->sb_timedout = true; + nBytes = 0; + } + } + break; + } + + return nBytes; +} + +int +RTMPSockBuf_Send(RTMPSockBuf *sb, const char *buf, int len) +{ + int rc; + +#ifdef _DEBUG + fwrite(buf, 1, len, netstackdump); +#endif + +#ifdef CRYPTO + if (sb->sb_ssl) + { + rc = TLS_write(sb->sb_ssl, buf, len); + } + else +#endif + { + rc = send(sb->sb_socket, buf, len, 0); + } + return rc; +} + +int +RTMPSockBuf_Close(RTMPSockBuf *sb) +{ +#ifdef CRYPTO + if (sb->sb_ssl) + { + TLS_shutdown(sb->sb_ssl); + TLS_close(sb->sb_ssl); + sb->sb_ssl = NULL; + } +#endif + return closesocket(sb->sb_socket); +} + +#define HEX2BIN(a) (((a)&0x40)?((a)&0xf)+9:((a)&0xf)) + +static void +DecodeTEA(AVal *key, AVal *text) +{ + uint32_t *v, k[4] = { 0 }, u; + uint32_t z, y, sum = 0, e, DELTA = 0x9e3779b9; + int32_t p, q; + int i, n; + unsigned char *ptr, *out; + + /* prep key: pack 1st 16 chars into 4 LittleEndian ints */ + ptr = (unsigned char *)key->av_val; + u = 0; + n = 0; + v = k; + p = key->av_len > 16 ? 16 : key->av_len; + for (i = 0; i < p; i++) + { + u |= ptr[i] << (n * 8); + if (n == 3) + { + *v++ = u; + u = 0; + n = 0; + } + else + { + n++; + } + } + /* any trailing chars */ + if (u) + *v = u; + + /* prep text: hex2bin, multiples of 4 */ + n = (text->av_len + 7) / 8; + out = malloc(n * 8); + ptr = (unsigned char *)text->av_val; + v = (uint32_t *) out; + for (i = 0; i < n; i++) + { + u = (HEX2BIN(ptr[0]) << 4) + HEX2BIN(ptr[1]); + u |= ((HEX2BIN(ptr[2]) << 4) + HEX2BIN(ptr[3])) << 8; + u |= ((HEX2BIN(ptr[4]) << 4) + HEX2BIN(ptr[5])) << 16; + u |= ((HEX2BIN(ptr[6]) << 4) + HEX2BIN(ptr[7])) << 24; + *v++ = u; + ptr += 8; + } + v = (uint32_t *) out; + + /* http://www.movable-type.co.uk/scripts/tea-block.html */ +#define MX (((z>>5)^(y<<2)) + ((y>>3)^(z<<4))) ^ ((sum^y) + (k[(p&3)^e]^z)); + z = v[n - 1]; + y = v[0]; + q = 6 + 52 / n; + sum = q * DELTA; + while (sum != 0) + { + e = sum >> 2 & 3; + for (p = n - 1; p > 0; p--) + z = v[p - 1], y = v[p] -= MX; + z = v[n - 1]; + y = v[0] -= MX; + sum -= DELTA; + } + + text->av_len /= 2; + memcpy(text->av_val, out, text->av_len); + free(out); +} + +static int +HTTP_Post(RTMP *r, RTMPTCmd cmd, const char *buf, int len) +{ + char hbuf[512]; + int hlen = snprintf(hbuf, sizeof(hbuf), "POST /%s%s/%d HTTP/1.1\r\n" + "Host: %.*s:%d\r\n" + "Accept: */*\r\n" + "User-Agent: Shockwave Flash\n" + "Connection: Keep-Alive\n" + "Cache-Control: no-cache\r\n" + "Content-type: application/x-fcs\r\n" + "Content-length: %d\r\n\r\n", RTMPT_cmds[cmd], + r->m_clientID.av_val ? r->m_clientID.av_val : "", + r->m_msgCounter, r->Link.hostname.av_len, r->Link.hostname.av_val, + r->Link.port, len); + RTMPSockBuf_Send(&r->m_sb, hbuf, hlen); + hlen = RTMPSockBuf_Send(&r->m_sb, buf, len); + r->m_msgCounter++; + r->m_unackd++; + return hlen; +} + +static int +HTTP_read(RTMP *r, int fill) +{ + char *ptr; + int hlen; + + if (fill) + RTMPSockBuf_Fill(&r->m_sb); + if (r->m_sb.sb_size < 144) + return -1; + if (strncmp(r->m_sb.sb_start, "HTTP/1.1 200 ", 13)) + return -1; + ptr = strstr(r->m_sb.sb_start, "Content-Length:"); + if (!ptr) + return -1; + hlen = atoi(ptr+16); + ptr = strstr(ptr, "\r\n\r\n"); + if (!ptr) + return -1; + ptr += 4; + r->m_sb.sb_size -= ptr - r->m_sb.sb_start; + r->m_sb.sb_start = ptr; + r->m_unackd--; + + if (!r->m_clientID.av_val) + { + r->m_clientID.av_len = hlen; + r->m_clientID.av_val = malloc(hlen+1); + if (!r->m_clientID.av_val) + return -1; + r->m_clientID.av_val[0] = '/'; + memcpy(r->m_clientID.av_val+1, ptr, hlen-1); + r->m_sb.sb_size = 0; + } + else + { + r->m_polling = *ptr++; + r->m_resplen = hlen - 1; + r->m_sb.sb_start++; + r->m_sb.sb_size--; + } + return 0; +} + +#define MAX_IGNORED_FRAMES 50 + +/* Read from the stream until we get a media packet. + * Returns -3 if Play.Close/Stop, -2 if fatal error, -1 if no more media + * packets, 0 if ignorable error, >0 if there is a media packet + */ +static int +Read_1_Packet(RTMP *r, char *buf, int buflen) +{ + uint32_t prevTagSize = 0; + int rtnGetNextMediaPacket = 0, ret = RTMP_READ_EOF; + RTMPPacket packet = { 0 }; + bool recopy = false; + + rtnGetNextMediaPacket = RTMP_GetNextMediaPacket(r, &packet); + while (rtnGetNextMediaPacket) + { + char *packetBody = packet.m_body; + unsigned int nPacketLen = packet.m_nBodySize; + + /* Return -3 if this was completed nicely with invoke message + * Play.Stop or Play.Complete + */ + if (rtnGetNextMediaPacket == 2) + { + RTMP_Log(RTMP_LOGDEBUG, + "Got Play.Complete or Play.Stop from server. " + "Assuming stream is complete"); + ret = RTMP_READ_COMPLETE; + break; + } + + r->m_read.dataType |= (((packet.m_packetType == 0x08) << 2) | + (packet.m_packetType == 0x09)); + + if (packet.m_packetType == 0x09 && nPacketLen <= 5) + { + RTMP_Log(RTMP_LOGWARNING, "ignoring too small video packet: size: %d", + nPacketLen); + ret = RTMP_READ_IGNORE; + break; + } + if (packet.m_packetType == 0x08 && nPacketLen <= 1) + { + RTMP_Log(RTMP_LOGWARNING, "ignoring too small audio packet: size: %d", + nPacketLen); + ret = RTMP_READ_IGNORE; + break; + } + + if (r->m_read.flags & RTMP_READ_SEEKING) + { + ret = RTMP_READ_IGNORE; + break; + } +#ifdef _DEBUG + RTMP_Log(RTMP_LOGDEBUG, "type: %02X, size: %d, TS: %d ms, abs TS: %d", + packet.m_packetType, nPacketLen, packet.m_nTimeStamp, + packet.m_hasAbsTimestamp); + if (packet.m_packetType == 0x09) + RTMP_Log(RTMP_LOGDEBUG, "frametype: %02X", (*packetBody & 0xf0)); +#endif + + if (r->m_read.flags & RTMP_READ_RESUME) + { + /* check the header if we get one */ + if (packet.m_nTimeStamp == 0) + { + if (r->m_read.nMetaHeaderSize > 0 + && packet.m_packetType == 0x12) + { + AMFObject metaObj; + int nRes = + AMF_Decode(&metaObj, packetBody, nPacketLen, false); + if (nRes >= 0) + { + AVal metastring; + AMFProp_GetString(AMF_GetProp(&metaObj, NULL, 0), + &metastring); + + if (AVMATCH(&metastring, &av_onMetaData)) + { + // compare + if ((r->m_read.nMetaHeaderSize != nPacketLen) || + (memcmp + (r->m_read.metaHeader, packetBody, + r->m_read.nMetaHeaderSize) != 0)) + { + ret = RTMP_READ_ERROR; + } + } + AMF_Reset(&metaObj); + if (ret == RTMP_READ_ERROR) + break; + } + } + + /* check first keyframe to make sure we got the right position + * in the stream! (the first non ignored frame) + */ + if (r->m_read.nInitialFrameSize > 0) + { + /* video or audio data */ + if (packet.m_packetType == r->m_read.initialFrameType + && r->m_read.nInitialFrameSize == nPacketLen) + { + /* we don't compare the sizes since the packet can + * contain several FLV packets, just make sure the + * first frame is our keyframe (which we are going + * to rewrite) + */ + if (memcmp + (r->m_read.initialFrame, packetBody, + r->m_read.nInitialFrameSize) == 0) + { + RTMP_Log(RTMP_LOGDEBUG, "Checked keyframe successfully!"); + r->m_read.flags |= RTMP_READ_GOTKF; + /* ignore it! (what about audio data after it? it is + * handled by ignoring all 0ms frames, see below) + */ + ret = RTMP_READ_IGNORE; + break; + } + } + + /* hande FLV streams, even though the server resends the + * keyframe as an extra video packet it is also included + * in the first FLV stream chunk and we have to compare + * it and filter it out !! + */ + if (packet.m_packetType == 0x16) + { + /* basically we have to find the keyframe with the + * correct TS being nResumeTS + */ + unsigned int pos = 0; + uint32_t ts = 0; + + while (pos + 11 < nPacketLen) + { + /* size without header (11) and prevTagSize (4) */ + uint32_t dataSize = + AMF_DecodeInt24(packetBody + pos + 1); + ts = AMF_DecodeInt24(packetBody + pos + 4); + ts |= (packetBody[pos + 7] << 24); + +#ifdef _DEBUG + RTMP_Log(RTMP_LOGDEBUG, + "keyframe search: FLV Packet: type %02X, dataSize: %d, timeStamp: %d ms", + packetBody[pos], dataSize, ts); +#endif + /* ok, is it a keyframe?: + * well doesn't work for audio! + */ + if (packetBody[pos /*6928, test 0 */ ] == + r->m_read.initialFrameType + /* && (packetBody[11]&0xf0) == 0x10 */ ) + { + if (ts == r->m_read.nResumeTS) + { + RTMP_Log(RTMP_LOGDEBUG, + "Found keyframe with resume-keyframe timestamp!"); + if (r->m_read.nInitialFrameSize != dataSize + || memcmp(r->m_read.initialFrame, + packetBody + pos + 11, + r->m_read. + nInitialFrameSize) != 0) + { + RTMP_Log(RTMP_LOGERROR, + "FLV Stream: Keyframe doesn't match!"); + ret = RTMP_READ_ERROR; + break; + } + r->m_read.flags |= RTMP_READ_GOTFLVK; + + /* skip this packet? + * check whether skippable: + */ + if (pos + 11 + dataSize + 4 > nPacketLen) + { + RTMP_Log(RTMP_LOGWARNING, + "Non skipable packet since it doesn't end with chunk, stream corrupt!"); + ret = RTMP_READ_ERROR; + break; + } + packetBody += (pos + 11 + dataSize + 4); + nPacketLen -= (pos + 11 + dataSize + 4); + + goto stopKeyframeSearch; + + } + else if (r->m_read.nResumeTS < ts) + { + /* the timestamp ts will only increase with + * further packets, wait for seek + */ + goto stopKeyframeSearch; + } + } + pos += (11 + dataSize + 4); + } + if (ts < r->m_read.nResumeTS) + { + RTMP_Log(RTMP_LOGERROR, + "First packet does not contain keyframe, all " + "timestamps are smaller than the keyframe " + "timestamp; probably the resume seek failed?"); + } + stopKeyframeSearch: + ; + if (!(r->m_read.flags & RTMP_READ_GOTFLVK)) + { + RTMP_Log(RTMP_LOGERROR, + "Couldn't find the seeked keyframe in this chunk!"); + ret = RTMP_READ_IGNORE; + break; + } + } + } + } + + if (packet.m_nTimeStamp > 0 + && (r->m_read.flags & (RTMP_READ_GOTKF|RTMP_READ_GOTFLVK))) + { + /* another problem is that the server can actually change from + * 09/08 video/audio packets to an FLV stream or vice versa and + * our keyframe check will prevent us from going along with the + * new stream if we resumed. + * + * in this case set the 'found keyframe' variables to true. + * We assume that if we found one keyframe somewhere and were + * already beyond TS > 0 we have written data to the output + * which means we can accept all forthcoming data including the + * change between 08/09 <-> FLV packets + */ + r->m_read.flags |= (RTMP_READ_GOTKF|RTMP_READ_GOTFLVK); + } + + /* skip till we find our keyframe + * (seeking might put us somewhere before it) + */ + if (!(r->m_read.flags & RTMP_READ_GOTKF) && + packet.m_packetType != 0x16) + { + RTMP_Log(RTMP_LOGWARNING, + "Stream does not start with requested frame, ignoring data... "); + r->m_read.nIgnoredFrameCounter++; + if (r->m_read.nIgnoredFrameCounter > MAX_IGNORED_FRAMES) + ret = RTMP_READ_ERROR; /* fatal error, couldn't continue stream */ + else + ret = RTMP_READ_IGNORE; + break; + } + /* ok, do the same for FLV streams */ + if (!(r->m_read.flags & RTMP_READ_GOTFLVK) && + packet.m_packetType == 0x16) + { + RTMP_Log(RTMP_LOGWARNING, + "Stream does not start with requested FLV frame, ignoring data... "); + r->m_read.nIgnoredFlvFrameCounter++; + if (r->m_read.nIgnoredFlvFrameCounter > MAX_IGNORED_FRAMES) + ret = RTMP_READ_ERROR; + else + ret = RTMP_READ_IGNORE; + break; + } + + /* we have to ignore the 0ms frames since these are the first + * keyframes; we've got these so don't mess around with multiple + * copies sent by the server to us! (if the keyframe is found at a + * later position there is only one copy and it will be ignored by + * the preceding if clause) + */ + if (!(r->m_read.flags & RTMP_READ_NO_IGNORE) && + packet.m_packetType != 0x16) + { /* exclude type 0x16 (FLV) since it can + * contain several FLV packets */ + if (packet.m_nTimeStamp == 0) + { + ret = RTMP_READ_IGNORE; + break; + } + else + { + /* stop ignoring packets */ + r->m_read.flags |= RTMP_READ_NO_IGNORE; + } + } + } + + /* calculate packet size and allocate slop buffer if necessary */ + unsigned int size = nPacketLen + + ((packet.m_packetType == 0x08 || packet.m_packetType == 0x09 + || packet.m_packetType == 0x12) ? 11 : 0) + + (packet.m_packetType != 0x16 ? 4 : 0); + + char *ptr, *pend; + if (size + 4 > buflen) + { + /* the extra 4 is for the case of an FLV stream without a last + * prevTagSize (we need extra 4 bytes to append it) */ + r->m_read.buf = malloc(size + 4); + if (r->m_read.buf == 0) + { + RTMP_Log(RTMP_LOGERROR, "Couldn't allocate memory!"); + ret = RTMP_READ_ERROR; // fatal error + break; + } + recopy = true; + ptr = r->m_read.buf; + } + else + { + ptr = buf; + } + pend = ptr + size + 4; + + /* use to return timestamp of last processed packet */ + uint32_t nTimeStamp = 0; + + /* audio (0x08), video (0x09) or metadata (0x12) packets : + * construct 11 byte header then add rtmp packet's data */ + if (packet.m_packetType == 0x08 || packet.m_packetType == 0x09 + || packet.m_packetType == 0x12) + { + nTimeStamp = r->m_read.nResumeTS + packet.m_nTimeStamp; + prevTagSize = 11 + nPacketLen; + + *ptr = packet.m_packetType; + ptr++; + ptr = AMF_EncodeInt24(ptr, pend, nPacketLen); + + /*if(packet.m_packetType == 0x09) { // video + + // H264 fix: + if((packetBody[0] & 0x0f) == 7) { // CodecId = H264 + uint8_t packetType = *(packetBody+1); + + uint32_t ts = AMF_DecodeInt24(packetBody+2); // composition time + int32_t cts = (ts+0xff800000)^0xff800000; + RTMP_Log(RTMP_LOGDEBUG, "cts : %d\n", cts); + + nTimeStamp -= cts; + // get rid of the composition time + CRTMP::EncodeInt24(packetBody+2, 0); + } + RTMP_Log(RTMP_LOGDEBUG, "VIDEO: nTimeStamp: 0x%08X (%d)\n", nTimeStamp, nTimeStamp); + } */ + + ptr = AMF_EncodeInt24(ptr, pend, nTimeStamp); + *ptr = (char)((nTimeStamp & 0xFF000000) >> 24); + ptr++; + + /* stream id */ + ptr = AMF_EncodeInt24(ptr, pend, 0); + } + + memcpy(ptr, packetBody, nPacketLen); + unsigned int len = nPacketLen; + + /* correct tagSize and obtain timestamp if we have an FLV stream */ + if (packet.m_packetType == 0x16) + { + unsigned int pos = 0; + + while (pos + 11 < nPacketLen) + { + /* size without header (11) and without prevTagSize (4) */ + uint32_t dataSize = AMF_DecodeInt24(packetBody + pos + 1); + nTimeStamp = AMF_DecodeInt24(packetBody + pos + 4); + nTimeStamp |= (packetBody[pos + 7] << 24); + + /* + CRTMP::EncodeInt24(ptr+pos+4, nTimeStamp); + ptr[pos+7] = (nTimeStamp>>24)&0xff;// */ + + /* set data type */ + r->m_read.dataType |= (((*(packetBody + pos) == 0x08) << 2) | + (*(packetBody + pos) == 0x09)); + + if (pos + 11 + dataSize + 4 > nPacketLen) + { + if (pos + 11 + dataSize > nPacketLen) + { + RTMP_Log(RTMP_LOGERROR, + "Wrong data size (%lu), stream corrupted, aborting!", + dataSize); + ret = RTMP_READ_ERROR; + break; + } + RTMP_Log(RTMP_LOGWARNING, "No tagSize found, appending!"); + + /* we have to append a last tagSize! */ + prevTagSize = dataSize + 11; + AMF_EncodeInt32(ptr + pos + 11 + dataSize, pend, + prevTagSize); + size += 4; + len += 4; + } + else + { + prevTagSize = + AMF_DecodeInt32(packetBody + pos + 11 + dataSize); + +#ifdef _DEBUG + RTMP_Log(RTMP_LOGDEBUG, + "FLV Packet: type %02X, dataSize: %lu, tagSize: %lu, timeStamp: %lu ms", + (unsigned char)packetBody[pos], dataSize, prevTagSize, + nTimeStamp); +#endif + + if (prevTagSize != (dataSize + 11)) + { +#ifdef _DEBUG + RTMP_Log(RTMP_LOGWARNING, + "Tag and data size are not consitent, writing tag size according to dataSize+11: %d", + dataSize + 11); +#endif + + prevTagSize = dataSize + 11; + AMF_EncodeInt32(ptr + pos + 11 + dataSize, pend, + prevTagSize); + } + } + + pos += prevTagSize + 4; //(11+dataSize+4); + } + } + ptr += len; + + if (packet.m_packetType != 0x16) + { + /* FLV tag packets contain their own prevTagSize */ + AMF_EncodeInt32(ptr, pend, prevTagSize); + } + + /* In non-live this nTimeStamp can contain an absolute TS. + * Update ext timestamp with this absolute offset in non-live mode + * otherwise report the relative one + */ + // RTMP_LogPrintf("\nDEBUG: type: %02X, size: %d, pktTS: %dms, TS: %dms, bLiveStream: %d", packet.m_packetType, nPacketLen, packet.m_nTimeStamp, nTimeStamp, bLiveStream); + r->m_read.timestamp = r->Link.bLiveStream ? packet.m_nTimeStamp : nTimeStamp; + + ret = size; + break; + } + + if (rtnGetNextMediaPacket) + RTMPPacket_Free(&packet); + + if (recopy) + { + memcpy(buf, r->m_read.buf, buflen); + r->m_read.bufpos = r->m_read.buf + buflen; + r->m_read.buflen = ret - buflen; + } + return ret; +} + +static const char flvHeader[] = { 'F', 'L', 'V', 0x01, + 0x00, /* 0x04 == audio, 0x01 == video */ + 0x00, 0x00, 0x00, 0x09, + 0x00, 0x00, 0x00, 0x00 +}; + +#define HEADERBUF (128*1024) +int +RTMP_Read(RTMP *r, char *buf, int size) +{ + int nRead = 0, total = 0; + + /* can't continue */ + if (r->m_read.status < 0) + return -1; + + /* first time thru */ + if (!(r->m_read.flags & RTMP_READ_HEADER)) + { + if (!(r->m_read.flags & RTMP_READ_RESUME)) + { + char *mybuf = malloc(HEADERBUF); + r->m_read.buf = mybuf; + r->m_read.buflen = HEADERBUF; + + memcpy(mybuf, flvHeader, sizeof(flvHeader)); + r->m_read.buf += sizeof(flvHeader); + r->m_read.buflen -= sizeof(flvHeader); + + while (r->m_read.timestamp == 0) + { + nRead = Read_1_Packet(r, r->m_read.buf, r->m_read.buflen); + if (nRead < 0) + { + free(mybuf); + r->m_read.buf = NULL; + r->m_read.buflen = 0; + r->m_read.status = nRead; + return -1; + } + r->m_read.buf += nRead; + r->m_read.buflen -= nRead; + if (r->m_read.dataType == 5) + break; + } + mybuf[4] = r->m_read.dataType; + r->m_read.buflen = r->m_read.buf - mybuf; + r->m_read.buf = mybuf; + r->m_read.bufpos = mybuf; + } + r->m_read.flags |= RTMP_READ_HEADER; + } + + if ((r->m_read.flags & RTMP_READ_SEEKING) && r->m_read.buf) + { + /* drop whatever's here */ + free(r->m_read.buf); + r->m_read.buf = NULL; + r->m_read.bufpos = NULL; + r->m_read.buflen = 0; + } + + /* If there's leftover data buffered, use it up */ + if (r->m_read.buf) + { + nRead = r->m_read.buflen; + if (nRead > size) + nRead = size; + memcpy(buf, r->m_read.bufpos, nRead); + r->m_read.buflen -= nRead; + if (!r->m_read.buflen) + { + free(r->m_read.buf); + r->m_read.buf = NULL; + r->m_read.bufpos = NULL; + } + else + { + r->m_read.bufpos += nRead; + } + buf += nRead; + total += nRead; + size -= nRead; + } + + while (size > 0 && (nRead = Read_1_Packet(r, buf, size)) >= 0) + { + buf += nRead; + total += nRead; + size -= nRead; + } + if (nRead < 0) + r->m_read.status = nRead; + + if (size < 0) + total += size; + return total; +} + +static const AVal av_setDataFrame = AVC("@setDataFrame"); + +int +RTMP_Write(RTMP *r, char *buf, int size) +{ + RTMPPacket *pkt = &r->m_write; + char *pend, *enc; + int s2 = size, ret, num; + + pkt->m_nChannel = 0x04; // source channel + pkt->m_nInfoField2 = r->m_stream_id; + + while (s2) + { + if (!pkt->m_nBytesRead) + { + if (size < 11) { + /* FLV pkt too small */ + return 0; + } + + if (buf[0] == 'F' && buf[1] == 'L' && buf[2] == 'V') + { + buf += 13; + s2 -= 13; + } + + pkt->m_packetType = *buf++; + pkt->m_nBodySize = AMF_DecodeInt24(buf); + buf += 3; + pkt->m_nTimeStamp = AMF_DecodeInt24(buf); + buf += 3; + pkt->m_nTimeStamp |= *buf++ << 24; + buf += 3; + s2 -= 11; + + if (((pkt->m_packetType == 0x08 || pkt->m_packetType == 0x09) && + !pkt->m_nTimeStamp) || pkt->m_packetType == 0x12) + { + pkt->m_headerType = RTMP_PACKET_SIZE_LARGE; + if (pkt->m_packetType == 0x12) + pkt->m_nBodySize += 16; + } + else + { + pkt->m_headerType = RTMP_PACKET_SIZE_MEDIUM; + } + + if (!RTMPPacket_Alloc(pkt, pkt->m_nBodySize)) + { + RTMP_Log(RTMP_LOGDEBUG, "%s, failed to allocate packet", __FUNCTION__); + return false; + } + enc = pkt->m_body; + pend = enc + pkt->m_nBodySize; + if (pkt->m_packetType == 0x12) + { + enc = AMF_EncodeString(enc, pend, &av_setDataFrame); + pkt->m_nBytesRead = enc - pkt->m_body; + } + } + else + { + enc = pkt->m_body + pkt->m_nBytesRead; + } + num = pkt->m_nBodySize - pkt->m_nBytesRead; + if (num > s2) + num = s2; + memcpy(enc, buf, num); + pkt->m_nBytesRead += num; + s2 -= num; + buf += num; + if (pkt->m_nBytesRead == pkt->m_nBodySize) + { + ret = RTMP_SendPacket(r, pkt, false); + RTMPPacket_Free(pkt); + pkt->m_nBytesRead = 0; + if (!ret) + return -1; + buf += 4; + s2 -= 4; + if (s2 < 0) + break; + } + } + return size+s2; +} diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/rtmp.cpp xbmc-trunk-28276/xbmc/lib/libRTMP/rtmp.cpp --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/rtmp.cpp 2010-04-04 11:46:52.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/rtmp.cpp 1970-01-01 01:00:00.000000000 +0100 @@ -1,1175 +0,0 @@ -/* - * Copyright (C) 2005-2008 Team XBMC - * http://www.xbmc.org - * - * This file is part of libRTMP. - * - * libRTMP 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. - * - * libRTMP 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 libRTMP; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "PlatformInclude.h" -#include "rtmp.h" -#include "AMFObject.h" -#include - -#ifdef _LINUX - #include - #include - #include - #include - #include - #include - #include -#endif - -#include "URL.h" -#include "utils/log.h" -#include "utils/TimeUtils.h" -#include "utils/EndianSwap.h" - -#define RTMP_SIG_SIZE 1536 -#define RTMP_LARGE_HEADER_SIZE 12 - -#define RTMP_BUFFER_CACHE_SIZE (16*1024) // Needs to fit largest number of bytes recv() may return - -using namespace RTMP_LIB; - -static const int packetSize[] = { 12, 8, 4, 1 }; -#define RTMP_PACKET_SIZE_LARGE 0 -#define RTMP_PACKET_SIZE_MEDIUM 1 -#define RTMP_PACKET_SIZE_SMALL 2 -#define RTMP_PACKET_SIZE_MINIMUM 3 - -CRTMP::CRTMP() : m_socket(INVALID_SOCKET) -{ - Close(); - m_strPlayer = "file:///xbmc.flv"; - m_pBuffer = new char[RTMP_BUFFER_CACHE_SIZE]; - m_nBufferMS = 300; - m_dStartPoint = 0; - m_bIsLive = false; -} - -CRTMP::~CRTMP() -{ - Close(); - delete [] m_pBuffer; -} - -void CRTMP::SetPlayer(const std::string &strPlayer) -{ - m_strPlayer = strPlayer; -} - -void CRTMP::SetPageUrl(const std::string &strPageUrl) -{ - m_strPageUrl = strPageUrl; -} - -void CRTMP::SetPlayPath(const std::string &strPlayPath) -{ - m_strPlayPath = strPlayPath; -} - -void CRTMP::SetTcUrl(const std::string &strTcUrl) -{ - m_strTcUrl = strTcUrl; -} - -void CRTMP::SetLive() -{ - m_bIsLive = true; -} - -void CRTMP::SetBufferMS(int size) -{ - m_nBufferMS = size; -} - -bool CRTMP::Connect(const std::string &strRTMPLink, double dTime) -{ - m_dStartPoint = dTime; - - Close(); - - CURL url(strRTMPLink.c_str()); - - sockaddr_in service; - memset(&service, 0, sizeof(sockaddr_in)); - service.sin_family = AF_INET; - service.sin_addr.s_addr = inet_addr(url.GetHostName().c_str()); - if (service.sin_addr.s_addr == INADDR_NONE) - { - CStdString strIpAddress = ""; - struct hostent *host = gethostbyname(url.GetHostName().c_str()); - if (host == NULL || host->h_addr == NULL) - { - CLog::Log(LOGWARNING, "ERROR: Problem accessing the DNS. (addr: %s)", url.GetHostName().c_str()); - return false; - } - service.sin_addr = *(struct in_addr*)host->h_addr; - } - - if (url.GetPort() == 0) - url.SetPort(1935); - - m_strLink = strRTMPLink; - - service.sin_port = htons(url.GetPort()); - m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (m_socket != INVALID_SOCKET ) - { - if (connect(m_socket, (sockaddr*) &service, sizeof(struct sockaddr)) == SOCKET_ERROR) - { - CLog::Log(LOGERROR,"%s, failed to connect socket. Error: %d. file: %s", __FUNCTION__, WSAGetLastError(), strRTMPLink.c_str()); - Close(); - return false; - } - - if (!HandShake()) - { - CLog::Log(LOGERROR,"%s, handshake failed. file: %s", __FUNCTION__, strRTMPLink.c_str()); - Close(); - return false; - } - - if (!Connect()) - { - CLog::Log(LOGERROR,"%s, RTMP connect failed. file: %s", __FUNCTION__, strRTMPLink.c_str()); - Close(); - return false; - } - } - else - { - CLog::Log(LOGERROR,"%s, failed to create socket. Error: %d. file: %s", __FUNCTION__, WSAGetLastError(), strRTMPLink.c_str()); - return false; - } - - return true; -} - -bool CRTMP::GetNextMediaPacket(RTMPPacket &packet) -{ - bool bHasMediaPacket = false; - while (!bHasMediaPacket && IsConnected() && ReadPacket(packet)) - { - if (!packet.IsReady()) - { - packet.FreePacket(); - continue; - } - - switch (packet.m_packetType) - { - case 0x01: - // chunk size - HandleChangeChunkSize(packet); - break; - - case 0x03: - // bytes read report - CLog::Log(LOGDEBUG,"%s, received: bytes read report", __FUNCTION__); - break; - - case 0x04: - // ping - HandlePing(packet); - break; - - case 0x05: - // server bw - CLog::Log(LOGDEBUG,"%s, received: server BW", __FUNCTION__); - break; - - case 0x06: - // client bw - CLog::Log(LOGDEBUG,"%s, received: client BW", __FUNCTION__); - break; - - case 0x08: - // audio data - //CLog::Log(LOGDEBUG,"%s, received: audio %lu bytes", __FUNCTION__, packet.m_nBodySize); //spamtacular - HandleAudio(packet); - bHasMediaPacket = true; - break; - - case 0x09: - // video data - //CLog::Log(LOGDEBUG,"%s, received: video %lu bytes", __FUNCTION__, packet.m_nBodySize); //spamtacular - HandleVideo(packet); - bHasMediaPacket = true; - break; - - case 0x12: - // metadata (notify) - CLog::Log(LOGDEBUG,"%s, received: notify %lu bytes", __FUNCTION__, packet.m_nBodySize); - HandleMetadata(packet); - bHasMediaPacket = true; - break; - - case 0x14: - // invoke - CLog::Log(LOGDEBUG,"%s, received: invoke %lu bytes", __FUNCTION__, packet.m_nBodySize); - HandleInvoke(packet); - break; - - case 0x16: - // FLV tag(s) - CLog::Log(LOGDEBUG,"%s, received: FLV tag(s) %lu bytes", __FUNCTION__, packet.m_nBodySize); - bHasMediaPacket = true; - break; - - default: - CLog::Log(LOGERROR,"%s, unknown packet type received: 0x%02x", __FUNCTION__, packet.m_packetType); - } - - if (!bHasMediaPacket) - packet.FreePacket(); - } - - if (bHasMediaPacket) - m_bPlaying = true; - - return bHasMediaPacket; -} - -int CRTMP::ReadN(char *buffer, int n) -{ - int nOriginalSize = n; - #ifdef _DEBUG - memset(buffer, 0, n); // only necessary for clarity when debugging - #endif - - char *ptr = buffer; - while (n > 0) - { - int nBytes = 0; - - if (m_nBufferSize == 0) - FillBuffer(); - - int nRead = ((n 0) - { - memcpy(ptr, m_pBufferStart, nRead); - m_pBufferStart += nRead; - m_nBufferSize -= nRead; - nBytes = nRead; - m_nBytesIn += nRead; - if (m_nBytesIn > m_nBytesInSent + (600*1024) ) // report every 600K - SendBytesReceived(); - } - - if (nBytes == 0) - { - CLog::Log(LOGDEBUG,"%s, RTMP socket closed by server", __FUNCTION__); - Close(); - break; - } - - n -= nBytes; - ptr += nBytes; - } - - return nOriginalSize - n; -} - -bool CRTMP::WriteN(const char *buffer, int n) -{ - const char *ptr = buffer; - while (n > 0) - { - int nBytes = send(m_socket, ptr, n, 0); - if (nBytes < 0) - { - CLog::Log(LOGERROR, "%s, RTMP send error %d (%d bytes)", __FUNCTION__, WSAGetLastError(), n); - Close(); - return false; - } - - if (nBytes == 0) - break; - - n -= nBytes; - ptr += nBytes; - } - - return n == 0; -} - -bool CRTMP::Connect() -{ - if (!SendConnectPacket()) - { - CLog::Log(LOGERROR, "%s, failed to send connect RTMP packet", __FUNCTION__); - return false; - } - - return true; -} - -bool CRTMP::SendConnectPacket() -{ - CURL url(m_strLink); - CStdString app = url.GetFileName(); - - CStdString::size_type slistPos = url.GetFileName().Find("slist="); - if ( slistPos == CStdString::npos ) - { - // no slist parameter. send the path as the app - // if URL path contains a slash, use the part up to that as the app - // as we'll send the part after the slash as the thing to play - CStdString::size_type pos_slash = app.find_last_of("/"); - if( pos_slash != CStdString::npos ) - app = app.Left(pos_slash); - } - - CStdString tcURL; - if (m_strTcUrl.empty()) - { - tcURL = url.GetWithoutFilename(); - tcURL += app; - } - else - { - tcURL = m_strTcUrl; - } - - - RTMPPacket packet; - packet.m_nChannel = 0x03; // control channel (invoke) - packet.m_headerType = RTMP_PACKET_SIZE_LARGE; - packet.m_packetType = 0x14; // INVOKE - packet.AllocPacket(4096); - - char *enc = packet.m_body; - enc += EncodeString(enc, "connect"); - enc += EncodeNumber(enc, 1.0); - *enc = 0x03; //Object Datatype - enc++; - enc += EncodeString(enc, "app", app); - enc += EncodeString(enc, "flashVer", "LNX 9,0,115,0"); - enc += EncodeString(enc, "swfUrl", m_strPlayer.c_str()); - enc += EncodeString(enc, "tcUrl", tcURL.c_str()); - enc += EncodeBoolean(enc, "fpad", false); - enc += EncodeNumber(enc, "capabilities", 15.0); - enc += EncodeNumber(enc, "audioCodecs", 1639.0); - enc += EncodeNumber(enc, "videoCodecs", 252.0); - enc += EncodeNumber(enc, "videoFunction", 1.0); - enc += EncodeString(enc, "pageUrl", m_strPageUrl.c_str()); - enc += 2; // end of object - 0x00 0x00 0x09 - *enc = 0x09; - enc++; - packet.m_nBodySize = enc-packet.m_body; - - return SendRTMP(packet); -} - -bool CRTMP::SendCreateStream(double dStreamId) -{ - RTMPPacket packet; - packet.m_nChannel = 0x03; // control channel (invoke) - packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; - packet.m_packetType = 0x14; // INVOKE - - packet.AllocPacket(256); // should be enough - char *enc = packet.m_body; - enc += EncodeString(enc, "createStream"); - enc += EncodeNumber(enc, dStreamId); - *enc = 0x05; // NULL - enc++; - - packet.m_nBodySize = enc - packet.m_body; - - return SendRTMP(packet); -} - -bool CRTMP::SendDeleteStream(double dStreamId) -{ - RTMPPacket packet; - packet.m_nChannel = 0x03; // control channel (invoke) - packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; - packet.m_packetType = 0x14; // INVOKE - - packet.AllocPacket(256); // should be enough - char *enc = packet.m_body; - enc += EncodeString(enc, "deleteStream"); - enc += EncodeNumber(enc, 0.0); - *enc = 0x05; // NULL - enc++; - enc += EncodeNumber(enc, dStreamId); - - packet.m_nBodySize = enc - packet.m_body; - - return SendRTMP(packet); -} - -bool CRTMP::SendPause(bool DoPause, double dTime) -{ - RTMPPacket packet; - packet.m_nChannel = 0x08; // video channel - packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; - packet.m_packetType = 0x14; // invoke - - packet.AllocPacket(256); // should be enough - char *enc = packet.m_body; - enc += EncodeString(enc, "pause"); - enc += EncodeNumber(enc, 0); - *enc = 0x05; // NULL - enc++; - enc += EncodeBoolean(enc, DoPause); - enc += EncodeNumber(enc, (double)dTime/1000); - - packet.m_nBodySize = enc - packet.m_body; - - return SendRTMP(packet); -} - -bool CRTMP::Seek(double dTime) -{ - return SendSeek(dTime); -} - -bool CRTMP::SendSeek(double dTime) -{ - RTMPPacket packet; - packet.m_nChannel = 0x08; // video channel - packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; - packet.m_packetType = 0x14; // invoke - - packet.AllocPacket(256); // should be enough - char *enc = packet.m_body; - enc += EncodeString(enc, "seek"); - enc += EncodeNumber(enc, 0); - *enc = 0x05; // NULL - enc++; - enc += EncodeNumber(enc, dTime); - - packet.m_nBodySize = enc - packet.m_body; - - return SendRTMP(packet); -} - -bool CRTMP::SendServerBW() -{ - RTMPPacket packet; - packet.m_nChannel = 0x02; // control channel (invoke) - packet.m_headerType = RTMP_PACKET_SIZE_LARGE; - packet.m_packetType = 0x05; // Server BW - - packet.AllocPacket(4); - packet.m_nBodySize = 4; - - EncodeInt32(packet.m_body, 0x001312d0); // hard coded for now - return SendRTMP(packet); -} - -bool CRTMP::SendBytesReceived() -{ - RTMPPacket packet; - packet.m_nChannel = 0x02; // control channel (invoke) - packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; - packet.m_packetType = 0x03; // bytes in - - packet.AllocPacket(4); - packet.m_nBodySize = 4; - - EncodeInt32(packet.m_body, m_nBytesIn); // hard coded for now - m_nBytesInSent = m_nBytesIn; - - CLog::Log(LOGDEBUG,"%s, Send bytes report. 0x%x (%d bytes)", __FUNCTION__, (unsigned int)m_nBytesIn, m_nBytesIn); - return SendRTMP(packet); -} - -bool CRTMP::SendCheckBW() -{ - RTMPPacket packet; - packet.m_nChannel = 0x03; // control channel (invoke) - packet.m_headerType = RTMP_PACKET_SIZE_LARGE; - packet.m_packetType = 0x14; // INVOKE - packet.m_nInfoField1 = CTimeUtils::GetTimeMS(); - - packet.AllocPacket(256); // should be enough - char *enc = packet.m_body; - enc += EncodeString(enc, "_checkbw"); - enc += EncodeNumber(enc, 0x00); - *enc = 0x05; // NULL - enc++; - - packet.m_nBodySize = enc - packet.m_body; - - return SendRTMP(packet); -} - -bool CRTMP::SendCheckBWResult() -{ - RTMPPacket packet; - packet.m_nChannel = 0x03; // control channel (invoke) - packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; - packet.m_packetType = 0x14; // INVOKE - packet.m_nInfoField1 = 0x16 * m_nBWCheckCounter; // temp inc value. till we figure it out. - - packet.AllocPacket(256); // should be enough - char *enc = packet.m_body; - enc += EncodeString(enc, "_result"); - enc += EncodeNumber(enc, (double)time(NULL)); // temp - *enc = 0x05; // NULL - enc++; - enc += EncodeNumber(enc, (double)m_nBWCheckCounter++); - - packet.m_nBodySize = enc - packet.m_body; - - return SendRTMP(packet); -} - -bool CRTMP::SendPlay() -{ - CURL url(m_strLink); - RTMPPacket packet; - packet.m_nChannel = 0x08; // we make 8 our stream channel - packet.m_headerType = RTMP_PACKET_SIZE_LARGE; - packet.m_packetType = 0x14; // INVOKE - packet.m_nInfoField2 = m_stream_id; - - packet.AllocPacket(256); // should be enough - char *enc = packet.m_body; - enc += EncodeString(enc, "play"); - enc += EncodeNumber(enc, 0.0); - *enc = 0x05; // NULL - enc++; - // use m_strPlayPath - CStdString strPlay = m_strPlayPath; - if (strPlay.IsEmpty()) - { - // or use slist parameter, if there is one - int nPos = url.GetFileName().Find("slist="); - if (nPos > 0) - strPlay = url.GetFileName().Mid(nPos + 6); - - if (strPlay.IsEmpty()) - { - // or use last piece of URL, if there's more than one level - CStdString::size_type pos_slash = url.GetFileName().find_last_of("/"); - if ( pos_slash != CStdString::npos ) - strPlay = url.GetFileName().Mid(pos_slash+1); - } - - if (strPlay.IsEmpty()) - { - CLog::Log(LOGERROR,"%s, no name to play!", __FUNCTION__); - return false; - } - } - - CLog::Log(LOGDEBUG,"%s, invoking play '%s'", __FUNCTION__, strPlay.c_str() ); - - enc += EncodeString(enc, strPlay.c_str()); - if (m_bIsLive) - enc += EncodeNumber(enc, -1000.0); - else - enc += EncodeNumber(enc, (m_dStartPoint/1000)); - - packet.m_nBodySize = enc - packet.m_body; - - return SendRTMP(packet); -} - -bool CRTMP::SendPing(short nType, unsigned int nObject, unsigned int nTime) -{ - CLog::Log(LOGDEBUG,"%s, sending ping. type: 0x%04x", __FUNCTION__, (unsigned short)nType); - - RTMPPacket packet; - packet.m_nChannel = 0x02; // control channel (ping) - packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; - packet.m_packetType = 0x04; // ping - packet.m_nInfoField1 = CTimeUtils::GetTimeMS(); - - int nSize = (nType==0x03?10:6); // type 3 is the buffer time and requires all 3 parameters. all in all 10 bytes. - packet.AllocPacket(nSize); - packet.m_nBodySize = nSize; - - char *buf = packet.m_body; - buf += EncodeInt16(buf, nType); - - if (nSize > 2) - buf += EncodeInt32(buf, nObject); - - if (nSize > 6) - buf += EncodeInt32(buf, nTime); - - return SendRTMP(packet); -} - -void CRTMP::HandleInvoke(const RTMPPacket &packet) -{ - if (packet.m_body[0] != 0x02) // make sure it is a string method name we start with - { - CLog::Log(LOGWARNING,"%s, Sanity failed. no string method in invoke packet", __FUNCTION__); - return; - } - - RTMP_LIB::AMFObject obj; - int nRes = obj.Decode(packet.m_body, packet.m_nBodySize); - if (nRes < 0) - { - CLog::Log(LOGERROR,"%s, error decoding invoke packet", __FUNCTION__); - return; - } - - obj.Dump(); - CStdString method = obj.GetProperty(0).GetString(); - CLog::Log(LOGDEBUG,"%s, server invoking <%s>", __FUNCTION__, method.c_str()); - - if (method == "_result") - { - CStdString methodInvoked = m_methodCalls[0]; - m_methodCalls.erase(m_methodCalls.begin()); - - CLog::Log(LOGDEBUG,"%s, received result for method call <%s>", __FUNCTION__, methodInvoked.c_str()); - - if (methodInvoked == "connect") - { - SendServerBW(); - SendPing(3, 0, 300); - SendCreateStream(2.0); - } - else if (methodInvoked == "createStream") - { - m_stream_id = (int)obj.GetProperty(3).GetNumber(); - SendPlay(); - SendPing(3, 1, m_nBufferMS); - } - else if (methodInvoked == "play") - { - SendPlay(); - } - } - else if (method == "onBWDone") - { - SendCheckBW(); - } - else if (method == "_onbwcheck") - { - SendCheckBWResult(); - } - else if (method == "_error") - { - CLog::Log(LOGERROR,"%s, rtmp server sent error", __FUNCTION__); - } - else if (method == "close") - { - CLog::Log(LOGERROR,"%s, rtmp server requested close", __FUNCTION__); - Close(); - } - else if (method == "onStatus") - { - CStdString code = obj.GetProperty(3).GetObject().GetProperty("code").GetString(); - CStdString level = obj.GetProperty(3).GetObject().GetProperty("level").GetString(); - - CLog::Log(LOGDEBUG,"%s, onStatus: %s", __FUNCTION__, code.c_str() ); - if (code == "NetStream.Failed" - || code == "NetStream.Play.Failed" - || code == "NetStream.Play.Stop" - || code == "NetStream.Play.StreamNotFound") - Close(); - } - else - { - - } -} - -void CRTMP::HandleMetadata(const RTMPPacket &packet) -{ -} - -void CRTMP::HandleChangeChunkSize(const RTMPPacket &packet) -{ - if (packet.m_nBodySize >= 4) - { - m_chunkSize = ReadInt32(packet.m_body); - CLog::Log(LOGDEBUG,"%s, received: chunk size change to %d", __FUNCTION__, m_chunkSize); - } -} - -void CRTMP::HandleAudio(const RTMPPacket &packet) -{ -} - -void CRTMP::HandleVideo(const RTMPPacket &packet) -{ -} - -void CRTMP::HandlePing(const RTMPPacket &packet) -{ - short nType = -1; - if (packet.m_body && packet.m_nBodySize >= 2) - nType = ReadInt16(packet.m_body); - CLog::Log(LOGDEBUG,"%s, received: ping, type: %d", __FUNCTION__, nType); - - if (nType == 0x06 && packet.m_nBodySize >= 6) // server ping. reply with pong. - { - unsigned int nTime = ReadInt32(packet.m_body + 2); - SendPing(0x07, nTime); - } -} - -bool CRTMP::ReadPacket(RTMPPacket &packet) -{ - char type; - if (ReadN(&type,1) != 1) - { - CLog::Log(LOGERROR, "%s, failed to read RTMP packet header", __FUNCTION__); - return false; - } - - packet.m_headerType = (type & 0xc0) >> 6; - packet.m_nChannel = (type & 0x3f); - - int nSize = packetSize[packet.m_headerType]; - - if (nSize == RTMP_LARGE_HEADER_SIZE) - packet.m_hasAbsTimestamp = true; - - if (nSize < RTMP_LARGE_HEADER_SIZE) // using values from the last message of this channel - { - packet.FreePacketHeader(); - packet = m_vecChannelsIn[packet.m_nChannel]; - } - - nSize--; - - char header[RTMP_LARGE_HEADER_SIZE] = {0}; - if (nSize > 0 && ReadN(header,nSize) != nSize) - { - CLog::Log(LOGERROR, "%s, failed to read RTMP packet header. type: %x", __FUNCTION__, (unsigned int)type); - return false; - } - - if (nSize >= 3) - packet.m_nInfoField1 = ReadInt24(header); - - //!!debug - //CLog::Log(LOGDEBUG, "%s, reading RTMP packet chunk on channel %x, headersz %i, timestamp %i, abs timestamp %i", __FUNCTION__, packet.m_nChannel, nSize, packet.m_nInfoField1, packet.m_hasAbsTimestamp); - - if (nSize >= 6) - { - packet.m_nBodySize = ReadInt24(header + 3); - packet.m_nBytesRead = 0; - packet.FreePacketHeader(); // new packet body - } - - if (nSize > 6) - packet.m_packetType = header[6]; - - if (nSize == 11) - packet.m_nInfoField2 = ReadInt32LE(header+7); - - if (packet.m_nBodySize > 0 && packet.m_body == NULL && !packet.AllocPacket(packet.m_nBodySize)) - { - CLog::Log(LOGDEBUG,"%s, failed to allocate packet", __FUNCTION__); - return false; - } - - int nToRead = packet.m_nBodySize - packet.m_nBytesRead; - int nChunk = m_chunkSize; - if (nToRead < nChunk) - nChunk = nToRead; - - if (ReadN(packet.m_body + packet.m_nBytesRead, nChunk) != nChunk) - { - CLog::Log(LOGERROR, "%s, failed to read RTMP packet body. len: %lu", __FUNCTION__, packet.m_nBodySize); - packet.m_body = NULL; // we dont want it deleted since its pointed to from the stored packets (m_vecChannelsIn) - return false; - } - - packet.m_nBytesRead += nChunk; - - // keep the packet as ref for other packets on this channel - m_vecChannelsIn[packet.m_nChannel] = packet; - - if (packet.IsReady()) - { - // make packet's timestamp absolute - if (!packet.m_hasAbsTimestamp) - packet.m_nInfoField1 += m_channelTimestamp[packet.m_nChannel]; - - m_channelTimestamp[packet.m_nChannel] = packet.m_nInfoField1; - - // reset the data from the stored packet. we keep the header since we may use it later if a new packet for this channel - // arrives and requests to re-use some info (small packet header) - m_vecChannelsIn[packet.m_nChannel].m_body = NULL; - m_vecChannelsIn[packet.m_nChannel].m_nBytesRead = 0; - m_vecChannelsIn[packet.m_nChannel].m_hasAbsTimestamp = false; - } - else - packet.m_body = NULL; // so it wont be erased on "free" - - return true; -} - -short CRTMP::ReadInt16(const char *data) -{ - short val; - memcpy(&val,data,sizeof(short)); - return ntohs(val); -} - -int CRTMP::ReadInt24(const char *data) -{ - char tmp[4] = {0}; - memcpy(tmp+1, data, 3); - int val; - memcpy(&val, tmp, sizeof(int)); - return ntohl(val); -} - -// big-endian 32bit integer -int CRTMP::ReadInt32(const char *data) -{ - int val; - memcpy(&val, data, sizeof(int)); - return ntohl(val); -} - -// little-endian 32bit integer -int CRTMP::ReadInt32LE(const char *data) -{ - int val; - memcpy(&val, data, sizeof(int)); - return Endian_SwapLE32(val); -} - -std::string CRTMP::ReadString(const char *data) -{ - std::string strRes; - short len = ReadInt16(data); - if (len > 0) - { - char *pStr = new char[len+1]; - memset(pStr, 0, len+1); - memcpy(pStr, data + sizeof(short), len); - strRes = pStr; - delete [] pStr; - } - return strRes; -} - -bool CRTMP::ReadBool(const char *data) -{ - return *data == 0x01; -} - -double CRTMP::ReadNumber(const char *data) -{ - double val; -#ifndef WORDS_BIGENDIAN - char *dPtr = (char *)&val; - for (int i=7;i>=0;i--) - { - *dPtr = data[i]; - dPtr++; - } -#else - memcpy(&val, data, 8); -#endif - - return val; -} - -int CRTMP::EncodeString(char *output, const std::string &strName, const std::string &strValue) -{ - char *buf = output; - short length = htons(strName.size()); - memcpy(buf, &length, 2); - buf += 2; - - memcpy(buf, strName.c_str(), strName.size()); - buf += strName.size(); - - buf += EncodeString(buf, strValue); - return buf - output; -} - -int CRTMP::EncodeInt16(char *output, short nVal) -{ - nVal = htons(nVal); - memcpy(output, &nVal, sizeof(short)); - return sizeof(short); -} - -int CRTMP::EncodeInt24(char *output, int nVal) -{ - nVal = htonl(nVal); - char *ptr = (char *)&nVal; - ptr++; - memcpy(output, ptr, 3); - return 3; -} - -// big-endian 32bit integer -int CRTMP::EncodeInt32(char *output, int nVal) -{ - nVal = htonl(nVal); - memcpy(output, &nVal, sizeof(int)); - return sizeof(int); -} - -// little-endian 32bit integer -int CRTMP::EncodeInt32LE(char *output, int nVal) -{ - nVal = Endian_SwapLE32(nVal); - memcpy(output, &nVal, sizeof(int)); - return sizeof(int); -} - -int CRTMP::EncodeNumber(char *output, const std::string &strName, double dVal) -{ - char *buf = output; - - unsigned short length = htons(strName.size()); - memcpy(buf, &length, 2); - buf += 2; - - memcpy(buf, strName.c_str(), strName.size()); - buf += strName.size(); - - buf += EncodeNumber(buf, dVal); - return buf - output; -} - -int CRTMP::EncodeBoolean(char *output, const std::string &strName, bool bVal) -{ - char *buf = output; - unsigned short length = htons(strName.size()); - memcpy(buf, &length, 2); - buf += 2; - - memcpy(buf, strName.c_str(), strName.size()); - buf += strName.size(); - - buf += EncodeBoolean(buf, bVal); - - return buf - output; -} - -int CRTMP::EncodeString(char *output, const std::string &strValue) -{ - char *buf = output; - *buf = 0x02; // Datatype: String - buf++; - - short length = htons(strValue.size()); - memcpy(buf, &length, 2); - buf += 2; - - memcpy(buf, strValue.c_str(), strValue.size()); - buf += strValue.size(); - - return buf - output; -} - -int CRTMP::EncodeNumber(char *output, double dVal) -{ - char *buf = output; - *buf = 0x00; // type: Number - buf++; - -#ifndef WORDS_BIGENDIAN - char *dPtr = (char *)&dVal; - for (int i=7;i>=0;i--) - { - buf[i] = *dPtr; - dPtr++; - } -#else - memcpy(buf, &dVal, 8); -#endif - - buf += 8; - - return buf - output; -} - -int CRTMP::EncodeBoolean(char *output, bool bVal) -{ - char *buf = output; - - *buf = 0x01; // type: Boolean - buf++; - - *buf = bVal?0x01:0x00; - buf++; - - return buf - output; -} - -bool CRTMP::HandShake() -{ - char clientsig[RTMP_SIG_SIZE+1]; - char serversig[RTMP_SIG_SIZE]; - - clientsig[0] = 0x3; - DWORD uptime = htonl(CTimeUtils::GetTimeMS()); - memcpy(clientsig + 1, &uptime, sizeof(DWORD)); - memset(clientsig + 5, 0, 4); - - for (int i=9; i<=RTMP_SIG_SIZE; i++) - clientsig[i] = (char)(rand() % 256); - - if (!WriteN(clientsig, RTMP_SIG_SIZE + 1)) - return false; - - char dummy; - if (ReadN(&dummy, 1) != 1) // 0x03 - return false; - - - if (ReadN(serversig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) - return false; - - char resp[RTMP_SIG_SIZE]; - if (ReadN(resp, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) - return false; - - bool bMatch = (memcmp(resp, clientsig + 1, RTMP_SIG_SIZE) == 0); - if (!bMatch) - { - CLog::Log(LOGWARNING,"%s, client signiture does not match!",__FUNCTION__); - } - - if (!WriteN(serversig, RTMP_SIG_SIZE)) - return false; - - return true; -} - -bool CRTMP::SendRTMP(RTMPPacket &packet) -{ - const RTMPPacket &prevPacket = m_vecChannelsOut[packet.m_nChannel]; - if (packet.m_headerType != RTMP_PACKET_SIZE_LARGE) - { - // compress a bit by using the prev packet's attributes - if (prevPacket.m_nBodySize == packet.m_nBodySize && packet.m_headerType == RTMP_PACKET_SIZE_MEDIUM) - packet.m_headerType = RTMP_PACKET_SIZE_SMALL; - - if (prevPacket.m_nInfoField2 == packet.m_nInfoField2 && packet.m_headerType == RTMP_PACKET_SIZE_SMALL) - packet.m_headerType = RTMP_PACKET_SIZE_MINIMUM; - - } - - if (packet.m_headerType > 3) // sanity - { - CLog::Log(LOGERROR,"sanity failed!! tring to send header of type: 0x%02x.", (unsigned char)packet.m_headerType); - return false; - } - - int nSize = packetSize[packet.m_headerType]; - char header[RTMP_LARGE_HEADER_SIZE] = { 0 }; - header[0] = (char)((packet.m_headerType << 6) | packet.m_nChannel); - if (nSize > 1) - EncodeInt24(header+1, packet.m_nInfoField1); - - if (nSize > 4) - { - EncodeInt24(header+4, packet.m_nBodySize); - header[7] = packet.m_packetType; - } - - if (nSize > 8) - EncodeInt32LE(header+8, packet.m_nInfoField2); - - if (!WriteN(header, nSize)) - { - CLog::Log(LOGWARNING,"couldn't send rtmp header"); - return false; - } - - nSize = packet.m_nBodySize; - char *buffer = packet.m_body; - - while (nSize) - { - int nChunkSize = packet.m_packetType == 0x14?m_chunkSize:packet.m_nBodySize; - if (nSize < m_chunkSize) - nChunkSize = nSize; - - if (!WriteN(buffer, nChunkSize)) - return false; - - nSize -= nChunkSize; - buffer += nChunkSize; - - if (nSize > 0) - { - char sep = (0xc0 | packet.m_nChannel); - if (!WriteN(&sep, 1)) - return false; - } - } - - if (packet.m_packetType == 0x14) // we invoked a remote method, keep it in call queue till result arrives - m_methodCalls.push_back(ReadString(packet.m_body + 1)); - - m_vecChannelsOut[packet.m_nChannel] = packet; - m_vecChannelsOut[packet.m_nChannel].m_body = NULL; - return true; -} - -void CRTMP::Close() -{ - if (IsConnected()) - { - //SendDeleteStream(m_stream_id); - closesocket(m_socket); - } - - m_socket = INVALID_SOCKET; - m_chunkSize = 128; - m_nBWCheckCounter = 0; - m_nBytesIn = 0; - m_nBytesInSent = 0; - - for (int i=0; i<64; i++) - { - m_vecChannelsIn[i].Reset(); - m_vecChannelsIn[i].m_nChannel = i; - m_vecChannelsOut[i].Reset(); - m_vecChannelsOut[i].m_nChannel = i; - } - - m_bPlaying = false; - m_nBufferSize = 0; -} - -bool CRTMP::FillBuffer() -{ - assert(m_nBufferSize==0);// only fill buffer when it's empty - int nBytes = recv(m_socket, m_pBuffer, RTMP_BUFFER_CACHE_SIZE, 0); - if (nBytes != SOCKET_ERROR) - { - m_nBufferSize += nBytes; - m_pBufferStart = m_pBuffer; - } - else - { - CLog::Log(LOGERROR,"%s, recv returned %d. errno: %d", __FUNCTION__, nBytes, WSAGetLastError()); - Close(); - return false; - } - - return true; -} diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/rtmp.h xbmc-trunk-28276/xbmc/lib/libRTMP/rtmp.h --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/rtmp.h 2010-04-04 11:46:52.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/rtmp.h 2010-04-04 22:58:14.472139912 +0100 @@ -3,135 +3,318 @@ /* * Copyright (C) 2005-2008 Team XBMC * http://www.xbmc.org + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu * - * This file is part of libRTMP. + * This file is part of librtmp. * - * libRTMP 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. + * librtmp 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, + * or (at your option) any later version. * - * libRTMP is distributed in the hope that it will be useful, + * librtmp 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. + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with libRTMP; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html */ -#include -#include -#include "rtmppacket.h" -#include "system.h" // for INVALID_SOCKET +#define CRYPTO -namespace RTMP_LIB +#include +#include + +#include "amf.h" + +#ifdef __cplusplus +extern "C" { - class CRTMP +#endif + +#define RTMP_LIB_VERSION 0x020202 /* 2.2b */ + +#define RTMP_FEATURE_HTTP 0x01 +#define RTMP_FEATURE_ENC 0x02 +#define RTMP_FEATURE_SSL 0x04 +#define RTMP_FEATURE_MFP 0x08 /* not yet supported */ +#define RTMP_FEATURE_WRITE 0x10 /* publish, not play */ +#define RTMP_FEATURE_HTTP2 0x20 /* server-side rtmpt */ + +#define RTMP_PROTOCOL_UNDEFINED -1 +#define RTMP_PROTOCOL_RTMP 0 +#define RTMP_PROTOCOL_RTMPE RTMP_FEATURE_ENC +#define RTMP_PROTOCOL_RTMPT RTMP_FEATURE_HTTP +#define RTMP_PROTOCOL_RTMPS (RTMP_FEATURE_HTTP|RTMP_FEATURE_SSL) +#define RTMP_PROTOCOL_RTMPTE (RTMP_FEATURE_HTTP|RTMP_FEATURE_ENC) +#define RTMP_PROTOCOL_RTMFP RTMP_FEATURE_MFP + +#define RTMP_DEFAULT_CHUNKSIZE 128 + +#define RTMP_BUFFER_CACHE_SIZE (16*1024) // needs to fit largest number of bytes recv() may return + +#define RTMP_CHANNELS 65600 + + extern const char RTMPProtocolStringsLower[][7]; + extern const AVal RTMP_DefaultFlashVer; + extern bool RTMP_ctrlC; + + uint32_t RTMP_GetTime(void); + +#define RTMP_PACKET_TYPE_AUDIO 0x08 +#define RTMP_PACKET_TYPE_VIDEO 0x09 +#define RTMP_PACKET_TYPE_INFO 0x12 + +#define RTMP_MAX_HEADER_SIZE 18 + +#define RTMP_PACKET_SIZE_LARGE 0 +#define RTMP_PACKET_SIZE_MEDIUM 1 +#define RTMP_PACKET_SIZE_SMALL 2 +#define RTMP_PACKET_SIZE_MINIMUM 3 + + typedef struct RTMPChunk { - public: + int c_headerSize; + int c_chunkSize; + char *c_chunk; + char c_header[RTMP_MAX_HEADER_SIZE]; + } RTMPChunk; - CRTMP(); - virtual ~CRTMP(); + typedef struct RTMPPacket + { + uint8_t m_headerType; + uint8_t m_packetType; + uint8_t m_hasAbsTimestamp; // timestamp absolute or relative? + int m_nChannel; + uint32_t m_nTimeStamp; // timestamp + int32_t m_nInfoField2; // last 4 bytes in a long header + uint32_t m_nBodySize; + uint32_t m_nBytesRead; + RTMPChunk *m_chunk; + char *m_body; + } RTMPPacket; - void SetPlayer(const std::string &strPlayer); - void SetPageUrl(const std::string &strPageUrl); - void SetPlayPath(const std::string &strPlayPath); - void SetTcUrl(const std::string &strTcUrl); - void SetLive(); - void SetBufferMS(int size); - bool Seek(double dTime); - - bool Connect(const std::string &strRTMPLink, double dTime = 0); - inline bool IsConnected() { return m_socket != INVALID_SOCKET; } - - bool GetNextMediaPacket(RTMPPacket &packet); - - void Close(); - - static int EncodeString(char *output, const std::string &strValue); - static int EncodeNumber(char *output, double dVal); - static int EncodeInt16(char *output, short nVal); - static int EncodeInt24(char *output, int nVal); - static int EncodeInt32(char *output, int nVal); - static int EncodeInt32LE(char *output, int nVal); - static int EncodeBoolean(char *output,bool bVal); - - static short ReadInt16(const char *data); - static int ReadInt24(const char *data); - static int ReadInt32(const char *data); - static int ReadInt32LE(const char *data); - static std::string ReadString(const char *data); - static bool ReadBool(const char *data); - static double ReadNumber(const char *data); - bool SendPause(bool DoPause, double dTime); - - protected: - bool HandShake(); - bool Connect(); - - bool SendConnectPacket(); - bool SendServerBW(); - bool SendCheckBW(); - bool SendCheckBWResult(); - bool SendPing(short nType, unsigned int nObject, unsigned int nTime = 0); - bool SendCreateStream(double dStreamId); - bool SendDeleteStream(double dStreamId); - bool SendPlay(); - bool SendSeek(double dTime); - bool SendBytesReceived(); - - void HandleInvoke(const RTMPPacket &packet); - void HandleMetadata(const RTMPPacket &packet); - void HandleChangeChunkSize(const RTMPPacket &packet); - void HandleAudio(const RTMPPacket &packet); - void HandleVideo(const RTMPPacket &packet); - void HandlePing(const RTMPPacket &packet); - - int EncodeString(char *output, const std::string &strName, const std::string &strValue); - int EncodeNumber(char *output, const std::string &strName, double dVal); - int EncodeBoolean(char *output, const std::string &strName, bool bVal); - - bool SendRTMP(RTMPPacket &packet); - - bool ReadPacket(RTMPPacket &packet); - int ReadN(char *buffer, int n); - bool WriteN(const char *buffer, int n); - - bool FillBuffer(); - void FlushBuffer(); - - int m_socket; - int m_chunkSize; - int m_nBWCheckCounter; - int m_nBytesIn; - int m_nBytesInSent; - bool m_bPlaying; - int m_nBufferMS; - int m_stream_id; // returned in _result from invoking createStream - - std::string m_strPlayer; - std::string m_strPageUrl; - std::string m_strLink; - std::string m_strPlayPath; - std::string m_strTcUrl; - bool m_bIsLive; - - std::vector m_methodCalls; //remote method calls queue - - char *m_pBuffer; // data read from socket - char *m_pBufferStart; // pointer into m_pBuffer of next byte to process - int m_nBufferSize; // number of unprocessed bytes in buffer - RTMPPacket m_vecChannelsIn[64]; - RTMPPacket m_vecChannelsOut[64]; - int m_channelTimestamp[64]; // abs timestamp of last packet + typedef struct RTMPSockBuf + { + int sb_socket; + int sb_size; /* number of unprocessed bytes in buffer */ + char *sb_start; /* pointer into sb_pBuffer of next byte to process */ + char sb_buf[RTMP_BUFFER_CACHE_SIZE]; /* data read from socket */ + bool sb_timedout; + void *sb_ssl; + } RTMPSockBuf; + + void RTMPPacket_Reset(RTMPPacket *p); + void RTMPPacket_Dump(RTMPPacket *p); + bool RTMPPacket_Alloc(RTMPPacket *p, int nSize); + void RTMPPacket_Free(RTMPPacket *p); - double m_dStartPoint; +#define RTMPPacket_IsReady(a) ((a)->m_nBytesRead == (a)->m_nBodySize) - }; -}; + typedef struct RTMP_LNK + { + AVal hostname; + AVal sockshost; + + AVal playpath0; /* parsed from URL */ + AVal playpath; /* passed in explicitly */ + AVal tcUrl; + AVal swfUrl; + AVal pageUrl; + AVal app; + AVal auth; + AVal flashVer; + AVal subscribepath; + AVal token; + AMFObject extras; + int edepth; + + int seekTime; + int stopTime; + + bool authflag; + bool bLiveStream; + bool swfVfy; + int swfAge; + + int protocol; + int timeout; // number of seconds before connection times out + + unsigned short socksport; + unsigned short port; + +#ifdef CRYPTO + void *dh; // for encryption + void *rc4keyIn; + void *rc4keyOut; + + uint32_t SWFSize; + char SWFHash[32]; + char SWFVerificationResponse[42]; +#endif + } RTMP_LNK; + /* state for read() wrapper */ + typedef struct RTMP_READ + { + char *buf; + char *bufpos; + unsigned int buflen; + uint32_t timestamp; + uint8_t dataType; + uint8_t flags; +#define RTMP_READ_HEADER 0x01 +#define RTMP_READ_RESUME 0x02 +#define RTMP_READ_NO_IGNORE 0x04 +#define RTMP_READ_GOTKF 0x08 +#define RTMP_READ_GOTFLVK 0x10 +#define RTMP_READ_SEEKING 0x20 + int8_t status; +#define RTMP_READ_COMPLETE -3 +#define RTMP_READ_ERROR -2 +#define RTMP_READ_EOF -1 +#define RTMP_READ_IGNORE 0 + + /* if bResume == TRUE */ + uint8_t initialFrameType; + uint32_t nResumeTS; + char *metaHeader; + char *initialFrame; + uint32_t nMetaHeaderSize; + uint32_t nInitialFrameSize; + uint32_t nIgnoredFrameCounter; + uint32_t nIgnoredFlvFrameCounter; + } RTMP_READ; + + typedef struct RTMP + { + int m_inChunkSize; + int m_outChunkSize; + int m_nBWCheckCounter; + int m_nBytesIn; + int m_nBytesInSent; + int m_nBufferMS; + int m_stream_id; // returned in _result from invoking createStream + int m_mediaChannel; + uint32_t m_mediaStamp; + uint32_t m_pauseStamp; + int m_pausing; + int m_nServerBW; + int m_nClientBW; + uint8_t m_nClientBW2; + uint8_t m_bPlaying; + uint8_t m_bSendEncoding; + uint8_t m_bSendCounter; + + int m_numInvokes; + int m_numCalls; + AVal *m_methodCalls; /* remote method calls queue */ + + RTMP_LNK Link; + RTMPPacket *m_vecChannelsIn[RTMP_CHANNELS]; + RTMPPacket *m_vecChannelsOut[RTMP_CHANNELS]; + int m_channelTimestamp[RTMP_CHANNELS]; // abs timestamp of last packet + + double m_fAudioCodecs; // audioCodecs for the connect packet + double m_fVideoCodecs; // videoCodecs for the connect packet + double m_fEncoding; /* AMF0 or AMF3 */ + + double m_fDuration; // duration of stream in seconds + + int m_msgCounter; /* RTMPT stuff */ + int m_polling; + int m_resplen; + int m_unackd; + AVal m_clientID; + + RTMP_READ m_read; + RTMPPacket m_write; + RTMPSockBuf m_sb; + } RTMP; + + bool RTMP_ParseURL(const char *url, int *protocol, AVal *host, + unsigned int *port, AVal *playpath, AVal *app); + + void RTMP_ParsePlaypath(AVal *in, AVal *out); + void RTMP_SetBufferMS(RTMP *r, int size); + void RTMP_UpdateBufferMS(RTMP *r); + + bool RTMP_SetOpt(RTMP *r, const AVal *opt, AVal *arg); + bool RTMP_SetupURL(RTMP *r, char *url); + void RTMP_SetupStream(RTMP *r, int protocol, + AVal *hostname, + unsigned int port, + AVal *sockshost, + AVal *playpath, + AVal *tcUrl, + AVal *swfUrl, + AVal *pageUrl, + AVal *app, + AVal *auth, + AVal *swfSHA256Hash, + uint32_t swfSize, + AVal *flashVer, + AVal *subscribepath, + int dStart, + int dStop, bool bLiveStream, long int timeout); + + bool RTMP_Connect(RTMP *r, RTMPPacket *cp); + struct sockaddr; + bool RTMP_Connect0(RTMP *r, struct sockaddr *svc); + bool RTMP_Connect1(RTMP *r, RTMPPacket *cp); + bool RTMP_Serve(RTMP *r); + + bool RTMP_ReadPacket(RTMP *r, RTMPPacket *packet); + bool RTMP_SendPacket(RTMP *r, RTMPPacket *packet, bool queue); + bool RTMP_SendChunk(RTMP *r, RTMPChunk *chunk); + bool RTMP_IsConnected(RTMP *r); + bool RTMP_IsTimedout(RTMP *r); + double RTMP_GetDuration(RTMP *r); + bool RTMP_ToggleStream(RTMP *r); + + bool RTMP_ConnectStream(RTMP *r, int seekTime); + bool RTMP_ReconnectStream(RTMP *r, int seekTime); + void RTMP_DeleteStream(RTMP *r); + int RTMP_GetNextMediaPacket(RTMP *r, RTMPPacket *packet); + int RTMP_ClientPacket(RTMP *r, RTMPPacket *packet); + + void RTMP_Init(RTMP *r); + void RTMP_Close(RTMP *r); + int RTMP_LibVersion(void); + void RTMP_UserInterrupt(void); /* user typed Ctrl-C */ + + bool RTMP_SendCtrl(RTMP *r, short nType, unsigned int nObject, + unsigned int nTime); + bool RTMP_SendPause(RTMP *r, bool DoPause, int dTime); + bool RTMP_FindFirstMatchingProperty(AMFObject *obj, const AVal *name, + AMFObjectProperty * p); + + int RTMPSockBuf_Fill(RTMPSockBuf *sb); + int RTMPSockBuf_Send(RTMPSockBuf *sb, const char *buf, int len); + int RTMPSockBuf_Close(RTMPSockBuf *sb); + + bool RTMP_SendCreateStream(RTMP *r); + bool RTMP_SendSeek(RTMP *r, int dTime); + bool RTMP_SendServerBW(RTMP *r); + bool RTMP_SendClientBW(RTMP *r); + void RTMP_DropRequest(RTMP *r, int i, bool freeit); + int RTMP_Read(RTMP *r, char *buf, int size); + int RTMP_Write(RTMP *r, char *buf, int size); + +#ifdef CRYPTO +/* hashswf.c */ +#define HASHLEN 32 + + int RTMP_HashSWF(const char *url, unsigned int *size, unsigned char *hash, + int age); #endif +#ifdef __cplusplus +}; +#endif +#endif diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/rtmppacket.cpp xbmc-trunk-28276/xbmc/lib/libRTMP/rtmppacket.cpp --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/rtmppacket.cpp 2010-04-04 11:46:52.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/rtmppacket.cpp 1970-01-01 01:00:00.000000000 +0100 @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2005-2008 Team XBMC - * http://www.xbmc.org - * - * This file is part of libRTMP. - * - * libRTMP 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. - * - * libRTMP 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 libRTMP; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifdef _LINUX -#include "linux/PlatformInclude.h" -#endif - -#include "rtmppacket.h" -#include "utils/log.h" - -#ifdef _LINUX - #include -#endif - -using namespace RTMP_LIB; - -RTMPPacket::RTMPPacket() -{ - Reset(); -} - -RTMPPacket::~RTMPPacket() -{ - FreePacket(); -} - -void RTMPPacket::Reset() -{ - m_headerType = 0; - m_packetType = 0; - m_nChannel = 0; - m_nInfoField1 = 0; - m_nInfoField2 = 0; - m_hasAbsTimestamp = false; - m_nBodySize = 0; - m_nBytesRead = 0; - m_body = NULL; -} - -bool RTMPPacket::AllocPacket(int nSize) -{ - m_body = new char[nSize]; - if (!m_body) - return false; - memset(m_body,0,nSize); - m_nBytesRead = 0; - return true; -} - -void RTMPPacket::FreePacket() -{ - FreePacketHeader(); - Reset(); -} - -void RTMPPacket::FreePacketHeader() -{ - if (m_body) - delete [] m_body; - m_body = NULL; -} - -void RTMPPacket::Dump() -{ - CLog::Log(LOGDEBUG,"RTMP PACKET: packet type: 0x%02x. channel: 0x%02x. info 1: %d info 2: %d. Body size: %lu. body: 0x%02x", m_packetType, m_nChannel, - m_nInfoField1, m_nInfoField2, m_nBodySize, m_body?(unsigned char)m_body[0]:0); -} diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/rtmppacket.h xbmc-trunk-28276/xbmc/lib/libRTMP/rtmppacket.h --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/rtmppacket.h 2010-04-04 11:46:52.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/rtmppacket.h 1970-01-01 01:00:00.000000000 +0100 @@ -1,60 +0,0 @@ -#ifndef __RTMP_PACKET__ -#define __RTMP_PACKET__ -/* - * Copyright (C) 2005-2008 Team XBMC - * http://www.xbmc.org - * - * This file is part of libRTMP. - * - * libRTMP 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. - * - * libRTMP 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 libRTMP; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#define RTMP_PACKET_TYPE_AUDIO 0x08 -#define RTMP_PACKET_TYPE_VIDEO 0x09 -#define RTMP_PACKET_TYPE_INFO 0x12 - -#define RTMP_MAX_HEADER_SIZE 12 - -namespace RTMP_LIB -{ - class RTMPPacket - { - public: - RTMPPacket(); - virtual ~RTMPPacket(); - - void Reset(); - bool AllocPacket(int nSize); - void FreePacket(); - void FreePacketHeader(); - - inline bool IsReady() { return m_nBytesRead == m_nBodySize; } - void Dump(); - - unsigned char m_headerType; - unsigned char m_packetType; - unsigned char m_nChannel; - int m_nInfoField1; // 3 first bytes - int m_nInfoField2; // last 4 bytes in a long header - bool m_hasAbsTimestamp; // timestamp absolute or relative? - unsigned long m_nBodySize; - unsigned long m_nBytesRead; - char *m_body; - }; -}; - -#endif diff -Nur xbmc-trunk-28276-orig/xbmc/lib/libRTMP/rtmp_sys.h xbmc-trunk-28276/xbmc/lib/libRTMP/rtmp_sys.h --- xbmc-trunk-28276-orig/xbmc/lib/libRTMP/rtmp_sys.h 1970-01-01 01:00:00.000000000 +0100 +++ xbmc-trunk-28276/xbmc/lib/libRTMP/rtmp_sys.h 2010-04-04 22:58:14.482143418 +0100 @@ -0,0 +1,76 @@ +#ifndef __RTMP_SYS_H__ +#define __RTMP_SYS_H__ +/* + * Copyright (C) 2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp 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, + * or (at your option) any later version. + * + * librtmp 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 General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#ifdef WIN32 +#include +#define GetSockError() WSAGetLastError() +#define setsockopt(a,b,c,d,e) (setsockopt)(a,b,c,(const char *)d,(int)e) +#define EWOULDBLOCK WSAETIMEDOUT /* we don't use nonblocking, but we do use timeouts */ +#define sleep(n) Sleep(n*1000) +#define msleep(n) Sleep(n) +#define socklen_t int +#define SET_RCVTIMEO(tv,s) int tv = s*1000 +#else +#include +#include +#include +#include +#include +#include +#include +#include +#define GetSockError() errno +#undef closesocket +#define closesocket(s) close(s) +#define msleep(n) usleep(n*1000) +#define SET_RCVTIMEO(tv,s) struct timeval tv = {s,0} +#endif + +#include "rtmp.h" + +#ifdef USE_GNUTLS +#include +typedef struct tls_ctx { + gnutls_certificate_credentials_t cred; + gnutls_priority_t prios; +} tls_ctx; +#define TLS_CTX tls_ctx * +#define TLS_client(ctx,s) gnutls_init((gnutls_session_t *)(&s), GNUTLS_CLIENT); gnutls_priority_set(s, ctx->prios); gnutls_credentials_set(s, GNUTLS_CRD_CERTIFICATE, ctx->cred) +#define TLS_setfd(s,fd) gnutls_transport_set_ptr(s, (gnutls_transport_ptr_t)(long)fd) +#define TLS_connect(s) gnutls_handshake(s) +#define TLS_read(s,b,l) gnutls_record_recv(s,b,l) +#define TLS_write(s,b,l) gnutls_record_send(s,b,l) +#define TLS_shutdown(s) gnutls_bye(s, GNUTLS_SHUT_RDWR) +#define TLS_close(s) gnutls_deinit(s) +#else +#define TLS_CTX SSL_CTX * +#define TLS_client(ctx,s) s = SSL_new(ctx) +#define TLS_setfd(s,fd) SSL_set_fd(s,fd) +#define TLS_connect(s) SSL_connect(s) +#define TLS_read(s,b,l) SSL_read(s,b,l) +#define TLS_write(s,b,l) SSL_write(s,b,l) +#define TLS_shutdown(s) SSL_shutdown(s) +#define TLS_close(s) SSL_free(s) + +#endif +#endif diff -Naur xbmc-28622/xbmc/cores/dvdplayer/DVDInputStreams/DVDInputStreamMMS.cpp xbmc-28622.patch/xbmc/cores/dvdplayer/DVDInputStreams/DVDInputStreamMMS.cpp --- xbmc-28622/xbmc/cores/dvdplayer/DVDInputStreams/DVDInputStreamMMS.cpp 2010-03-17 20:11:42.000000000 +0100 +++ xbmc-28622.patch/xbmc/cores/dvdplayer/DVDInputStreams/DVDInputStreamMMS.cpp 2010-03-19 04:04:41.074751644 +0100 @@ -35,6 +35,7 @@ // some distros have already patched this but upstream @ https://launchpad.net/libmms // does still has the "this" usage. #define this instance +#undef byte #include // FIXME: remove this header once the ubuntu headers is fixed (variable named this) #include #include