rtmp.c 166 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559
  1. /*
  2. * Copyright (C) 2005-2008 Team XBMC
  3. * http://www.xbmc.org
  4. * Copyright (C) 2008-2009 Andrej Stepanchuk
  5. * Copyright (C) 2009-2010 Howard Chu
  6. *
  7. * This file is part of librtmp.
  8. *
  9. * librtmp is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU Lesser General Public License as
  11. * published by the Free Software Foundation; either version 2.1,
  12. * or (at your option) any later version.
  13. *
  14. * librtmp is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public License
  20. * along with librtmp see the file COPYING. If not, write to
  21. * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  22. * Boston, MA 02110-1301, USA.
  23. * http://www.gnu.org/copyleft/lgpl.html
  24. */
  25. #include "rtmp_sys.h"
  26. #include "log.h"
  27. #ifdef CRYPTO
  28. #ifdef USE_POLARSSL
  29. #include <polarssl/havege.h>
  30. #include <polarssl/md5.h>
  31. #include <polarssl/base64.h>
  32. #define MD5_DIGEST_LENGTH 16
  33. static const char *my_dhm_P =
  34. "E4004C1F94182000103D883A448B3F80" \
  35. "2CE4B44A83301270002C20D0321CFD00" \
  36. "11CCEF784C26A400F43DFB901BCA7538" \
  37. "F2C6B176001CF5A0FD16D2C48B1D0C1C" \
  38. "F6AC8E1DA6BCC3B4E1F96B0564965300" \
  39. "FFA1D0B601EB2800F489AA512C4B248C" \
  40. "01F76949A60BB7F00A40B1EAB64BDD48" \
  41. "E8A700D60B7F1200FA8E77B0A979DABF";
  42. static const char *my_dhm_G = "4";
  43. #elif defined(USE_GNUTLS)
  44. #include <gnutls/gnutls.h>
  45. #define MD5_DIGEST_LENGTH 16
  46. #include <nettle/base64.h>
  47. #include <nettle/md5.h>
  48. #else /* USE_OPENSSL */
  49. #include <openssl/ssl.h>
  50. #include <openssl/rc4.h>
  51. #include <openssl/md5.h>
  52. #include <openssl/bio.h>
  53. #include <openssl/buffer.h>
  54. #endif
  55. TLS_CTX RTMP_TLS_ctx;
  56. #endif
  57. #define RTMP_SIG_SIZE 1536
  58. #define RTMP_LARGE_HEADER_SIZE 12
  59. static const int packetSize[] = { 12, 8, 4, 1 };
  60. int RTMP_ctrlC;
  61. const char RTMPProtocolStrings[][7] =
  62. {
  63. "RTMP",
  64. "RTMPT",
  65. "RTMPE",
  66. "RTMPTE",
  67. "RTMPS",
  68. "RTMPTS",
  69. "",
  70. "",
  71. "RTMFP"
  72. };
  73. const char RTMPProtocolStringsLower[][7] =
  74. {
  75. "rtmp",
  76. "rtmpt",
  77. "rtmpe",
  78. "rtmpte",
  79. "rtmps",
  80. "rtmpts",
  81. "",
  82. "",
  83. "rtmfp"
  84. };
  85. static const char *RTMPT_cmds[] =
  86. {
  87. "open",
  88. "send",
  89. "idle",
  90. "close"
  91. };
  92. typedef enum
  93. {
  94. RTMPT_OPEN=0, RTMPT_SEND, RTMPT_IDLE, RTMPT_CLOSE
  95. } RTMPTCmd;
  96. static int DumpMetaData(AMFObject *obj);
  97. static int HandShake(RTMP *r, int FP9HandShake);
  98. static int SocksNegotiate(RTMP *r);
  99. static int SendConnectPacket(RTMP *r, RTMPPacket *cp);
  100. static int SendCheckBW(RTMP *r);
  101. static int SendCheckBWResult(RTMP *r, double txn);
  102. static int SendDeleteStream(RTMP *r, double dStreamId);
  103. static int SendFCSubscribe(RTMP *r, AVal *subscribepath);
  104. static int SendPlay(RTMP *r);
  105. static int SendBytesReceived(RTMP *r);
  106. static int SendUsherToken(RTMP *r, AVal *usherToken);
  107. static int SendFCUnpublish(RTMP *r);
  108. #if 0 /* unused */
  109. static int SendBGHasStream(RTMP *r, double dId, AVal *playpath);
  110. #endif
  111. static int HandleInvoke(RTMP *r, const char *body, unsigned int nBodySize);
  112. static int HandleMetadata(RTMP *r, char *body, unsigned int len);
  113. static void HandleChangeChunkSize(RTMP *r, const RTMPPacket *packet);
  114. static void HandleAudio(RTMP *r, const RTMPPacket *packet);
  115. static void HandleVideo(RTMP *r, const RTMPPacket *packet);
  116. static void HandleCtrl(RTMP *r, const RTMPPacket *packet);
  117. static void HandleServerBW(RTMP *r, const RTMPPacket *packet);
  118. static void HandleClientBW(RTMP *r, const RTMPPacket *packet);
  119. static int ReadN(RTMP *r, char *buffer, int n);
  120. static int WriteN(RTMP *r, const char *buffer, int n);
  121. static void DecodeTEA(AVal *key, AVal *text);
  122. static int HTTP_Post(RTMP *r, RTMPTCmd cmd, const char *buf, int len);
  123. static int HTTP_read(RTMP *r, int fill);
  124. #if !defined(_WIN32) && !defined(_DEBUG)
  125. static int clk_tck;
  126. #endif
  127. #ifdef CRYPTO
  128. #include "handshake.h"
  129. #endif
  130. uint32_t
  131. RTMP_GetTime()
  132. {
  133. #ifdef _DEBUG
  134. return 0;
  135. #elif defined(_WIN32)
  136. return timeGetTime();
  137. #else
  138. struct tms t;
  139. if (!clk_tck) clk_tck = sysconf(_SC_CLK_TCK);
  140. return times(&t) * 1000 / clk_tck;
  141. #endif
  142. }
  143. const char *
  144. socketerror(int err)
  145. {
  146. static char buff[1024];
  147. #ifdef _WIN32
  148. if (FormatMessageA (FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, buff, sizeof(buff), NULL))
  149. {
  150. int i, len;
  151. buff[sizeof(buff)-1] = '\0';
  152. len = (int)strlen (buff);
  153. for (i = 0; i < len; i++)
  154. {
  155. if (buff[i] == '\r' || buff[i] == '\n')
  156. {
  157. memmove (buff + i, buff + i + 1, len - i);
  158. i--;
  159. len--;
  160. }
  161. }
  162. return buff;
  163. }
  164. #else
  165. (void)err;
  166. #endif
  167. strcpy (buff, "unknown error");
  168. return buff;
  169. }
  170. void
  171. RTMP_UserInterrupt()
  172. {
  173. RTMP_ctrlC = TRUE;
  174. }
  175. void
  176. RTMPPacket_Reset(RTMPPacket *p)
  177. {
  178. p->m_headerType = 0;
  179. p->m_packetType = 0;
  180. p->m_nChannel = 0;
  181. p->m_nTimeStamp = 0;
  182. p->m_nInfoField2 = 0;
  183. p->m_hasAbsTimestamp = FALSE;
  184. p->m_nBodySize = 0;
  185. p->m_nBytesRead = 0;
  186. }
  187. int
  188. RTMPPacket_Alloc(RTMPPacket *p, int nSize)
  189. {
  190. char *ptr = calloc(1, nSize + RTMP_MAX_HEADER_SIZE);
  191. if (!ptr)
  192. return FALSE;
  193. p->m_body = ptr + RTMP_MAX_HEADER_SIZE;
  194. p->m_nBytesRead = 0;
  195. return TRUE;
  196. }
  197. void
  198. RTMPPacket_Free(RTMPPacket *p)
  199. {
  200. if (p->m_body)
  201. {
  202. free(p->m_body - RTMP_MAX_HEADER_SIZE);
  203. p->m_body = NULL;
  204. }
  205. }
  206. void
  207. RTMPPacket_Dump(RTMPPacket *p)
  208. {
  209. RTMP_Log(RTMP_LOGDEBUG,
  210. "RTMP PACKET: packet type: 0x%02x. channel: 0x%02x. info 1: %d info 2: %d. Body size: %u. body: 0x%02x",
  211. p->m_packetType, p->m_nChannel, p->m_nTimeStamp, p->m_nInfoField2,
  212. p->m_nBodySize, p->m_body ? (unsigned char)p->m_body[0] : 0);
  213. }
  214. int
  215. RTMP_LibVersion()
  216. {
  217. return RTMP_LIB_VERSION;
  218. }
  219. void
  220. RTMP_TLS_Init()
  221. {
  222. #ifdef CRYPTO
  223. #ifdef USE_POLARSSL
  224. /* Do this regardless of NO_SSL, we use havege for rtmpe too */
  225. RTMP_TLS_ctx = calloc(1,sizeof(struct tls_ctx));
  226. havege_init(&RTMP_TLS_ctx->hs);
  227. #elif defined(USE_GNUTLS) && !defined(NO_SSL)
  228. /* Technically we need to initialize libgcrypt ourselves if
  229. * we're not going to call gnutls_global_init(). Ignoring this
  230. * for now.
  231. */
  232. gnutls_global_init();
  233. RTMP_TLS_ctx = malloc(sizeof(struct tls_ctx));
  234. gnutls_certificate_allocate_credentials(&RTMP_TLS_ctx->cred);
  235. gnutls_priority_init(&RTMP_TLS_ctx->prios, "NORMAL", NULL);
  236. gnutls_certificate_set_x509_trust_file(RTMP_TLS_ctx->cred,
  237. "ca.pem", GNUTLS_X509_FMT_PEM);
  238. #elif !defined(NO_SSL) /* USE_OPENSSL */
  239. /* libcrypto doesn't need anything special */
  240. SSL_load_error_strings();
  241. SSL_library_init();
  242. OpenSSL_add_all_digests();
  243. RTMP_TLS_ctx = SSL_CTX_new(SSLv23_method());
  244. SSL_CTX_set_options(RTMP_TLS_ctx, SSL_OP_ALL);
  245. SSL_CTX_set_default_verify_paths(RTMP_TLS_ctx);
  246. #endif
  247. #endif
  248. }
  249. void *
  250. RTMP_TLS_AllocServerContext(const char* cert, const char* key)
  251. {
  252. void *ctx = NULL;
  253. #ifdef CRYPTO
  254. if (!RTMP_TLS_ctx)
  255. RTMP_TLS_Init();
  256. #ifdef USE_POLARSSL
  257. tls_server_ctx *tc = ctx = calloc(1, sizeof(struct tls_server_ctx));
  258. tc->dhm_P = my_dhm_P;
  259. tc->dhm_G = my_dhm_G;
  260. tc->hs = &RTMP_TLS_ctx->hs;
  261. if (x509parse_crtfile(&tc->cert, cert))
  262. {
  263. free(tc);
  264. return NULL;
  265. }
  266. if (x509parse_keyfile(&tc->key, key, NULL))
  267. {
  268. x509_free(&tc->cert);
  269. free(tc);
  270. return NULL;
  271. }
  272. #elif defined(USE_GNUTLS) && !defined(NO_SSL)
  273. gnutls_certificate_allocate_credentials((gnutls_certificate_credentials*) &ctx);
  274. if (gnutls_certificate_set_x509_key_file(ctx, cert, key, GNUTLS_X509_FMT_PEM) != 0)
  275. {
  276. gnutls_certificate_free_credentials(ctx);
  277. return NULL;
  278. }
  279. #elif !defined(NO_SSL) /* USE_OPENSSL */
  280. ctx = SSL_CTX_new(SSLv23_server_method());
  281. if (!SSL_CTX_use_certificate_chain_file(ctx, cert))
  282. {
  283. SSL_CTX_free(ctx);
  284. return NULL;
  285. }
  286. if (!SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM))
  287. {
  288. SSL_CTX_free(ctx);
  289. return NULL;
  290. }
  291. #endif
  292. #else
  293. (void)cert;
  294. (void)key;
  295. #endif
  296. return ctx;
  297. }
  298. void
  299. RTMP_TLS_FreeServerContext(void *ctx)
  300. {
  301. #ifdef CRYPTO
  302. #ifdef USE_POLARSSL
  303. x509_free(&((tls_server_ctx*)ctx)->cert);
  304. rsa_free(&((tls_server_ctx*)ctx)->key);
  305. free(ctx);
  306. #elif defined(USE_GNUTLS) && !defined(NO_SSL)
  307. gnutls_certificate_free_credentials(ctx);
  308. #elif !defined(NO_SSL) /* USE_OPENSSL */
  309. SSL_CTX_free(ctx);
  310. #endif
  311. #else
  312. (void)ctx;
  313. #endif
  314. }
  315. RTMP *
  316. RTMP_Alloc()
  317. {
  318. return calloc(1, sizeof(RTMP));
  319. }
  320. void
  321. RTMP_Free(RTMP *r)
  322. {
  323. free(r);
  324. }
  325. void
  326. RTMP_Init(RTMP *r)
  327. {
  328. #ifdef CRYPTO
  329. if (!RTMP_TLS_ctx)
  330. RTMP_TLS_Init();
  331. #endif
  332. memset(r, 0, sizeof(RTMP));
  333. r->m_sb.sb_socket = -1;
  334. r->m_inChunkSize = RTMP_DEFAULT_CHUNKSIZE;
  335. r->m_outChunkSize = RTMP_DEFAULT_CHUNKSIZE;
  336. r->m_bSendChunkSizeInfo = 1;
  337. r->m_nBufferMS = 30000;
  338. r->m_nClientBW = 2500000;
  339. r->m_nClientBW2 = 2;
  340. r->m_nServerBW = 2500000;
  341. r->m_fAudioCodecs = 3191.0;
  342. r->m_fVideoCodecs = 252.0;
  343. r->Link.timeout = 30;
  344. r->Link.swfAge = 30;
  345. }
  346. void
  347. RTMP_EnableWrite(RTMP *r)
  348. {
  349. r->Link.protocol |= RTMP_FEATURE_WRITE;
  350. }
  351. double
  352. RTMP_GetDuration(RTMP *r)
  353. {
  354. return r->m_fDuration;
  355. }
  356. int
  357. RTMP_IsConnected(RTMP *r)
  358. {
  359. return r->m_sb.sb_socket != -1;
  360. }
  361. SOCKET
  362. RTMP_Socket(RTMP *r)
  363. {
  364. return r->m_sb.sb_socket;
  365. }
  366. int
  367. RTMP_IsTimedout(RTMP *r)
  368. {
  369. return r->m_sb.sb_timedout;
  370. }
  371. void
  372. RTMP_SetBufferMS(RTMP *r, int size)
  373. {
  374. r->m_nBufferMS = size;
  375. }
  376. void
  377. RTMP_UpdateBufferMS(RTMP *r)
  378. {
  379. RTMP_SendCtrl(r, 3, r->m_stream_id, r->m_nBufferMS);
  380. }
  381. #undef OSS
  382. #ifdef _WIN32
  383. #define OSS "WIN"
  384. #elif defined(__sun__)
  385. #define OSS "SOL"
  386. #elif defined(__APPLE__)
  387. #define OSS "MAC"
  388. #elif defined(__linux__)
  389. #define OSS "LNX"
  390. #else
  391. #define OSS "GNU"
  392. #endif
  393. #define DEF_VERSTR OSS " 10,0,32,18"
  394. static const char DEFAULT_FLASH_VER[] = DEF_VERSTR;
  395. const AVal RTMP_DefaultFlashVer =
  396. { (char *)DEFAULT_FLASH_VER, sizeof(DEFAULT_FLASH_VER) - 1 };
  397. static void
  398. SocksSetup(RTMP *r, AVal *sockshost)
  399. {
  400. if (sockshost->av_len)
  401. {
  402. const char *socksport = strchr(sockshost->av_val, ':');
  403. char *hostname = strdup(sockshost->av_val);
  404. if (socksport)
  405. hostname[socksport - sockshost->av_val] = '\0';
  406. r->Link.sockshost.av_val = hostname;
  407. r->Link.sockshost.av_len = (int)strlen(hostname);
  408. r->Link.socksport = socksport ? atoi(socksport + 1) : 1080;
  409. RTMP_Log(RTMP_LOGDEBUG, "Connecting via SOCKS proxy: %s:%d", r->Link.sockshost.av_val,
  410. r->Link.socksport);
  411. }
  412. else
  413. {
  414. r->Link.sockshost.av_val = NULL;
  415. r->Link.sockshost.av_len = 0;
  416. r->Link.socksport = 0;
  417. }
  418. }
  419. void
  420. RTMP_SetupStream(RTMP *r,
  421. int protocol,
  422. AVal *host,
  423. unsigned int port,
  424. AVal *sockshost,
  425. AVal *playpath,
  426. AVal *tcUrl,
  427. AVal *swfUrl,
  428. AVal *pageUrl,
  429. AVal *app,
  430. AVal *auth,
  431. AVal *swfSHA256Hash,
  432. uint32_t swfSize,
  433. AVal *flashVer,
  434. AVal *subscribepath,
  435. AVal *usherToken,
  436. int dStart,
  437. int dStop, int bLiveStream, long int timeout)
  438. {
  439. RTMP_Log(RTMP_LOGDEBUG, "Protocol : %s", RTMPProtocolStrings[protocol&7]);
  440. RTMP_Log(RTMP_LOGDEBUG, "Hostname : %.*s", host->av_len, host->av_val);
  441. RTMP_Log(RTMP_LOGDEBUG, "Port : %d", port);
  442. RTMP_Log(RTMP_LOGDEBUG, "Playpath : %s", playpath->av_val);
  443. if (tcUrl && tcUrl->av_val)
  444. RTMP_Log(RTMP_LOGDEBUG, "tcUrl : %s", tcUrl->av_val);
  445. if (swfUrl && swfUrl->av_val)
  446. RTMP_Log(RTMP_LOGDEBUG, "swfUrl : %s", swfUrl->av_val);
  447. if (pageUrl && pageUrl->av_val)
  448. RTMP_Log(RTMP_LOGDEBUG, "pageUrl : %s", pageUrl->av_val);
  449. if (app && app->av_val)
  450. RTMP_Log(RTMP_LOGDEBUG, "app : %.*s", app->av_len, app->av_val);
  451. if (auth && auth->av_val)
  452. RTMP_Log(RTMP_LOGDEBUG, "auth : %s", auth->av_val);
  453. if (subscribepath && subscribepath->av_val)
  454. RTMP_Log(RTMP_LOGDEBUG, "subscribepath : %s", subscribepath->av_val);
  455. if (usherToken && usherToken->av_val)
  456. RTMP_Log(RTMP_LOGDEBUG, "NetStream.Authenticate.UsherToken : %s", usherToken->av_val);
  457. if (flashVer && flashVer->av_val)
  458. RTMP_Log(RTMP_LOGDEBUG, "flashVer : %s", flashVer->av_val);
  459. if (dStart > 0)
  460. RTMP_Log(RTMP_LOGDEBUG, "StartTime : %d msec", dStart);
  461. if (dStop > 0)
  462. RTMP_Log(RTMP_LOGDEBUG, "StopTime : %d msec", dStop);
  463. RTMP_Log(RTMP_LOGDEBUG, "live : %s", bLiveStream ? "yes" : "no");
  464. RTMP_Log(RTMP_LOGDEBUG, "timeout : %ld sec", timeout);
  465. #ifdef CRYPTO
  466. if (swfSHA256Hash != NULL && swfSize > 0)
  467. {
  468. memcpy(r->Link.SWFHash, swfSHA256Hash->av_val, sizeof(r->Link.SWFHash));
  469. r->Link.SWFSize = swfSize;
  470. RTMP_Log(RTMP_LOGDEBUG, "SWFSHA256:");
  471. RTMP_LogHex(RTMP_LOGDEBUG, r->Link.SWFHash, sizeof(r->Link.SWFHash));
  472. RTMP_Log(RTMP_LOGDEBUG, "SWFSize : %u", r->Link.SWFSize);
  473. }
  474. else
  475. {
  476. r->Link.SWFSize = 0;
  477. }
  478. #else
  479. (void)swfSHA256Hash;
  480. (void)swfSize;
  481. #endif
  482. SocksSetup(r, sockshost);
  483. if (tcUrl && tcUrl->av_len)
  484. r->Link.tcUrl = *tcUrl;
  485. if (swfUrl && swfUrl->av_len)
  486. r->Link.swfUrl = *swfUrl;
  487. if (pageUrl && pageUrl->av_len)
  488. r->Link.pageUrl = *pageUrl;
  489. if (app && app->av_len)
  490. r->Link.app = *app;
  491. if (auth && auth->av_len)
  492. {
  493. r->Link.auth = *auth;
  494. r->Link.lFlags |= RTMP_LF_AUTH;
  495. }
  496. if (flashVer && flashVer->av_len)
  497. r->Link.flashVer = *flashVer;
  498. else
  499. r->Link.flashVer = RTMP_DefaultFlashVer;
  500. if (subscribepath && subscribepath->av_len)
  501. r->Link.subscribepath = *subscribepath;
  502. if (usherToken && usherToken->av_len)
  503. r->Link.usherToken = *usherToken;
  504. r->Link.seekTime = dStart;
  505. r->Link.stopTime = dStop;
  506. if (bLiveStream)
  507. r->Link.lFlags |= RTMP_LF_LIVE;
  508. r->Link.timeout = timeout;
  509. r->Link.protocol = protocol;
  510. r->Link.hostname = *host;
  511. r->Link.port = port;
  512. r->Link.playpath = *playpath;
  513. if (r->Link.port == 0)
  514. {
  515. if (protocol & RTMP_FEATURE_SSL)
  516. r->Link.port = 443;
  517. else if (protocol & RTMP_FEATURE_HTTP)
  518. r->Link.port = 80;
  519. else
  520. r->Link.port = 1935;
  521. }
  522. }
  523. enum { OPT_STR=0, OPT_INT, OPT_BOOL, OPT_CONN };
  524. static const char *optinfo[] =
  525. {
  526. "string", "integer", "boolean", "AMF"
  527. };
  528. #define OFF(x) offsetof(struct RTMP,x)
  529. static struct urlopt
  530. {
  531. AVal name;
  532. off_t off;
  533. int otype;
  534. int omisc;
  535. char *use;
  536. } options[] =
  537. {
  538. {
  539. AVC("socks"), OFF(Link.sockshost), OPT_STR, 0,
  540. "Use the specified SOCKS proxy"
  541. },
  542. {
  543. AVC("app"), OFF(Link.app), OPT_STR, 0,
  544. "Name of target app on server"
  545. },
  546. {
  547. AVC("tcUrl"), OFF(Link.tcUrl), OPT_STR, 0,
  548. "URL to played stream"
  549. },
  550. {
  551. AVC("pageUrl"), OFF(Link.pageUrl), OPT_STR, 0,
  552. "URL of played media's web page"
  553. },
  554. {
  555. AVC("swfUrl"), OFF(Link.swfUrl), OPT_STR, 0,
  556. "URL to player SWF file"
  557. },
  558. {
  559. AVC("flashver"), OFF(Link.flashVer), OPT_STR, 0,
  560. "Flash version string (default " DEF_VERSTR ")"
  561. },
  562. {
  563. AVC("conn"), OFF(Link.extras), OPT_CONN, 0,
  564. "Append arbitrary AMF data to Connect message"
  565. },
  566. {
  567. AVC("playpath"), OFF(Link.playpath), OPT_STR, 0,
  568. "Path to target media on server"
  569. },
  570. {
  571. AVC("playlist"), OFF(Link.lFlags), OPT_BOOL, RTMP_LF_PLST,
  572. "Set playlist before play command"
  573. },
  574. {
  575. AVC("live"), OFF(Link.lFlags), OPT_BOOL, RTMP_LF_LIVE,
  576. "Stream is live, no seeking possible"
  577. },
  578. {
  579. AVC("subscribe"), OFF(Link.subscribepath), OPT_STR, 0,
  580. "Stream to subscribe to"
  581. },
  582. {
  583. AVC("jtv"), OFF(Link.usherToken), OPT_STR, 0,
  584. "Justin.tv authentication token"
  585. },
  586. {
  587. AVC("token"), OFF(Link.token), OPT_STR, 0,
  588. "Key for SecureToken response"
  589. },
  590. {
  591. AVC("swfVfy"), OFF(Link.lFlags), OPT_BOOL, RTMP_LF_SWFV,
  592. "Perform SWF Verification"
  593. },
  594. {
  595. AVC("swfAge"), OFF(Link.swfAge), OPT_INT, 0,
  596. "Number of days to use cached SWF hash"
  597. },
  598. {
  599. AVC("start"), OFF(Link.seekTime), OPT_INT, 0,
  600. "Stream start position in milliseconds"
  601. },
  602. {
  603. AVC("stop"), OFF(Link.stopTime), OPT_INT, 0,
  604. "Stream stop position in milliseconds"
  605. },
  606. {
  607. AVC("buffer"), OFF(m_nBufferMS), OPT_INT, 0,
  608. "Buffer time in milliseconds"
  609. },
  610. {
  611. AVC("timeout"), OFF(Link.timeout), OPT_INT, 0,
  612. "Session timeout in seconds"
  613. },
  614. {
  615. AVC("pubUser"), OFF(Link.pubUser), OPT_STR, 0,
  616. "Publisher username"
  617. },
  618. {
  619. AVC("pubPasswd"), OFF(Link.pubPasswd), OPT_STR, 0,
  620. "Publisher password"
  621. },
  622. { {NULL,0}, 0, 0}
  623. };
  624. static const AVal truth[] =
  625. {
  626. AVC("1"),
  627. AVC("on"),
  628. AVC("yes"),
  629. AVC("true"),
  630. {0,0}
  631. };
  632. static void RTMP_OptUsage()
  633. {
  634. int i;
  635. RTMP_Log(RTMP_LOGERROR, "Valid RTMP options are:\n");
  636. for (i=0; options[i].name.av_len; i++)
  637. {
  638. RTMP_Log(RTMP_LOGERROR, "%10s %-7s %s\n", options[i].name.av_val,
  639. optinfo[options[i].otype], options[i].use);
  640. }
  641. }
  642. static int
  643. parseAMF(AMFObject *obj, AVal *av, int *depth)
  644. {
  645. AMFObjectProperty prop = {{0,0}};
  646. int i;
  647. char *p, *arg = av->av_val;
  648. if (arg[1] == ':')
  649. {
  650. p = (char *)arg+2;
  651. switch(arg[0])
  652. {
  653. case 'B':
  654. prop.p_type = AMF_BOOLEAN;
  655. prop.p_vu.p_number = atoi(p);
  656. break;
  657. case 'S':
  658. prop.p_type = AMF_STRING;
  659. prop.p_vu.p_aval.av_val = p;
  660. prop.p_vu.p_aval.av_len = av->av_len - (p-arg);
  661. break;
  662. case 'N':
  663. prop.p_type = AMF_NUMBER;
  664. prop.p_vu.p_number = strtod(p, NULL);
  665. break;
  666. case 'Z':
  667. prop.p_type = AMF_NULL;
  668. break;
  669. case 'O':
  670. i = atoi(p);
  671. if (i)
  672. {
  673. prop.p_type = AMF_OBJECT;
  674. }
  675. else
  676. {
  677. (*depth)--;
  678. return 0;
  679. }
  680. break;
  681. default:
  682. return -1;
  683. }
  684. }
  685. else if (arg[2] == ':' && arg[0] == 'N')
  686. {
  687. p = strchr(arg+3, ':');
  688. if (!p || !*depth)
  689. return -1;
  690. prop.p_name.av_val = (char *)arg+3;
  691. prop.p_name.av_len = p - (arg+3);
  692. p++;
  693. switch(arg[1])
  694. {
  695. case 'B':
  696. prop.p_type = AMF_BOOLEAN;
  697. prop.p_vu.p_number = atoi(p);
  698. break;
  699. case 'S':
  700. prop.p_type = AMF_STRING;
  701. prop.p_vu.p_aval.av_val = p;
  702. prop.p_vu.p_aval.av_len = av->av_len - (p-arg);
  703. break;
  704. case 'N':
  705. prop.p_type = AMF_NUMBER;
  706. prop.p_vu.p_number = strtod(p, NULL);
  707. break;
  708. case 'O':
  709. prop.p_type = AMF_OBJECT;
  710. break;
  711. default:
  712. return -1;
  713. }
  714. }
  715. else
  716. return -1;
  717. if (*depth)
  718. {
  719. AMFObject *o2;
  720. for (i=0; i<*depth; i++)
  721. {
  722. o2 = &obj->o_props[obj->o_num-1].p_vu.p_object;
  723. obj = o2;
  724. }
  725. }
  726. AMF_AddProp(obj, &prop);
  727. if (prop.p_type == AMF_OBJECT)
  728. (*depth)++;
  729. return 0;
  730. }
  731. int RTMP_SetOpt(RTMP *r, const AVal *opt, AVal *arg)
  732. {
  733. int i;
  734. void *v;
  735. for (i=0; options[i].name.av_len; i++)
  736. {
  737. if (opt->av_len != options[i].name.av_len) continue;
  738. if (strcasecmp(opt->av_val, options[i].name.av_val)) continue;
  739. v = (char *)r + options[i].off;
  740. switch(options[i].otype)
  741. {
  742. case OPT_STR:
  743. {
  744. AVal *aptr = v;
  745. *aptr = *arg;
  746. }
  747. break;
  748. case OPT_INT:
  749. {
  750. long l = strtol(arg->av_val, NULL, 0);
  751. *(int *)v = l;
  752. }
  753. break;
  754. case OPT_BOOL:
  755. {
  756. int j, fl;
  757. fl = *(int *)v;
  758. for (j=0; truth[j].av_len; j++)
  759. {
  760. if (arg->av_len != truth[j].av_len) continue;
  761. if (strcasecmp(arg->av_val, truth[j].av_val)) continue;
  762. fl |= options[i].omisc;
  763. break;
  764. }
  765. *(int *)v = fl;
  766. }
  767. break;
  768. case OPT_CONN:
  769. if (parseAMF(&r->Link.extras, arg, &r->Link.edepth))
  770. return FALSE;
  771. break;
  772. }
  773. break;
  774. }
  775. if (!options[i].name.av_len)
  776. {
  777. RTMP_Log(RTMP_LOGERROR, "Unknown option %s", opt->av_val);
  778. RTMP_OptUsage();
  779. return FALSE;
  780. }
  781. return TRUE;
  782. }
  783. int RTMP_SetupURL(RTMP *r, char *url)
  784. {
  785. AVal opt, arg;
  786. char *p1, *p2, *ptr = strchr(url, ' ');
  787. int ret, len;
  788. unsigned int port = 0;
  789. if (ptr)
  790. *ptr = '\0';
  791. len = (int)strlen(url);
  792. ret = RTMP_ParseURL(url, &r->Link.protocol, &r->Link.hostname,
  793. &port, &r->Link.playpath0, &r->Link.app);
  794. if (!ret)
  795. return ret;
  796. r->Link.port = port;
  797. r->Link.playpath = r->Link.playpath0;
  798. while (ptr)
  799. {
  800. *ptr++ = '\0';
  801. p1 = ptr;
  802. p2 = strchr(p1, '=');
  803. if (!p2)
  804. break;
  805. opt.av_val = p1;
  806. opt.av_len = p2 - p1;
  807. *p2++ = '\0';
  808. arg.av_val = p2;
  809. ptr = strchr(p2, ' ');
  810. if (ptr)
  811. {
  812. *ptr = '\0';
  813. arg.av_len = ptr - p2;
  814. /* skip repeated spaces */
  815. while(ptr[1] == ' ')
  816. *ptr++ = '\0';
  817. }
  818. else
  819. {
  820. arg.av_len = (int)strlen(p2);
  821. }
  822. /* unescape */
  823. port = arg.av_len;
  824. for (p1=p2; port >0;)
  825. {
  826. if (*p1 == '\\')
  827. {
  828. unsigned int c;
  829. if (port < 3)
  830. return FALSE;
  831. sscanf(p1+1, "%02x", &c);
  832. *p2++ = c;
  833. port -= 3;
  834. p1 += 3;
  835. }
  836. else
  837. {
  838. *p2++ = *p1++;
  839. port--;
  840. }
  841. }
  842. arg.av_len = p2 - arg.av_val;
  843. ret = RTMP_SetOpt(r, &opt, &arg);
  844. if (!ret)
  845. return ret;
  846. }
  847. if (!r->Link.tcUrl.av_len)
  848. {
  849. r->Link.tcUrl.av_val = url;
  850. if (r->Link.app.av_len)
  851. {
  852. if (r->Link.app.av_val < url + len)
  853. {
  854. /* if app is part of original url, just use it */
  855. r->Link.tcUrl.av_len = r->Link.app.av_len + (r->Link.app.av_val - url);
  856. }
  857. else
  858. {
  859. len = r->Link.hostname.av_len + r->Link.app.av_len +
  860. sizeof("rtmpte://:65535/");
  861. r->Link.tcUrl.av_val = malloc(len);
  862. r->Link.tcUrl.av_len = snprintf(r->Link.tcUrl.av_val, len,
  863. "%s://%.*s:%d/%.*s",
  864. RTMPProtocolStringsLower[r->Link.protocol],
  865. r->Link.hostname.av_len, r->Link.hostname.av_val,
  866. r->Link.port,
  867. r->Link.app.av_len, r->Link.app.av_val);
  868. r->Link.lFlags |= RTMP_LF_FTCU;
  869. }
  870. }
  871. else
  872. {
  873. r->Link.tcUrl.av_len = (int)strlen(url);
  874. }
  875. }
  876. #ifdef CRYPTO
  877. if ((r->Link.lFlags & RTMP_LF_SWFV) && r->Link.swfUrl.av_len)
  878. RTMP_HashSWF(r->Link.swfUrl.av_val, &r->Link.SWFSize,
  879. (unsigned char *)r->Link.SWFHash, r->Link.swfAge);
  880. #endif
  881. SocksSetup(r, &r->Link.sockshost);
  882. if (r->Link.port == 0)
  883. {
  884. if (r->Link.protocol & RTMP_FEATURE_SSL)
  885. r->Link.port = 443;
  886. else if (r->Link.protocol & RTMP_FEATURE_HTTP)
  887. r->Link.port = 80;
  888. else
  889. r->Link.port = 1935;
  890. }
  891. return TRUE;
  892. }
  893. int RTMP_SetupURL2(RTMP *r, char *url, char *playpath)
  894. {
  895. AVal opt, arg;
  896. char *p1, *p2, *ptr = strchr(url, ' ');
  897. int ret, len;
  898. unsigned int port = 0;
  899. if (ptr)
  900. *ptr = '\0';
  901. len = (int)strlen(url);
  902. ret = RTMP_ParseURL2(url, &r->Link.protocol, &r->Link.hostname,
  903. &port, &r->Link.app);
  904. if (!ret)
  905. return ret;
  906. r->Link.port = port;
  907. if(playpath && *playpath)
  908. {
  909. AVal pp = {playpath, (int)strlen(playpath)};
  910. RTMP_ParsePlaypath(&pp, &r->Link.playpath0);
  911. }
  912. r->Link.playpath = r->Link.playpath0;
  913. while (ptr)
  914. {
  915. *ptr++ = '\0';
  916. p1 = ptr;
  917. p2 = strchr(p1, '=');
  918. if (!p2)
  919. break;
  920. opt.av_val = p1;
  921. opt.av_len = p2 - p1;
  922. *p2++ = '\0';
  923. arg.av_val = p2;
  924. ptr = strchr(p2, ' ');
  925. if (ptr)
  926. {
  927. *ptr = '\0';
  928. arg.av_len = ptr - p2;
  929. /* skip repeated spaces */
  930. while(ptr[1] == ' ')
  931. *ptr++ = '\0';
  932. }
  933. else
  934. {
  935. arg.av_len = (int)strlen(p2);
  936. }
  937. /* unescape */
  938. port = arg.av_len;
  939. for (p1=p2; port >0;)
  940. {
  941. if (*p1 == '\\')
  942. {
  943. unsigned int c;
  944. if (port < 3)
  945. return FALSE;
  946. sscanf(p1+1, "%02x", &c);
  947. *p2++ = c;
  948. port -= 3;
  949. p1 += 3;
  950. }
  951. else
  952. {
  953. *p2++ = *p1++;
  954. port--;
  955. }
  956. }
  957. arg.av_len = p2 - arg.av_val;
  958. ret = RTMP_SetOpt(r, &opt, &arg);
  959. if (!ret)
  960. return ret;
  961. }
  962. if (!r->Link.tcUrl.av_len)
  963. {
  964. r->Link.tcUrl.av_val = url;
  965. if (r->Link.app.av_len)
  966. {
  967. if (r->Link.app.av_val < url + len)
  968. {
  969. /* if app is part of original url, just use it */
  970. r->Link.tcUrl.av_len = r->Link.app.av_len + (r->Link.app.av_val - url);
  971. }
  972. else
  973. {
  974. len = r->Link.hostname.av_len + r->Link.app.av_len +
  975. sizeof("rtmpte://:65535/");
  976. r->Link.tcUrl.av_val = malloc(len);
  977. r->Link.tcUrl.av_len = snprintf(r->Link.tcUrl.av_val, len,
  978. "%s://%.*s:%d/%.*s",
  979. RTMPProtocolStringsLower[r->Link.protocol],
  980. r->Link.hostname.av_len, r->Link.hostname.av_val,
  981. r->Link.port,
  982. r->Link.app.av_len, r->Link.app.av_val);
  983. r->Link.lFlags |= RTMP_LF_FTCU;
  984. }
  985. }
  986. else
  987. {
  988. r->Link.tcUrl.av_len = (int)strlen(url);
  989. }
  990. }
  991. #ifdef CRYPTO
  992. if ((r->Link.lFlags & RTMP_LF_SWFV) && r->Link.swfUrl.av_len)
  993. RTMP_HashSWF(r->Link.swfUrl.av_val, &r->Link.SWFSize,
  994. (unsigned char *)r->Link.SWFHash, r->Link.swfAge);
  995. #endif
  996. SocksSetup(r, &r->Link.sockshost);
  997. if (r->Link.port == 0)
  998. {
  999. if (r->Link.protocol & RTMP_FEATURE_SSL)
  1000. r->Link.port = 443;
  1001. else if (r->Link.protocol & RTMP_FEATURE_HTTP)
  1002. r->Link.port = 80;
  1003. else
  1004. r->Link.port = 1935;
  1005. }
  1006. return TRUE;
  1007. }
  1008. static int
  1009. add_addr_info(struct sockaddr_in *service, AVal *host, int port)
  1010. {
  1011. char *hostname;
  1012. int ret = TRUE;
  1013. if (host->av_val[host->av_len])
  1014. {
  1015. hostname = malloc(host->av_len+1);
  1016. memcpy(hostname, host->av_val, host->av_len);
  1017. hostname[host->av_len] = '\0';
  1018. }
  1019. else
  1020. {
  1021. hostname = host->av_val;
  1022. }
  1023. service->sin_addr.s_addr = inet_addr(hostname);
  1024. if (service->sin_addr.s_addr == INADDR_NONE)
  1025. {
  1026. struct hostent *host = gethostbyname(hostname);
  1027. if (host == NULL || host->h_addr == NULL)
  1028. {
  1029. RTMP_Log(RTMP_LOGERROR, "Problem accessing the DNS. (addr: %s, error: %d)", hostname, GetSockError());
  1030. ret = FALSE;
  1031. goto finish;
  1032. }
  1033. service->sin_addr = *(struct in_addr *)host->h_addr;
  1034. }
  1035. service->sin_port = htons(port);
  1036. finish:
  1037. if (hostname != host->av_val)
  1038. free(hostname);
  1039. return ret;
  1040. }
  1041. #ifdef _WIN32
  1042. #define E_TIMEDOUT WSAETIMEDOUT
  1043. #define E_CONNREFUSED WSAECONNREFUSED
  1044. #define E_ACCES WSAEACCES
  1045. #else
  1046. #define E_TIMEDOUT ETIMEDOUT
  1047. #define E_CONNREFUSED ECONNREFUSED
  1048. #define E_ACCES EACCES
  1049. #endif
  1050. int
  1051. RTMP_Connect0(RTMP *r, struct sockaddr * service)
  1052. {
  1053. int on = 1;
  1054. r->m_sb.sb_timedout = FALSE;
  1055. r->m_pausing = 0;
  1056. r->m_fDuration = 0.0;
  1057. //best to be explicit, we need overlapped socket
  1058. #ifdef _WIN32
  1059. r->m_sb.sb_socket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
  1060. #else
  1061. r->m_sb.sb_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  1062. #endif
  1063. if (r->m_sb.sb_socket != -1)
  1064. {
  1065. if(r->m_bindIP.addrLen)
  1066. {
  1067. if (bind(r->m_sb.sb_socket, (const struct sockaddr *)&r->m_bindIP.addr, r->m_bindIP.addrLen) < 0)
  1068. {
  1069. int err = GetSockError();
  1070. RTMP_Log(RTMP_LOGERROR, "%s, failed to bind socket: %s (%d)",
  1071. __FUNCTION__, socketerror(err), err);
  1072. RTMP_Close(r);
  1073. return FALSE;
  1074. }
  1075. }
  1076. if (connect(r->m_sb.sb_socket, service, sizeof(struct sockaddr)) < 0)
  1077. {
  1078. int err = GetSockError();
  1079. if (err == E_CONNREFUSED)
  1080. RTMP_Log(RTMP_LOGERROR, "%s is offline. Try a different server (ECONNREFUSED).", r->Link.hostname.av_val);
  1081. else if (err == E_ACCES)
  1082. RTMP_Log(RTMP_LOGERROR, "The connection is being blocked by a firewall or other security software (EACCES).");
  1083. else if (err == E_TIMEDOUT)
  1084. RTMP_Log(RTMP_LOGERROR, "The connection timed out. Try a different server, or check that the connection is not being blocked by a firewall or other security software (ETIMEDOUT).");
  1085. else
  1086. RTMP_Log(RTMP_LOGERROR, "%s, failed to connect socket: %s (%d)",
  1087. __FUNCTION__, socketerror(err), err);
  1088. RTMP_Close(r);
  1089. return FALSE;
  1090. }
  1091. if (r->Link.socksport)
  1092. {
  1093. RTMP_Log(RTMP_LOGDEBUG, "%s ... SOCKS negotiation", __FUNCTION__);
  1094. if (!SocksNegotiate(r))
  1095. {
  1096. RTMP_Log(RTMP_LOGERROR, "%s, SOCKS negotiation failed.", __FUNCTION__);
  1097. RTMP_Close(r);
  1098. return FALSE;
  1099. }
  1100. }
  1101. }
  1102. else
  1103. {
  1104. RTMP_Log(RTMP_LOGERROR, "%s, failed to create socket. Error: %d", __FUNCTION__,
  1105. GetSockError());
  1106. return FALSE;
  1107. }
  1108. /* set timeout */
  1109. {
  1110. SET_RCVTIMEO(tv, r->Link.timeout);
  1111. if (setsockopt
  1112. (r->m_sb.sb_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)))
  1113. {
  1114. RTMP_Log(RTMP_LOGERROR, "%s, Setting socket timeout to %ds failed!",
  1115. __FUNCTION__, r->Link.timeout);
  1116. }
  1117. }
  1118. if(!r->m_bUseNagle)
  1119. setsockopt(r->m_sb.sb_socket, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof(on));
  1120. return TRUE;
  1121. }
  1122. int
  1123. RTMP_TLS_Accept(RTMP *r, void *ctx)
  1124. {
  1125. #if defined(CRYPTO) && !defined(NO_SSL)
  1126. TLS_server(ctx, r->m_sb.sb_ssl);
  1127. TLS_setfd(r->m_sb.sb_ssl, r->m_sb.sb_socket);
  1128. if (TLS_accept(r->m_sb.sb_ssl) < 0)
  1129. {
  1130. RTMP_Log(RTMP_LOGERROR, "%s, TLS_Connect failed", __FUNCTION__);
  1131. return FALSE;
  1132. }
  1133. return TRUE;
  1134. #else
  1135. (void)r;
  1136. (void)ctx;
  1137. return FALSE;
  1138. #endif
  1139. }
  1140. int
  1141. RTMP_Connect1(RTMP *r, RTMPPacket *cp)
  1142. {
  1143. if (r->Link.protocol & RTMP_FEATURE_SSL)
  1144. {
  1145. #if defined(CRYPTO) && !defined(NO_SSL)
  1146. TLS_client(RTMP_TLS_ctx, r->m_sb.sb_ssl);
  1147. TLS_setfd(r->m_sb.sb_ssl, r->m_sb.sb_socket);
  1148. if (TLS_connect(r->m_sb.sb_ssl) < 0)
  1149. {
  1150. RTMP_Log(RTMP_LOGERROR, "%s, TLS_Connect failed", __FUNCTION__);
  1151. RTMP_Close(r);
  1152. return FALSE;
  1153. }
  1154. #else
  1155. RTMP_Log(RTMP_LOGERROR, "%s, no SSL/TLS support", __FUNCTION__);
  1156. RTMP_Close(r);
  1157. return FALSE;
  1158. #endif
  1159. }
  1160. if (r->Link.protocol & RTMP_FEATURE_HTTP)
  1161. {
  1162. r->m_msgCounter = 1;
  1163. r->m_clientID.av_val = NULL;
  1164. r->m_clientID.av_len = 0;
  1165. HTTP_Post(r, RTMPT_OPEN, "", 1);
  1166. if (HTTP_read(r, 1) != 0)
  1167. {
  1168. r->m_msgCounter = 0;
  1169. RTMP_Log(RTMP_LOGDEBUG, "%s, Could not connect for handshake", __FUNCTION__);
  1170. RTMP_Close(r);
  1171. return 0;
  1172. }
  1173. r->m_msgCounter = 0;
  1174. }
  1175. RTMP_Log(RTMP_LOGDEBUG, "%s, ... connected, handshaking", __FUNCTION__);
  1176. if (!HandShake(r, TRUE))
  1177. {
  1178. RTMP_Log(RTMP_LOGERROR, "%s, handshake failed.", __FUNCTION__);
  1179. RTMP_Close(r);
  1180. return FALSE;
  1181. }
  1182. RTMP_Log(RTMP_LOGDEBUG, "%s, handshaked", __FUNCTION__);
  1183. if (!SendConnectPacket(r, cp))
  1184. {
  1185. RTMP_Log(RTMP_LOGERROR, "%s, RTMP connect failed.", __FUNCTION__);
  1186. RTMP_Close(r);
  1187. return FALSE;
  1188. }
  1189. return TRUE;
  1190. }
  1191. int
  1192. RTMP_Connect(RTMP *r, RTMPPacket *cp)
  1193. {
  1194. struct sockaddr_in service;
  1195. if (!r->Link.hostname.av_len)
  1196. return FALSE;
  1197. memset(&service, 0, sizeof(struct sockaddr_in));
  1198. service.sin_family = AF_INET;
  1199. if (r->Link.socksport)
  1200. {
  1201. /* Connect via SOCKS */
  1202. if (!add_addr_info(&service, &r->Link.sockshost, r->Link.socksport))
  1203. return FALSE;
  1204. }
  1205. else
  1206. {
  1207. /* Connect directly */
  1208. if (!add_addr_info(&service, &r->Link.hostname, r->Link.port))
  1209. return FALSE;
  1210. }
  1211. if (!RTMP_Connect0(r, (struct sockaddr *)&service))
  1212. return FALSE;
  1213. r->m_bSendCounter = TRUE;
  1214. return RTMP_Connect1(r, cp);
  1215. }
  1216. static int
  1217. SocksNegotiate(RTMP *r)
  1218. {
  1219. unsigned long addr;
  1220. struct sockaddr_in service;
  1221. memset(&service, 0, sizeof(struct sockaddr_in));
  1222. add_addr_info(&service, &r->Link.hostname, r->Link.port);
  1223. addr = htonl(service.sin_addr.s_addr);
  1224. {
  1225. char packet[] =
  1226. {
  1227. 4, 1, /* SOCKS 4, connect */
  1228. (r->Link.port >> 8) & 0xFF,
  1229. (r->Link.port) & 0xFF,
  1230. (char)(addr >> 24) & 0xFF, (char)(addr >> 16) & 0xFF,
  1231. (char)(addr >> 8) & 0xFF, (char)addr & 0xFF,
  1232. 0
  1233. }; /* NULL terminate */
  1234. WriteN(r, packet, sizeof packet);
  1235. if (ReadN(r, packet, 8) != 8)
  1236. return FALSE;
  1237. if (packet[0] == 0 && packet[1] == 90)
  1238. {
  1239. return TRUE;
  1240. }
  1241. else
  1242. {
  1243. RTMP_Log(RTMP_LOGERROR, "%s, SOCKS returned error code %d", __FUNCTION__, packet[1]);
  1244. return FALSE;
  1245. }
  1246. }
  1247. }
  1248. int
  1249. RTMP_ConnectStream(RTMP *r, int seekTime)
  1250. {
  1251. RTMPPacket packet = { 0 };
  1252. /* seekTime was already set by SetupStream / SetupURL.
  1253. * This is only needed by ReconnectStream.
  1254. */
  1255. if (seekTime > 0)
  1256. r->Link.seekTime = seekTime;
  1257. r->m_mediaChannel = 0;
  1258. while (!r->m_bPlaying && RTMP_IsConnected(r) && RTMP_ReadPacket(r, &packet))
  1259. {
  1260. if (RTMPPacket_IsReady(&packet))
  1261. {
  1262. if (!packet.m_nBodySize)
  1263. continue;
  1264. if ((packet.m_packetType == RTMP_PACKET_TYPE_AUDIO) ||
  1265. (packet.m_packetType == RTMP_PACKET_TYPE_VIDEO) ||
  1266. (packet.m_packetType == RTMP_PACKET_TYPE_INFO))
  1267. {
  1268. RTMP_Log(RTMP_LOGWARNING, "Received FLV packet before play()! Ignoring.");
  1269. RTMPPacket_Free(&packet);
  1270. continue;
  1271. }
  1272. RTMP_ClientPacket(r, &packet);
  1273. RTMPPacket_Free(&packet);
  1274. }
  1275. }
  1276. return r->m_bPlaying;
  1277. }
  1278. int
  1279. RTMP_ReconnectStream(RTMP *r, int seekTime)
  1280. {
  1281. RTMP_DeleteStream(r);
  1282. RTMP_SendCreateStream(r);
  1283. return RTMP_ConnectStream(r, seekTime);
  1284. }
  1285. int
  1286. RTMP_ToggleStream(RTMP *r)
  1287. {
  1288. int res;
  1289. if (!r->m_pausing)
  1290. {
  1291. if (RTMP_IsTimedout(r) && r->m_read.status == RTMP_READ_EOF)
  1292. r->m_read.status = 0;
  1293. res = RTMP_SendPause(r, TRUE, r->m_pauseStamp);
  1294. if (!res)
  1295. return res;
  1296. r->m_pausing = 1;
  1297. sleep(1);
  1298. }
  1299. res = RTMP_SendPause(r, FALSE, r->m_pauseStamp);
  1300. r->m_pausing = 3;
  1301. return res;
  1302. }
  1303. void
  1304. RTMP_DeleteStream(RTMP *r)
  1305. {
  1306. if (r->m_stream_id < 0)
  1307. return;
  1308. r->m_bPlaying = FALSE;
  1309. if ((r->Link.protocol & RTMP_FEATURE_WRITE))
  1310. SendFCUnpublish(r);
  1311. SendDeleteStream(r, r->m_stream_id);
  1312. r->m_stream_id = -1;
  1313. }
  1314. int
  1315. RTMP_GetNextMediaPacket(RTMP *r, RTMPPacket *packet)
  1316. {
  1317. int bHasMediaPacket = 0;
  1318. while (!bHasMediaPacket && RTMP_IsConnected(r)
  1319. && RTMP_ReadPacket(r, packet))
  1320. {
  1321. if (!RTMPPacket_IsReady(packet))
  1322. {
  1323. continue;
  1324. }
  1325. bHasMediaPacket = RTMP_ClientPacket(r, packet);
  1326. if (!bHasMediaPacket)
  1327. {
  1328. RTMPPacket_Free(packet);
  1329. }
  1330. else if (r->m_pausing == 3)
  1331. {
  1332. if (packet->m_nTimeStamp <= r->m_mediaStamp)
  1333. {
  1334. bHasMediaPacket = 0;
  1335. #ifdef _DEBUG
  1336. RTMP_Log(RTMP_LOGDEBUG,
  1337. "Skipped type: %02X, size: %d, TS: %d ms, abs TS: %d, pause: %d ms",
  1338. packet->m_packetType, packet->m_nBodySize,
  1339. packet->m_nTimeStamp, packet->m_hasAbsTimestamp,
  1340. r->m_mediaStamp);
  1341. #endif
  1342. RTMPPacket_Free(packet);
  1343. continue;
  1344. }
  1345. r->m_pausing = 0;
  1346. }
  1347. }
  1348. if (bHasMediaPacket)
  1349. r->m_bPlaying = TRUE;
  1350. else if (r->m_sb.sb_timedout && !r->m_pausing)
  1351. r->m_pauseStamp = r->m_mediaChannel < r->m_channelsAllocatedIn ?
  1352. r->m_channelTimestamp[r->m_mediaChannel] : 0;
  1353. return bHasMediaPacket;
  1354. }
  1355. int
  1356. RTMP_ClientPacket(RTMP *r, RTMPPacket *packet)
  1357. {
  1358. int bHasMediaPacket = 0;
  1359. switch (packet->m_packetType)
  1360. {
  1361. case RTMP_PACKET_TYPE_CHUNK_SIZE:
  1362. /* chunk size */
  1363. HandleChangeChunkSize(r, packet);
  1364. break;
  1365. case RTMP_PACKET_TYPE_BYTES_READ_REPORT:
  1366. /* bytes read report */
  1367. RTMP_Log(RTMP_LOGDEBUG, "%s, received: bytes read report", __FUNCTION__);
  1368. break;
  1369. case RTMP_PACKET_TYPE_CONTROL:
  1370. /* ctrl */
  1371. HandleCtrl(r, packet);
  1372. break;
  1373. case RTMP_PACKET_TYPE_SERVER_BW:
  1374. /* server bw */
  1375. HandleServerBW(r, packet);
  1376. break;
  1377. case RTMP_PACKET_TYPE_CLIENT_BW:
  1378. /* client bw */
  1379. HandleClientBW(r, packet);
  1380. break;
  1381. case RTMP_PACKET_TYPE_AUDIO:
  1382. /* audio data */
  1383. /*RTMP_Log(RTMP_LOGDEBUG, "%s, received: audio %lu bytes", __FUNCTION__, packet.m_nBodySize); */
  1384. HandleAudio(r, packet);
  1385. bHasMediaPacket = 1;
  1386. if (!r->m_mediaChannel)
  1387. r->m_mediaChannel = packet->m_nChannel;
  1388. if (!r->m_pausing)
  1389. r->m_mediaStamp = packet->m_nTimeStamp;
  1390. break;
  1391. case RTMP_PACKET_TYPE_VIDEO:
  1392. /* video data */
  1393. /*RTMP_Log(RTMP_LOGDEBUG, "%s, received: video %lu bytes", __FUNCTION__, packet.m_nBodySize); */
  1394. HandleVideo(r, packet);
  1395. bHasMediaPacket = 1;
  1396. if (!r->m_mediaChannel)
  1397. r->m_mediaChannel = packet->m_nChannel;
  1398. if (!r->m_pausing)
  1399. r->m_mediaStamp = packet->m_nTimeStamp;
  1400. break;
  1401. case RTMP_PACKET_TYPE_FLEX_STREAM_SEND:
  1402. /* flex stream send */
  1403. RTMP_Log(RTMP_LOGDEBUG,
  1404. "%s, flex stream send, size %u bytes, not supported, ignoring",
  1405. __FUNCTION__, packet->m_nBodySize);
  1406. break;
  1407. case RTMP_PACKET_TYPE_FLEX_SHARED_OBJECT:
  1408. /* flex shared object */
  1409. RTMP_Log(RTMP_LOGDEBUG,
  1410. "%s, flex shared object, size %u bytes, not supported, ignoring",
  1411. __FUNCTION__, packet->m_nBodySize);
  1412. break;
  1413. case RTMP_PACKET_TYPE_FLEX_MESSAGE:
  1414. /* flex message */
  1415. {
  1416. RTMP_Log(RTMP_LOGDEBUG,
  1417. "%s, flex message, size %u bytes, not fully supported",
  1418. __FUNCTION__, packet->m_nBodySize);
  1419. /*RTMP_LogHex(packet.m_body, packet.m_nBodySize); */
  1420. /* some DEBUG code */
  1421. #if 0
  1422. RTMP_LIB_AMFObject obj;
  1423. int nRes = obj.Decode(packet.m_body+1, packet.m_nBodySize-1);
  1424. if(nRes < 0)
  1425. {
  1426. RTMP_Log(RTMP_LOGERROR, "%s, error decoding AMF3 packet", __FUNCTION__);
  1427. /*return; */
  1428. }
  1429. obj.Dump();
  1430. #endif
  1431. if (HandleInvoke(r, packet->m_body + 1, packet->m_nBodySize - 1) == 1)
  1432. bHasMediaPacket = 2;
  1433. break;
  1434. }
  1435. case RTMP_PACKET_TYPE_INFO:
  1436. /* metadata (notify) */
  1437. RTMP_Log(RTMP_LOGDEBUG, "%s, received: notify %u bytes", __FUNCTION__,
  1438. packet->m_nBodySize);
  1439. if (HandleMetadata(r, packet->m_body, packet->m_nBodySize))
  1440. bHasMediaPacket = 1;
  1441. break;
  1442. case RTMP_PACKET_TYPE_SHARED_OBJECT:
  1443. RTMP_Log(RTMP_LOGDEBUG, "%s, shared object, not supported, ignoring",
  1444. __FUNCTION__);
  1445. break;
  1446. case RTMP_PACKET_TYPE_INVOKE:
  1447. /* invoke */
  1448. RTMP_Log(RTMP_LOGDEBUG, "%s, received: invoke %u bytes", __FUNCTION__,
  1449. packet->m_nBodySize);
  1450. /*RTMP_LogHex(packet.m_body, packet.m_nBodySize); */
  1451. if (HandleInvoke(r, packet->m_body, packet->m_nBodySize) == 1)
  1452. bHasMediaPacket = 2;
  1453. break;
  1454. case RTMP_PACKET_TYPE_FLASH_VIDEO:
  1455. {
  1456. /* go through FLV packets and handle metadata packets */
  1457. unsigned int pos = 0;
  1458. uint32_t nTimeStamp = packet->m_nTimeStamp;
  1459. while (pos + 11 < packet->m_nBodySize)
  1460. {
  1461. uint32_t dataSize = AMF_DecodeInt24(packet->m_body + pos + 1); /* size without header (11) and prevTagSize (4) */
  1462. if (pos + 11 + dataSize + 4 > packet->m_nBodySize)
  1463. {
  1464. RTMP_Log(RTMP_LOGWARNING, "Stream corrupt?!");
  1465. break;
  1466. }
  1467. if (packet->m_body[pos] == 0x12)
  1468. {
  1469. HandleMetadata(r, packet->m_body + pos + 11, dataSize);
  1470. }
  1471. else if (packet->m_body[pos] == 8 || packet->m_body[pos] == 9)
  1472. {
  1473. nTimeStamp = AMF_DecodeInt24(packet->m_body + pos + 4);
  1474. nTimeStamp |= (packet->m_body[pos + 7] << 24);
  1475. }
  1476. pos += (11 + dataSize + 4);
  1477. }
  1478. if (!r->m_pausing)
  1479. r->m_mediaStamp = nTimeStamp;
  1480. /* FLV tag(s) */
  1481. /*RTMP_Log(RTMP_LOGDEBUG, "%s, received: FLV tag(s) %lu bytes", __FUNCTION__, packet.m_nBodySize); */
  1482. bHasMediaPacket = 1;
  1483. break;
  1484. }
  1485. default:
  1486. RTMP_Log(RTMP_LOGDEBUG, "%s, unknown packet type received: 0x%02x", __FUNCTION__,
  1487. packet->m_packetType);
  1488. #ifdef _DEBUG
  1489. RTMP_LogHex(RTMP_LOGDEBUG, (uint8_t*)packet->m_body, packet->m_nBodySize);
  1490. #endif
  1491. }
  1492. return bHasMediaPacket;
  1493. }
  1494. #if defined(RTMP_NETSTACK_DUMP)
  1495. extern FILE *netstackdump;
  1496. extern FILE *netstackdump_read;
  1497. #endif
  1498. static int
  1499. ReadN(RTMP *r, char *buffer, int n)
  1500. {
  1501. int nOriginalSize = n;
  1502. int avail;
  1503. char *ptr;
  1504. r->m_sb.sb_timedout = FALSE;
  1505. #ifdef _DEBUG
  1506. memset(buffer, 0, n);
  1507. #endif
  1508. ptr = buffer;
  1509. while (n > 0)
  1510. {
  1511. int nBytes = 0, nRead;
  1512. if (r->Link.protocol & RTMP_FEATURE_HTTP)
  1513. {
  1514. int refill = 0;
  1515. while (!r->m_resplen)
  1516. {
  1517. int ret;
  1518. if (r->m_sb.sb_size < 13 || refill)
  1519. {
  1520. if (!r->m_unackd)
  1521. HTTP_Post(r, RTMPT_IDLE, "", 1);
  1522. if (RTMPSockBuf_Fill(&r->m_sb) < 1)
  1523. {
  1524. if (!r->m_sb.sb_timedout)
  1525. RTMP_Close(r);
  1526. return 0;
  1527. }
  1528. }
  1529. if ((ret = HTTP_read(r, 0)) == -1)
  1530. {
  1531. RTMP_Log(RTMP_LOGDEBUG, "%s, No valid HTTP response found", __FUNCTION__);
  1532. RTMP_Close(r);
  1533. return 0;
  1534. }
  1535. else if (ret == -2)
  1536. {
  1537. refill = 1;
  1538. }
  1539. else
  1540. {
  1541. refill = 0;
  1542. }
  1543. }
  1544. if (r->m_resplen && !r->m_sb.sb_size)
  1545. RTMPSockBuf_Fill(&r->m_sb);
  1546. avail = r->m_sb.sb_size;
  1547. if (avail > r->m_resplen)
  1548. avail = r->m_resplen;
  1549. }
  1550. else
  1551. {
  1552. avail = r->m_sb.sb_size;
  1553. if (avail == 0)
  1554. {
  1555. if (RTMPSockBuf_Fill(&r->m_sb) < 1)
  1556. {
  1557. if (!r->m_sb.sb_timedout)
  1558. RTMP_Close(r);
  1559. return 0;
  1560. }
  1561. avail = r->m_sb.sb_size;
  1562. }
  1563. }
  1564. nRead = ((n < avail) ? n : avail);
  1565. if (nRead > 0)
  1566. {
  1567. memcpy(ptr, r->m_sb.sb_start, nRead);
  1568. r->m_sb.sb_start += nRead;
  1569. r->m_sb.sb_size -= nRead;
  1570. nBytes = nRead;
  1571. r->m_nBytesIn += nRead;
  1572. if (r->m_bSendCounter
  1573. && r->m_nBytesIn > ( r->m_nBytesInSent + r->m_nClientBW / 10))
  1574. if (!SendBytesReceived(r))
  1575. return FALSE;
  1576. }
  1577. /*RTMP_Log(RTMP_LOGDEBUG, "%s: %d bytes\n", __FUNCTION__, nBytes); */
  1578. #if defined(RTMP_NETSTACK_DUMP)
  1579. fwrite(ptr, 1, nBytes, netstackdump_read);
  1580. #endif
  1581. if (nBytes == 0)
  1582. {
  1583. RTMP_Log(RTMP_LOGDEBUG, "%s, RTMP socket closed by peer", __FUNCTION__);
  1584. /*goto again; */
  1585. RTMP_Close(r);
  1586. break;
  1587. }
  1588. if (r->Link.protocol & RTMP_FEATURE_HTTP)
  1589. r->m_resplen -= nBytes;
  1590. #ifdef CRYPTO
  1591. if (r->Link.rc4keyIn)
  1592. {
  1593. RC4_encrypt(r->Link.rc4keyIn, nBytes, ptr);
  1594. }
  1595. #endif
  1596. n -= nBytes;
  1597. ptr += nBytes;
  1598. }
  1599. return nOriginalSize - n;
  1600. }
  1601. static int
  1602. WriteN(RTMP *r, const char *buffer, int n)
  1603. {
  1604. const char *ptr = buffer;
  1605. #ifdef CRYPTO
  1606. char *encrypted = 0;
  1607. char buf[RTMP_BUFFER_CACHE_SIZE];
  1608. if (r->Link.rc4keyOut)
  1609. {
  1610. if (n > sizeof(buf))
  1611. encrypted = (char *)malloc(n);
  1612. else
  1613. encrypted = (char *)buf;
  1614. ptr = encrypted;
  1615. RC4_encrypt2(r->Link.rc4keyOut, n, buffer, ptr);
  1616. }
  1617. #endif
  1618. while (n > 0)
  1619. {
  1620. int nBytes;
  1621. if (r->Link.protocol & RTMP_FEATURE_HTTP)
  1622. nBytes = HTTP_Post(r, RTMPT_SEND, ptr, n);
  1623. else if(r->m_bCustomSend && r->m_customSendFunc)
  1624. nBytes = r->m_customSendFunc(&r->m_sb, ptr, n, r->m_customSendParam);
  1625. else
  1626. nBytes = RTMPSockBuf_Send(&r->m_sb, ptr, n);
  1627. /*RTMP_Log(RTMP_LOGDEBUG, "%s: %d\n", __FUNCTION__, nBytes); */
  1628. if (nBytes < 0)
  1629. {
  1630. int sockerr = GetSockError();
  1631. RTMP_Log(RTMP_LOGERROR, "%s, RTMP send error %d (%d bytes)", __FUNCTION__,
  1632. sockerr, n);
  1633. if (sockerr == EINTR && !RTMP_ctrlC)
  1634. continue;
  1635. RTMP_Close(r);
  1636. n = 1;
  1637. break;
  1638. }
  1639. if (nBytes == 0)
  1640. break;
  1641. n -= nBytes;
  1642. ptr += nBytes;
  1643. }
  1644. #ifdef CRYPTO
  1645. if (encrypted && encrypted != buf)
  1646. free(encrypted);
  1647. #endif
  1648. return n == 0;
  1649. }
  1650. #define SAVC(x) static const AVal av_##x = AVC(#x)
  1651. SAVC(app);
  1652. SAVC(connect);
  1653. SAVC(flashVer);
  1654. SAVC(swfUrl);
  1655. SAVC(pageUrl);
  1656. SAVC(tcUrl);
  1657. SAVC(fpad);
  1658. SAVC(capabilities);
  1659. SAVC(audioCodecs);
  1660. SAVC(videoCodecs);
  1661. SAVC(videoFunction);
  1662. SAVC(objectEncoding);
  1663. SAVC(secureToken);
  1664. SAVC(secureTokenResponse);
  1665. SAVC(type);
  1666. SAVC(nonprivate);
  1667. static int
  1668. SendConnectPacket(RTMP *r, RTMPPacket *cp)
  1669. {
  1670. RTMPPacket packet;
  1671. char pbuf[4096], *pend = pbuf + sizeof(pbuf);
  1672. char *enc;
  1673. if (cp)
  1674. return RTMP_SendPacket(r, cp, TRUE);
  1675. if((r->Link.protocol & RTMP_FEATURE_WRITE) && r->m_bSendChunkSizeInfo)
  1676. {
  1677. packet.m_nChannel = 0x02;
  1678. packet.m_headerType = RTMP_PACKET_SIZE_LARGE;
  1679. packet.m_packetType = RTMP_PACKET_TYPE_CHUNK_SIZE;
  1680. packet.m_nTimeStamp = 0;
  1681. packet.m_nInfoField2 = 0;
  1682. packet.m_hasAbsTimestamp = 0;
  1683. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  1684. packet.m_nBodySize = 4;
  1685. enc = packet.m_body;
  1686. AMF_EncodeInt32(enc, pend, r->m_outChunkSize);
  1687. if(!RTMP_SendPacket(r, &packet, FALSE))
  1688. return 0;
  1689. }
  1690. packet.m_nChannel = 0x03; /* control channel (invoke) */
  1691. packet.m_headerType = RTMP_PACKET_SIZE_LARGE;
  1692. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  1693. packet.m_nTimeStamp = 0;
  1694. packet.m_nInfoField2 = 0;
  1695. packet.m_hasAbsTimestamp = 0;
  1696. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  1697. enc = packet.m_body;
  1698. enc = AMF_EncodeString(enc, pend, &av_connect);
  1699. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  1700. *enc++ = AMF_OBJECT;
  1701. enc = AMF_EncodeNamedString(enc, pend, &av_app, &r->Link.app);
  1702. if (!enc)
  1703. return FALSE;
  1704. if (r->Link.protocol & RTMP_FEATURE_WRITE)
  1705. {
  1706. enc = AMF_EncodeNamedString(enc, pend, &av_type, &av_nonprivate);
  1707. if (!enc)
  1708. return FALSE;
  1709. }
  1710. if (r->Link.flashVer.av_len)
  1711. {
  1712. enc = AMF_EncodeNamedString(enc, pend, &av_flashVer, &r->Link.flashVer);
  1713. if (!enc)
  1714. return FALSE;
  1715. }
  1716. if (r->Link.swfUrl.av_len)
  1717. {
  1718. enc = AMF_EncodeNamedString(enc, pend, &av_swfUrl, &r->Link.swfUrl);
  1719. if (!enc)
  1720. return FALSE;
  1721. }
  1722. if (r->Link.tcUrl.av_len)
  1723. {
  1724. enc = AMF_EncodeNamedString(enc, pend, &av_tcUrl, &r->Link.tcUrl);
  1725. if (!enc)
  1726. return FALSE;
  1727. }
  1728. if (!(r->Link.protocol & RTMP_FEATURE_WRITE))
  1729. {
  1730. enc = AMF_EncodeNamedBoolean(enc, pend, &av_fpad, FALSE);
  1731. if (!enc)
  1732. return FALSE;
  1733. enc = AMF_EncodeNamedNumber(enc, pend, &av_capabilities, 15.0);
  1734. if (!enc)
  1735. return FALSE;
  1736. enc = AMF_EncodeNamedNumber(enc, pend, &av_audioCodecs, r->m_fAudioCodecs);
  1737. if (!enc)
  1738. return FALSE;
  1739. enc = AMF_EncodeNamedNumber(enc, pend, &av_videoCodecs, r->m_fVideoCodecs);
  1740. if (!enc)
  1741. return FALSE;
  1742. enc = AMF_EncodeNamedNumber(enc, pend, &av_videoFunction, 1.0);
  1743. if (!enc)
  1744. return FALSE;
  1745. if (r->Link.pageUrl.av_len)
  1746. {
  1747. enc = AMF_EncodeNamedString(enc, pend, &av_pageUrl, &r->Link.pageUrl);
  1748. if (!enc)
  1749. return FALSE;
  1750. }
  1751. }
  1752. if (r->m_fEncoding != 0.0 || r->m_bSendEncoding)
  1753. {
  1754. /* AMF0, AMF3 not fully supported yet */
  1755. enc = AMF_EncodeNamedNumber(enc, pend, &av_objectEncoding, r->m_fEncoding);
  1756. if (!enc)
  1757. return FALSE;
  1758. }
  1759. if (enc + 3 >= pend)
  1760. return FALSE;
  1761. *enc++ = 0;
  1762. *enc++ = 0; /* end of object - 0x00 0x00 0x09 */
  1763. *enc++ = AMF_OBJECT_END;
  1764. /* add auth string */
  1765. if (r->Link.auth.av_len)
  1766. {
  1767. enc = AMF_EncodeBoolean(enc, pend, r->Link.lFlags & RTMP_LF_AUTH);
  1768. if (!enc)
  1769. return FALSE;
  1770. enc = AMF_EncodeString(enc, pend, &r->Link.auth);
  1771. if (!enc)
  1772. return FALSE;
  1773. }
  1774. if (r->Link.extras.o_num)
  1775. {
  1776. int i;
  1777. for (i = 0; i < r->Link.extras.o_num; i++)
  1778. {
  1779. enc = AMFProp_Encode(&r->Link.extras.o_props[i], enc, pend);
  1780. if (!enc)
  1781. return FALSE;
  1782. }
  1783. }
  1784. packet.m_nBodySize = enc - packet.m_body;
  1785. return RTMP_SendPacket(r, &packet, TRUE);
  1786. }
  1787. #if 0 /* unused */
  1788. SAVC(bgHasStream);
  1789. static int
  1790. SendBGHasStream(RTMP *r, double dId, AVal *playpath)
  1791. {
  1792. RTMPPacket packet;
  1793. char pbuf[1024], *pend = pbuf + sizeof(pbuf);
  1794. char *enc;
  1795. packet.m_forceChannel = FALSE;
  1796. packet.m_nChannel = 0x03; /* control channel (invoke) */
  1797. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  1798. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  1799. packet.m_nTimeStamp = 0;
  1800. packet.m_nInfoField2 = 0;
  1801. packet.m_hasAbsTimestamp = 0;
  1802. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  1803. enc = packet.m_body;
  1804. enc = AMF_EncodeString(enc, pend, &av_bgHasStream);
  1805. enc = AMF_EncodeNumber(enc, pend, dId);
  1806. *enc++ = AMF_NULL;
  1807. enc = AMF_EncodeString(enc, pend, playpath);
  1808. if (enc == NULL)
  1809. return FALSE;
  1810. packet.m_nBodySize = enc - packet.m_body;
  1811. return RTMP_SendPacket(r, &packet, TRUE);
  1812. }
  1813. #endif
  1814. SAVC(createStream);
  1815. int
  1816. RTMP_SendCreateStream(RTMP *r)
  1817. {
  1818. RTMPPacket packet;
  1819. char pbuf[256], *pend = pbuf + sizeof(pbuf);
  1820. char *enc;
  1821. packet.m_nChannel = 0x03; /* control channel (invoke) */
  1822. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  1823. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  1824. packet.m_nTimeStamp = 0;
  1825. packet.m_nInfoField2 = 0;
  1826. packet.m_hasAbsTimestamp = 0;
  1827. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  1828. enc = packet.m_body;
  1829. enc = AMF_EncodeString(enc, pend, &av_createStream);
  1830. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  1831. *enc++ = AMF_NULL; /* NULL */
  1832. packet.m_nBodySize = enc - packet.m_body;
  1833. return RTMP_SendPacket(r, &packet, TRUE);
  1834. }
  1835. SAVC(FCSubscribe);
  1836. static int
  1837. SendFCSubscribe(RTMP *r, AVal *subscribepath)
  1838. {
  1839. RTMPPacket packet;
  1840. char pbuf[512], *pend = pbuf + sizeof(pbuf);
  1841. char *enc;
  1842. packet.m_nChannel = 0x03; /* control channel (invoke) */
  1843. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  1844. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  1845. packet.m_nTimeStamp = 0;
  1846. packet.m_nInfoField2 = 0;
  1847. packet.m_hasAbsTimestamp = 0;
  1848. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  1849. RTMP_Log(RTMP_LOGDEBUG, "FCSubscribe: %s", subscribepath->av_val);
  1850. enc = packet.m_body;
  1851. enc = AMF_EncodeString(enc, pend, &av_FCSubscribe);
  1852. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  1853. *enc++ = AMF_NULL;
  1854. enc = AMF_EncodeString(enc, pend, subscribepath);
  1855. if (!enc)
  1856. return FALSE;
  1857. packet.m_nBodySize = enc - packet.m_body;
  1858. return RTMP_SendPacket(r, &packet, TRUE);
  1859. }
  1860. /* Justin.tv specific authentication */
  1861. static const AVal av_NetStream_Authenticate_UsherToken = AVC("NetStream.Authenticate.UsherToken");
  1862. static int
  1863. SendUsherToken(RTMP *r, AVal *usherToken)
  1864. {
  1865. RTMPPacket packet;
  1866. char pbuf[1024], *pend = pbuf + sizeof(pbuf);
  1867. char *enc;
  1868. packet.m_nChannel = 0x03; /* control channel (invoke) */
  1869. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  1870. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  1871. packet.m_nTimeStamp = 0;
  1872. packet.m_nInfoField2 = 0;
  1873. packet.m_hasAbsTimestamp = 0;
  1874. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  1875. RTMP_Log(RTMP_LOGDEBUG, "UsherToken: %s", usherToken->av_val);
  1876. enc = packet.m_body;
  1877. enc = AMF_EncodeString(enc, pend, &av_NetStream_Authenticate_UsherToken);
  1878. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  1879. *enc++ = AMF_NULL;
  1880. enc = AMF_EncodeString(enc, pend, usherToken);
  1881. if (!enc)
  1882. return FALSE;
  1883. packet.m_nBodySize = enc - packet.m_body;
  1884. return RTMP_SendPacket(r, &packet, FALSE);
  1885. }
  1886. /******************************************/
  1887. SAVC(releaseStream);
  1888. static int
  1889. SendReleaseStream(RTMP *r)
  1890. {
  1891. RTMPPacket packet;
  1892. char pbuf[1024], *pend = pbuf + sizeof(pbuf);
  1893. char *enc;
  1894. packet.m_nChannel = 0x03; /* control channel (invoke) */
  1895. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  1896. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  1897. packet.m_nTimeStamp = 0;
  1898. packet.m_nInfoField2 = 0;
  1899. packet.m_hasAbsTimestamp = 0;
  1900. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  1901. enc = packet.m_body;
  1902. enc = AMF_EncodeString(enc, pend, &av_releaseStream);
  1903. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  1904. *enc++ = AMF_NULL;
  1905. enc = AMF_EncodeString(enc, pend, &r->Link.playpath);
  1906. if (!enc)
  1907. return FALSE;
  1908. packet.m_nBodySize = enc - packet.m_body;
  1909. return RTMP_SendPacket(r, &packet, FALSE);
  1910. }
  1911. SAVC(FCPublish);
  1912. static int
  1913. SendFCPublish(RTMP *r)
  1914. {
  1915. RTMPPacket packet;
  1916. char pbuf[1024], *pend = pbuf + sizeof(pbuf);
  1917. char *enc;
  1918. packet.m_nChannel = 0x03; /* control channel (invoke) */
  1919. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  1920. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  1921. packet.m_nTimeStamp = 0;
  1922. packet.m_nInfoField2 = 0;
  1923. packet.m_hasAbsTimestamp = 0;
  1924. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  1925. enc = packet.m_body;
  1926. enc = AMF_EncodeString(enc, pend, &av_FCPublish);
  1927. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  1928. *enc++ = AMF_NULL;
  1929. enc = AMF_EncodeString(enc, pend, &r->Link.playpath);
  1930. if (!enc)
  1931. return FALSE;
  1932. packet.m_nBodySize = enc - packet.m_body;
  1933. return RTMP_SendPacket(r, &packet, FALSE);
  1934. }
  1935. SAVC(FCUnpublish);
  1936. static int
  1937. SendFCUnpublish(RTMP *r)
  1938. {
  1939. RTMPPacket packet;
  1940. char pbuf[1024], *pend = pbuf + sizeof(pbuf);
  1941. char *enc;
  1942. packet.m_nChannel = 0x03; /* control channel (invoke) */
  1943. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  1944. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  1945. packet.m_nTimeStamp = 0;
  1946. packet.m_nInfoField2 = 0;
  1947. packet.m_hasAbsTimestamp = 0;
  1948. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  1949. enc = packet.m_body;
  1950. enc = AMF_EncodeString(enc, pend, &av_FCUnpublish);
  1951. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  1952. *enc++ = AMF_NULL;
  1953. enc = AMF_EncodeString(enc, pend, &r->Link.playpath);
  1954. if (!enc)
  1955. return FALSE;
  1956. packet.m_nBodySize = enc - packet.m_body;
  1957. return RTMP_SendPacket(r, &packet, FALSE);
  1958. }
  1959. SAVC(publish);
  1960. SAVC(live);
  1961. #if 0
  1962. SAVC(record);
  1963. #endif
  1964. static int
  1965. SendPublish(RTMP *r)
  1966. {
  1967. RTMPPacket packet;
  1968. char pbuf[1024], *pend = pbuf + sizeof(pbuf);
  1969. char *enc;
  1970. packet.m_nChannel = 0x04; /* source channel (invoke) */
  1971. packet.m_headerType = RTMP_PACKET_SIZE_LARGE;
  1972. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  1973. packet.m_nTimeStamp = 0;
  1974. packet.m_nInfoField2 = r->m_stream_id;
  1975. packet.m_hasAbsTimestamp = 0;
  1976. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  1977. enc = packet.m_body;
  1978. enc = AMF_EncodeString(enc, pend, &av_publish);
  1979. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  1980. *enc++ = AMF_NULL;
  1981. enc = AMF_EncodeString(enc, pend, &r->Link.playpath);
  1982. if (!enc)
  1983. return FALSE;
  1984. /* FIXME: should we choose live based on Link.lFlags & RTMP_LF_LIVE? */
  1985. enc = AMF_EncodeString(enc, pend, &av_live);
  1986. if (!enc)
  1987. return FALSE;
  1988. packet.m_nBodySize = enc - packet.m_body;
  1989. return RTMP_SendPacket(r, &packet, TRUE);
  1990. }
  1991. SAVC(deleteStream);
  1992. static int
  1993. SendDeleteStream(RTMP *r, double dStreamId)
  1994. {
  1995. RTMPPacket packet;
  1996. char pbuf[256], *pend = pbuf + sizeof(pbuf);
  1997. char *enc;
  1998. packet.m_nChannel = 0x03; /* control channel (invoke) */
  1999. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  2000. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  2001. packet.m_nTimeStamp = 0;
  2002. packet.m_nInfoField2 = 0;
  2003. packet.m_hasAbsTimestamp = 0;
  2004. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2005. enc = packet.m_body;
  2006. enc = AMF_EncodeString(enc, pend, &av_deleteStream);
  2007. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  2008. *enc++ = AMF_NULL;
  2009. enc = AMF_EncodeNumber(enc, pend, dStreamId);
  2010. packet.m_nBodySize = enc - packet.m_body;
  2011. /* no response expected */
  2012. return RTMP_SendPacket(r, &packet, FALSE);
  2013. }
  2014. SAVC(pause);
  2015. int
  2016. RTMP_SendPause(RTMP *r, int DoPause, int iTime)
  2017. {
  2018. RTMPPacket packet;
  2019. char pbuf[256], *pend = pbuf + sizeof(pbuf);
  2020. char *enc;
  2021. packet.m_nChannel = 0x08; /* video channel */
  2022. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  2023. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  2024. packet.m_nTimeStamp = 0;
  2025. packet.m_nInfoField2 = 0;
  2026. packet.m_hasAbsTimestamp = 0;
  2027. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2028. enc = packet.m_body;
  2029. enc = AMF_EncodeString(enc, pend, &av_pause);
  2030. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  2031. *enc++ = AMF_NULL;
  2032. enc = AMF_EncodeBoolean(enc, pend, DoPause);
  2033. enc = AMF_EncodeNumber(enc, pend, (double)iTime);
  2034. packet.m_nBodySize = enc - packet.m_body;
  2035. RTMP_Log(RTMP_LOGDEBUG, "%s, %d, pauseTime=%d", __FUNCTION__, DoPause, iTime);
  2036. return RTMP_SendPacket(r, &packet, TRUE);
  2037. }
  2038. int RTMP_Pause(RTMP *r, int DoPause)
  2039. {
  2040. if (DoPause)
  2041. r->m_pauseStamp = r->m_mediaChannel < r->m_channelsAllocatedIn ?
  2042. r->m_channelTimestamp[r->m_mediaChannel] : 0;
  2043. return RTMP_SendPause(r, DoPause, r->m_pauseStamp);
  2044. }
  2045. SAVC(seek);
  2046. int
  2047. RTMP_SendSeek(RTMP *r, int iTime)
  2048. {
  2049. RTMPPacket packet;
  2050. char pbuf[256], *pend = pbuf + sizeof(pbuf);
  2051. char *enc;
  2052. packet.m_nChannel = 0x08; /* video channel */
  2053. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  2054. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  2055. packet.m_nTimeStamp = 0;
  2056. packet.m_nInfoField2 = 0;
  2057. packet.m_hasAbsTimestamp = 0;
  2058. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2059. enc = packet.m_body;
  2060. enc = AMF_EncodeString(enc, pend, &av_seek);
  2061. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  2062. *enc++ = AMF_NULL;
  2063. enc = AMF_EncodeNumber(enc, pend, (double)iTime);
  2064. packet.m_nBodySize = enc - packet.m_body;
  2065. r->m_read.flags |= RTMP_READ_SEEKING;
  2066. r->m_read.nResumeTS = 0;
  2067. return RTMP_SendPacket(r, &packet, TRUE);
  2068. }
  2069. int
  2070. RTMP_SendServerBW(RTMP *r)
  2071. {
  2072. RTMPPacket packet;
  2073. char pbuf[256], *pend = pbuf + sizeof(pbuf);
  2074. packet.m_nChannel = 0x02; /* control channel (invoke) */
  2075. packet.m_headerType = RTMP_PACKET_SIZE_LARGE;
  2076. packet.m_packetType = RTMP_PACKET_TYPE_SERVER_BW;
  2077. packet.m_nTimeStamp = 0;
  2078. packet.m_nInfoField2 = 0;
  2079. packet.m_hasAbsTimestamp = 0;
  2080. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2081. packet.m_nBodySize = 4;
  2082. AMF_EncodeInt32(packet.m_body, pend, r->m_nServerBW);
  2083. return RTMP_SendPacket(r, &packet, FALSE);
  2084. }
  2085. int
  2086. RTMP_SendClientBW(RTMP *r)
  2087. {
  2088. RTMPPacket packet;
  2089. char pbuf[256], *pend = pbuf + sizeof(pbuf);
  2090. packet.m_nChannel = 0x02; /* control channel (invoke) */
  2091. packet.m_headerType = RTMP_PACKET_SIZE_LARGE;
  2092. packet.m_packetType = RTMP_PACKET_TYPE_CLIENT_BW;
  2093. packet.m_nTimeStamp = 0;
  2094. packet.m_nInfoField2 = 0;
  2095. packet.m_hasAbsTimestamp = 0;
  2096. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2097. packet.m_nBodySize = 5;
  2098. AMF_EncodeInt32(packet.m_body, pend, r->m_nClientBW);
  2099. packet.m_body[4] = r->m_nClientBW2;
  2100. return RTMP_SendPacket(r, &packet, FALSE);
  2101. }
  2102. static int
  2103. SendBytesReceived(RTMP *r)
  2104. {
  2105. RTMPPacket packet;
  2106. char pbuf[256], *pend = pbuf + sizeof(pbuf);
  2107. packet.m_nChannel = 0x02; /* control channel (invoke) */
  2108. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  2109. packet.m_packetType = RTMP_PACKET_TYPE_BYTES_READ_REPORT;
  2110. packet.m_nTimeStamp = 0;
  2111. packet.m_nInfoField2 = 0;
  2112. packet.m_hasAbsTimestamp = 0;
  2113. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2114. packet.m_nBodySize = 4;
  2115. AMF_EncodeInt32(packet.m_body, pend, r->m_nBytesIn); /* hard coded for now */
  2116. r->m_nBytesInSent = r->m_nBytesIn;
  2117. /*RTMP_Log(RTMP_LOGDEBUG, "Send bytes report. 0x%x (%d bytes)", (unsigned int)m_nBytesIn, m_nBytesIn); */
  2118. return RTMP_SendPacket(r, &packet, FALSE);
  2119. }
  2120. SAVC(_checkbw);
  2121. static int
  2122. SendCheckBW(RTMP *r)
  2123. {
  2124. RTMPPacket packet;
  2125. char pbuf[256], *pend = pbuf + sizeof(pbuf);
  2126. char *enc;
  2127. packet.m_nChannel = 0x03; /* control channel (invoke) */
  2128. packet.m_headerType = RTMP_PACKET_SIZE_LARGE;
  2129. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  2130. packet.m_nTimeStamp = 0; /* RTMP_GetTime(); */
  2131. packet.m_nInfoField2 = 0;
  2132. packet.m_hasAbsTimestamp = 0;
  2133. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2134. enc = packet.m_body;
  2135. enc = AMF_EncodeString(enc, pend, &av__checkbw);
  2136. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  2137. *enc++ = AMF_NULL;
  2138. packet.m_nBodySize = enc - packet.m_body;
  2139. /* triggers _onbwcheck and eventually results in _onbwdone */
  2140. return RTMP_SendPacket(r, &packet, FALSE);
  2141. }
  2142. SAVC(_result);
  2143. static int
  2144. SendCheckBWResult(RTMP *r, double txn)
  2145. {
  2146. RTMPPacket packet;
  2147. char pbuf[256], *pend = pbuf + sizeof(pbuf);
  2148. char *enc;
  2149. packet.m_nChannel = 0x03; /* control channel (invoke) */
  2150. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  2151. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  2152. packet.m_nTimeStamp = 0x16 * r->m_nBWCheckCounter; /* temp inc value. till we figure it out. */
  2153. packet.m_nInfoField2 = 0;
  2154. packet.m_hasAbsTimestamp = 0;
  2155. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2156. enc = packet.m_body;
  2157. enc = AMF_EncodeString(enc, pend, &av__result);
  2158. enc = AMF_EncodeNumber(enc, pend, txn);
  2159. *enc++ = AMF_NULL;
  2160. enc = AMF_EncodeNumber(enc, pend, (double)r->m_nBWCheckCounter++);
  2161. packet.m_nBodySize = enc - packet.m_body;
  2162. return RTMP_SendPacket(r, &packet, FALSE);
  2163. }
  2164. SAVC(ping);
  2165. SAVC(pong);
  2166. static int
  2167. SendPong(RTMP *r, double txn)
  2168. {
  2169. RTMPPacket packet;
  2170. char pbuf[256], *pend = pbuf + sizeof(pbuf);
  2171. char *enc;
  2172. packet.m_nChannel = 0x03; /* control channel (invoke) */
  2173. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  2174. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  2175. packet.m_nTimeStamp = 0x16 * r->m_nBWCheckCounter; /* temp inc value. till we figure it out. */
  2176. packet.m_nInfoField2 = 0;
  2177. packet.m_hasAbsTimestamp = 0;
  2178. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2179. enc = packet.m_body;
  2180. enc = AMF_EncodeString(enc, pend, &av_pong);
  2181. enc = AMF_EncodeNumber(enc, pend, txn);
  2182. *enc++ = AMF_NULL;
  2183. packet.m_nBodySize = enc - packet.m_body;
  2184. return RTMP_SendPacket(r, &packet, FALSE);
  2185. }
  2186. SAVC(play);
  2187. static int
  2188. SendPlay(RTMP *r)
  2189. {
  2190. RTMPPacket packet;
  2191. char pbuf[1024], *pend = pbuf + sizeof(pbuf);
  2192. char *enc;
  2193. packet.m_nChannel = 0x08; /* we make 8 our stream channel */
  2194. packet.m_headerType = RTMP_PACKET_SIZE_LARGE;
  2195. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  2196. packet.m_nTimeStamp = 0;
  2197. packet.m_nInfoField2 = r->m_stream_id; /*0x01000000; */
  2198. packet.m_hasAbsTimestamp = 0;
  2199. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2200. enc = packet.m_body;
  2201. enc = AMF_EncodeString(enc, pend, &av_play);
  2202. enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes);
  2203. *enc++ = AMF_NULL;
  2204. RTMP_Log(RTMP_LOGDEBUG, "%s, seekTime=%d, stopTime=%d, sending play: %s",
  2205. __FUNCTION__, r->Link.seekTime, r->Link.stopTime,
  2206. r->Link.playpath.av_val);
  2207. enc = AMF_EncodeString(enc, pend, &r->Link.playpath);
  2208. if (!enc)
  2209. return FALSE;
  2210. /* Optional parameters start and len.
  2211. *
  2212. * start: -2, -1, 0, positive number
  2213. * -2: looks for a live stream, then a recorded stream,
  2214. * if not found any open a live stream
  2215. * -1: plays a live stream
  2216. * >=0: plays a recorded streams from 'start' milliseconds
  2217. */
  2218. if (r->Link.lFlags & RTMP_LF_LIVE)
  2219. enc = AMF_EncodeNumber(enc, pend, -1000.0);
  2220. else
  2221. {
  2222. if (r->Link.seekTime > 0.0)
  2223. enc = AMF_EncodeNumber(enc, pend, r->Link.seekTime); /* resume from here */
  2224. else
  2225. 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 */
  2226. }
  2227. if (!enc)
  2228. return FALSE;
  2229. /* len: -1, 0, positive number
  2230. * -1: plays live or recorded stream to the end (default)
  2231. * 0: plays a frame 'start' ms away from the beginning
  2232. * >0: plays a live or recoded stream for 'len' milliseconds
  2233. */
  2234. /*enc += EncodeNumber(enc, -1.0); */ /* len */
  2235. if (r->Link.stopTime)
  2236. {
  2237. enc = AMF_EncodeNumber(enc, pend, r->Link.stopTime - r->Link.seekTime);
  2238. if (!enc)
  2239. return FALSE;
  2240. }
  2241. packet.m_nBodySize = enc - packet.m_body;
  2242. return RTMP_SendPacket(r, &packet, TRUE);
  2243. }
  2244. SAVC(set_playlist);
  2245. SAVC(0);
  2246. static int
  2247. SendPlaylist(RTMP *r)
  2248. {
  2249. RTMPPacket packet;
  2250. char pbuf[1024], *pend = pbuf + sizeof(pbuf);
  2251. char *enc;
  2252. packet.m_nChannel = 0x08; /* we make 8 our stream channel */
  2253. packet.m_headerType = RTMP_PACKET_SIZE_LARGE;
  2254. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  2255. packet.m_nTimeStamp = 0;
  2256. packet.m_nInfoField2 = r->m_stream_id; /*0x01000000; */
  2257. packet.m_hasAbsTimestamp = 0;
  2258. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2259. enc = packet.m_body;
  2260. enc = AMF_EncodeString(enc, pend, &av_set_playlist);
  2261. enc = AMF_EncodeNumber(enc, pend, 0);
  2262. *enc++ = AMF_NULL;
  2263. *enc++ = AMF_ECMA_ARRAY;
  2264. *enc++ = 0;
  2265. *enc++ = 0;
  2266. *enc++ = 0;
  2267. *enc++ = AMF_OBJECT;
  2268. enc = AMF_EncodeNamedString(enc, pend, &av_0, &r->Link.playpath);
  2269. if (!enc)
  2270. return FALSE;
  2271. if (enc + 3 >= pend)
  2272. return FALSE;
  2273. *enc++ = 0;
  2274. *enc++ = 0;
  2275. *enc++ = AMF_OBJECT_END;
  2276. packet.m_nBodySize = enc - packet.m_body;
  2277. return RTMP_SendPacket(r, &packet, TRUE);
  2278. }
  2279. static int
  2280. SendSecureTokenResponse(RTMP *r, AVal *resp)
  2281. {
  2282. RTMPPacket packet;
  2283. char pbuf[1024], *pend = pbuf + sizeof(pbuf);
  2284. char *enc;
  2285. packet.m_nChannel = 0x03; /* control channel (invoke) */
  2286. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  2287. packet.m_packetType = RTMP_PACKET_TYPE_INVOKE;
  2288. packet.m_nTimeStamp = 0;
  2289. packet.m_nInfoField2 = 0;
  2290. packet.m_hasAbsTimestamp = 0;
  2291. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2292. enc = packet.m_body;
  2293. enc = AMF_EncodeString(enc, pend, &av_secureTokenResponse);
  2294. enc = AMF_EncodeNumber(enc, pend, 0.0);
  2295. *enc++ = AMF_NULL;
  2296. enc = AMF_EncodeString(enc, pend, resp);
  2297. if (!enc)
  2298. return FALSE;
  2299. packet.m_nBodySize = enc - packet.m_body;
  2300. return RTMP_SendPacket(r, &packet, FALSE);
  2301. }
  2302. /*
  2303. from http://jira.red5.org/confluence/display/docs/Ping:
  2304. 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.
  2305. 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.
  2306. * 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.
  2307. * type 1: Tell the stream to clear the playing buffer.
  2308. * type 3: Buffer time of the client. The third parameter is the buffer time in millisecond.
  2309. * type 4: Reset a stream. Used together with type 0 in the case of VOD. Often sent before type 0.
  2310. * type 6: Ping the client from server. The second parameter is the current time.
  2311. * type 7: Pong reply from client. The second parameter is the time the server sent with his ping request.
  2312. * type 26: SWFVerification request
  2313. * type 27: SWFVerification response
  2314. */
  2315. int
  2316. RTMP_SendCtrl(RTMP *r, short nType, unsigned int nObject, unsigned int nTime)
  2317. {
  2318. RTMPPacket packet;
  2319. char pbuf[256], *pend = pbuf + sizeof(pbuf);
  2320. int nSize;
  2321. char *buf;
  2322. RTMP_Log(RTMP_LOGDEBUG, "sending ctrl. type: 0x%04x", (unsigned short)nType);
  2323. packet.m_nChannel = 0x02; /* control channel (ping) */
  2324. packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  2325. packet.m_packetType = RTMP_PACKET_TYPE_CONTROL;
  2326. packet.m_nTimeStamp = 0; /* RTMP_GetTime(); */
  2327. packet.m_nInfoField2 = 0;
  2328. packet.m_hasAbsTimestamp = 0;
  2329. packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE;
  2330. switch(nType)
  2331. {
  2332. case 0x03:
  2333. nSize = 10;
  2334. break; /* buffer time */
  2335. case 0x1A:
  2336. nSize = 3;
  2337. break; /* SWF verify request */
  2338. case 0x1B:
  2339. nSize = 44;
  2340. break; /* SWF verify response */
  2341. default:
  2342. nSize = 6;
  2343. break;
  2344. }
  2345. packet.m_nBodySize = nSize;
  2346. buf = packet.m_body;
  2347. buf = AMF_EncodeInt16(buf, pend, nType);
  2348. if (nType == 0x1B)
  2349. {
  2350. #ifdef CRYPTO
  2351. memcpy(buf, r->Link.SWFVerificationResponse, 42);
  2352. RTMP_Log(RTMP_LOGDEBUG, "Sending SWFVerification response: ");
  2353. RTMP_LogHex(RTMP_LOGDEBUG, (uint8_t *)packet.m_body, packet.m_nBodySize);
  2354. #endif
  2355. }
  2356. else if (nType == 0x1A)
  2357. {
  2358. *buf = nObject & 0xff;
  2359. }
  2360. else
  2361. {
  2362. if (nSize > 2)
  2363. buf = AMF_EncodeInt32(buf, pend, nObject);
  2364. if (nSize > 6)
  2365. buf = AMF_EncodeInt32(buf, pend, nTime);
  2366. }
  2367. return RTMP_SendPacket(r, &packet, FALSE);
  2368. }
  2369. static void
  2370. AV_erase(RTMP_METHOD *vals, int *num, int i, int freeit)
  2371. {
  2372. if (freeit)
  2373. free(vals[i].name.av_val);
  2374. (*num)--;
  2375. for (; i < *num; i++)
  2376. {
  2377. vals[i] = vals[i + 1];
  2378. }
  2379. vals[i].name.av_val = NULL;
  2380. vals[i].name.av_len = 0;
  2381. vals[i].num = 0;
  2382. }
  2383. void
  2384. RTMP_DropRequest(RTMP *r, int i, int freeit)
  2385. {
  2386. AV_erase(r->m_methodCalls, &r->m_numCalls, i, freeit);
  2387. }
  2388. static void
  2389. AV_queue(RTMP_METHOD **vals, int *num, AVal *av, int txn)
  2390. {
  2391. char *tmp;
  2392. if (!(*num & 0x0f))
  2393. *vals = realloc(*vals, (*num + 16) * sizeof(RTMP_METHOD));
  2394. tmp = malloc(av->av_len + 1);
  2395. memcpy(tmp, av->av_val, av->av_len);
  2396. tmp[av->av_len] = '\0';
  2397. (*vals)[*num].num = txn;
  2398. (*vals)[*num].name.av_len = av->av_len;
  2399. (*vals)[(*num)++].name.av_val = tmp;
  2400. }
  2401. static void
  2402. AV_clear(RTMP_METHOD *vals, int num)
  2403. {
  2404. int i;
  2405. for (i = 0; i < num; i++)
  2406. free(vals[i].name.av_val);
  2407. free(vals);
  2408. }
  2409. #if defined(CRYPTO) || defined(USE_ONLY_MD5)
  2410. static int
  2411. b64enc(const unsigned char *input, int length, char *output, int maxsize)
  2412. {
  2413. #ifdef USE_POLARSSL
  2414. size_t buf_size = maxsize;
  2415. if(base64_encode((unsigned char *) output, &buf_size, input, length) == 0)
  2416. {
  2417. output[buf_size] = '\0';
  2418. return 1;
  2419. }
  2420. else
  2421. {
  2422. RTMP_Log(RTMP_LOGDEBUG, "%s, error", __FUNCTION__);
  2423. return 0;
  2424. }
  2425. #elif defined(USE_GNUTLS)
  2426. if (BASE64_ENCODE_RAW_LENGTH(length) <= maxsize)
  2427. base64_encode_raw((uint8_t*) output, length, input);
  2428. else
  2429. {
  2430. RTMP_Log(RTMP_LOGDEBUG, "%s, error", __FUNCTION__);
  2431. return 0;
  2432. }
  2433. #elif defined(USE_ONLY_MD5)
  2434. base64_encodestate state;
  2435. base64_init_encodestate(&state);
  2436. output += base64_encode_block((const char *)input, length, output, &state);
  2437. base64_encode_blockend(output, &state);
  2438. #else /* USE_OPENSSL */
  2439. BIO *bmem, *b64;
  2440. BUF_MEM *bptr;
  2441. b64 = BIO_new(BIO_f_base64());
  2442. bmem = BIO_new(BIO_s_mem());
  2443. b64 = BIO_push(b64, bmem);
  2444. BIO_write(b64, input, length);
  2445. if (BIO_flush(b64) == 1)
  2446. {
  2447. BIO_get_mem_ptr(b64, &bptr);
  2448. memcpy(output, bptr->data, bptr->length-1);
  2449. output[bptr->length-1] = '\0';
  2450. }
  2451. else
  2452. {
  2453. RTMP_Log(RTMP_LOGDEBUG, "%s, error", __FUNCTION__);
  2454. return 0;
  2455. }
  2456. BIO_free_all(b64);
  2457. #endif
  2458. return 1;
  2459. }
  2460. #ifdef USE_POLARSSL
  2461. #define MD5_CTX md5_context
  2462. #define MD5_Init(ctx) md5_starts(ctx)
  2463. #define MD5_Update(ctx,data,len) md5_update(ctx,(unsigned char *)data,len)
  2464. #define MD5_Final(dig,ctx) md5_finish(ctx,dig)
  2465. #elif defined(USE_GNUTLS)
  2466. typedef struct md5_ctx MD5_CTX;
  2467. #define MD5_Init(ctx) md5_init(ctx)
  2468. #define MD5_Update(ctx,data,len) md5_update(ctx,len,data)
  2469. #define MD5_Final(dig,ctx) md5_digest(ctx,MD5_DIGEST_LENGTH,dig)
  2470. #else
  2471. #endif
  2472. static const AVal av_authmod_adobe = AVC("authmod=adobe");
  2473. static const AVal av_authmod_llnw = AVC("authmod=llnw");
  2474. static void hexenc(unsigned char *inbuf, int len, char *dst)
  2475. {
  2476. char *ptr = dst;
  2477. while(len--)
  2478. {
  2479. sprintf(ptr, "%02x", *inbuf++);
  2480. ptr += 2;
  2481. }
  2482. *ptr = '\0';
  2483. }
  2484. static int
  2485. PublisherAuth(RTMP *r, AVal *description)
  2486. {
  2487. char *token_in = NULL;
  2488. char *ptr;
  2489. unsigned char md5sum_val[MD5_DIGEST_LENGTH+1];
  2490. MD5_CTX md5ctx;
  2491. int challenge2_data;
  2492. #define RESPONSE_LEN 32
  2493. #define CHALLENGE2_LEN 16
  2494. #define SALTED2_LEN (32+8+8+8)
  2495. #define B64DIGEST_LEN 24 /* 16 byte digest => 22 b64 chars + 2 chars padding */
  2496. #define B64INT_LEN 8 /* 4 byte int => 6 b64 chars + 2 chars padding */
  2497. #define HEXHASH_LEN (2*MD5_DIGEST_LENGTH)
  2498. char response[RESPONSE_LEN];
  2499. char challenge2[CHALLENGE2_LEN];
  2500. char salted2[SALTED2_LEN];
  2501. AVal pubToken;
  2502. if (strstr(description->av_val, av_authmod_adobe.av_val) != NULL)
  2503. {
  2504. if(strstr(description->av_val, "code=403 need auth") != NULL)
  2505. {
  2506. if (strstr(r->Link.app.av_val, av_authmod_adobe.av_val) != NULL)
  2507. {
  2508. RTMP_Log(RTMP_LOGERROR, "%s, wrong pubUser & pubPasswd for publisher auth", __FUNCTION__);
  2509. r->Link.pFlags |= RTMP_PUB_CLEAN;
  2510. return 0;
  2511. }
  2512. else if(r->Link.pubUser.av_len && r->Link.pubPasswd.av_len)
  2513. {
  2514. pubToken.av_val = malloc(r->Link.pubUser.av_len + av_authmod_adobe.av_len + 8);
  2515. pubToken.av_len = sprintf(pubToken.av_val, "?%s&user=%s",
  2516. av_authmod_adobe.av_val,
  2517. r->Link.pubUser.av_val);
  2518. RTMP_Log(RTMP_LOGDEBUG, "%s, pubToken1: %s", __FUNCTION__, pubToken.av_val);
  2519. r->Link.pFlags |= RTMP_PUB_NAME;
  2520. }
  2521. else
  2522. {
  2523. RTMP_Log(RTMP_LOGERROR, "%s, need to set pubUser & pubPasswd for publisher auth", __FUNCTION__);
  2524. r->Link.pFlags |= RTMP_PUB_CLEAN;
  2525. return 0;
  2526. }
  2527. }
  2528. else if((token_in = strstr(description->av_val, "?reason=needauth")) != NULL)
  2529. {
  2530. char *par, *val = NULL, *orig_ptr;
  2531. AVal user, salt, opaque, challenge, *aptr = NULL;
  2532. opaque.av_len = 0;
  2533. challenge.av_len = 0;
  2534. ptr = orig_ptr = strdup(token_in);
  2535. while (ptr)
  2536. {
  2537. par = ptr;
  2538. ptr = strchr(par, '&');
  2539. if(ptr)
  2540. *ptr++ = '\0';
  2541. val = strchr(par, '=');
  2542. if(val)
  2543. *val++ = '\0';
  2544. if (aptr)
  2545. {
  2546. aptr->av_len = par - aptr->av_val - 1;
  2547. aptr = NULL;
  2548. }
  2549. if (strcmp(par, "user") == 0)
  2550. {
  2551. user.av_val = val;
  2552. aptr = &user;
  2553. }
  2554. else if (strcmp(par, "salt") == 0)
  2555. {
  2556. salt.av_val = val;
  2557. aptr = &salt;
  2558. }
  2559. else if (strcmp(par, "opaque") == 0)
  2560. {
  2561. opaque.av_val = val;
  2562. aptr = &opaque;
  2563. }
  2564. else if (strcmp(par, "challenge") == 0)
  2565. {
  2566. challenge.av_val = val;
  2567. aptr = &challenge;
  2568. }
  2569. RTMP_Log(RTMP_LOGDEBUG, "%s, par:\"%s\" = val:\"%s\"", __FUNCTION__, par, val);
  2570. }
  2571. if (aptr)
  2572. aptr->av_len = (int)strlen(aptr->av_val);
  2573. /* hash1 = base64enc(md5(user + _aodbeAuthSalt + password)) */
  2574. MD5_Init(&md5ctx);
  2575. MD5_Update(&md5ctx, user.av_val, user.av_len);
  2576. MD5_Update(&md5ctx, salt.av_val, salt.av_len);
  2577. MD5_Update(&md5ctx, r->Link.pubPasswd.av_val, r->Link.pubPasswd.av_len);
  2578. MD5_Final(md5sum_val, &md5ctx);
  2579. RTMP_Log(RTMP_LOGDEBUG, "%s, md5(%s%s%s) =>", __FUNCTION__,
  2580. user.av_val, salt.av_val, r->Link.pubPasswd.av_val);
  2581. RTMP_LogHexString(RTMP_LOGDEBUG, md5sum_val, MD5_DIGEST_LENGTH);
  2582. b64enc(md5sum_val, MD5_DIGEST_LENGTH, salted2, SALTED2_LEN);
  2583. RTMP_Log(RTMP_LOGDEBUG, "%s, b64(md5_1) = %s", __FUNCTION__, salted2);
  2584. challenge2_data = rand();
  2585. b64enc((unsigned char *) &challenge2_data, sizeof(int), challenge2, CHALLENGE2_LEN);
  2586. RTMP_Log(RTMP_LOGDEBUG, "%s, b64(%d) = %s", __FUNCTION__, challenge2_data, challenge2);
  2587. MD5_Init(&md5ctx);
  2588. MD5_Update(&md5ctx, salted2, B64DIGEST_LEN);
  2589. /* response = base64enc(md5(hash1 + opaque + challenge2)) */
  2590. if (opaque.av_len)
  2591. MD5_Update(&md5ctx, opaque.av_val, opaque.av_len);
  2592. else if (challenge.av_len)
  2593. MD5_Update(&md5ctx, challenge.av_val, challenge.av_len);
  2594. MD5_Update(&md5ctx, challenge2, B64INT_LEN);
  2595. MD5_Final(md5sum_val, &md5ctx);
  2596. RTMP_Log(RTMP_LOGDEBUG, "%s, md5(%s%s%s) =>", __FUNCTION__,
  2597. salted2, opaque.av_len ? opaque.av_val : "", challenge2);
  2598. RTMP_LogHexString(RTMP_LOGDEBUG, md5sum_val, MD5_DIGEST_LENGTH);
  2599. b64enc(md5sum_val, MD5_DIGEST_LENGTH, response, RESPONSE_LEN);
  2600. RTMP_Log(RTMP_LOGDEBUG, "%s, b64(md5_2) = %s", __FUNCTION__, response);
  2601. /* have all hashes, create auth token for the end of app */
  2602. pubToken.av_val = malloc(32 + B64INT_LEN + B64DIGEST_LEN + opaque.av_len);
  2603. pubToken.av_len = sprintf(pubToken.av_val,
  2604. "&challenge=%s&response=%s&opaque=%s",
  2605. challenge2,
  2606. response,
  2607. opaque.av_len ? opaque.av_val : "");
  2608. RTMP_Log(RTMP_LOGDEBUG, "%s, pubToken2: %s", __FUNCTION__, pubToken.av_val);
  2609. free(orig_ptr);
  2610. r->Link.pFlags |= RTMP_PUB_RESP|RTMP_PUB_CLATE;
  2611. }
  2612. else if(strstr(description->av_val, "?reason=authfailed") != NULL)
  2613. {
  2614. RTMP_Log(RTMP_LOGERROR, "%s, Authentication failed: wrong password", __FUNCTION__);
  2615. r->Link.pFlags |= RTMP_PUB_CLEAN;
  2616. return 0;
  2617. }
  2618. else if(strstr(description->av_val, "?reason=nosuchuser") != NULL)
  2619. {
  2620. RTMP_Log(RTMP_LOGERROR, "%s, Authentication failed: no such user", __FUNCTION__);
  2621. r->Link.pFlags |= RTMP_PUB_CLEAN;
  2622. return 0;
  2623. }
  2624. else
  2625. {
  2626. RTMP_Log(RTMP_LOGERROR, "%s, Authentication failed: unknown auth mode: %s",
  2627. __FUNCTION__, description->av_val);
  2628. r->Link.pFlags |= RTMP_PUB_CLEAN;
  2629. return 0;
  2630. }
  2631. ptr = malloc(r->Link.app.av_len + pubToken.av_len);
  2632. strncpy(ptr, r->Link.app.av_val, r->Link.app.av_len);
  2633. strncpy(ptr + r->Link.app.av_len, pubToken.av_val, pubToken.av_len);
  2634. r->Link.app.av_len += pubToken.av_len;
  2635. if(r->Link.pFlags & RTMP_PUB_ALLOC)
  2636. free(r->Link.app.av_val);
  2637. r->Link.app.av_val = ptr;
  2638. ptr = malloc(r->Link.tcUrl.av_len + pubToken.av_len);
  2639. strncpy(ptr, r->Link.tcUrl.av_val, r->Link.tcUrl.av_len);
  2640. strncpy(ptr + r->Link.tcUrl.av_len, pubToken.av_val, pubToken.av_len);
  2641. r->Link.tcUrl.av_len += pubToken.av_len;
  2642. if(r->Link.pFlags & RTMP_PUB_ALLOC)
  2643. free(r->Link.tcUrl.av_val);
  2644. r->Link.tcUrl.av_val = ptr;
  2645. free(pubToken.av_val);
  2646. r->Link.pFlags |= RTMP_PUB_ALLOC;
  2647. RTMP_Log(RTMP_LOGDEBUG, "%s, new app: %.*s tcUrl: %.*s playpath: %s", __FUNCTION__,
  2648. r->Link.app.av_len, r->Link.app.av_val,
  2649. r->Link.tcUrl.av_len, r->Link.tcUrl.av_val,
  2650. r->Link.playpath.av_val);
  2651. }
  2652. else if (strstr(description->av_val, av_authmod_llnw.av_val) != NULL)
  2653. {
  2654. if(strstr(description->av_val, "code=403 need auth") != NULL)
  2655. {
  2656. /* This part seems to be the same for llnw and adobe */
  2657. if (strstr(r->Link.app.av_val, av_authmod_llnw.av_val) != NULL)
  2658. {
  2659. RTMP_Log(RTMP_LOGERROR, "%s, wrong pubUser & pubPasswd for publisher auth", __FUNCTION__);
  2660. r->Link.pFlags |= RTMP_PUB_CLEAN;
  2661. return 0;
  2662. }
  2663. else if(r->Link.pubUser.av_len && r->Link.pubPasswd.av_len)
  2664. {
  2665. pubToken.av_val = malloc(r->Link.pubUser.av_len + av_authmod_llnw.av_len + 8);
  2666. pubToken.av_len = sprintf(pubToken.av_val, "?%s&user=%s",
  2667. av_authmod_llnw.av_val,
  2668. r->Link.pubUser.av_val);
  2669. RTMP_Log(RTMP_LOGDEBUG, "%s, pubToken1: %s", __FUNCTION__, pubToken.av_val);
  2670. r->Link.pFlags |= RTMP_PUB_NAME;
  2671. }
  2672. else
  2673. {
  2674. RTMP_Log(RTMP_LOGERROR, "%s, need to set pubUser & pubPasswd for publisher auth", __FUNCTION__);
  2675. r->Link.pFlags |= RTMP_PUB_CLEAN;
  2676. return 0;
  2677. }
  2678. }
  2679. else if((token_in = strstr(description->av_val, "?reason=needauth")) != NULL)
  2680. {
  2681. char *orig_ptr;
  2682. char *par, *val = NULL;
  2683. char hash1[HEXHASH_LEN+1], hash2[HEXHASH_LEN+1], hash3[HEXHASH_LEN+1];
  2684. AVal user, nonce, *aptr = NULL;
  2685. AVal apptmp;
  2686. /* llnw auth method
  2687. * Seems to be closely based on HTTP Digest Auth:
  2688. * http://tools.ietf.org/html/rfc2617
  2689. * http://en.wikipedia.org/wiki/Digest_access_authentication
  2690. */
  2691. const char authmod[] = "llnw";
  2692. const char realm[] = "live";
  2693. const char method[] = "publish";
  2694. const char qop[] = "auth";
  2695. /* nc = 1..connection count (or rather, number of times cnonce has been reused) */
  2696. int nc = 1;
  2697. /* nchex = hexenc(nc) (8 hex digits according to RFC 2617) */
  2698. char nchex[9];
  2699. /* cnonce = hexenc(4 random bytes) (initialized on first connection) */
  2700. char cnonce[9];
  2701. ptr = orig_ptr = strdup(token_in);
  2702. /* Extract parameters (we need user and nonce) */
  2703. while (ptr)
  2704. {
  2705. par = ptr;
  2706. ptr = strchr(par, '&');
  2707. if(ptr)
  2708. *ptr++ = '\0';
  2709. val = strchr(par, '=');
  2710. if(val)
  2711. *val++ = '\0';
  2712. if (aptr)
  2713. {
  2714. aptr->av_len = par - aptr->av_val - 1;
  2715. aptr = NULL;
  2716. }
  2717. if (strcmp(par, "user") == 0)
  2718. {
  2719. user.av_val = val;
  2720. aptr = &user;
  2721. }
  2722. else if (strcmp(par, "nonce") == 0)
  2723. {
  2724. nonce.av_val = val;
  2725. aptr = &nonce;
  2726. }
  2727. RTMP_Log(RTMP_LOGDEBUG, "%s, par:\"%s\" = val:\"%s\"", __FUNCTION__, par, val);
  2728. }
  2729. if (aptr)
  2730. aptr->av_len = (int)strlen(aptr->av_val);
  2731. /* FIXME: handle case where user==NULL or nonce==NULL */
  2732. sprintf(nchex, "%08x", nc);
  2733. sprintf(cnonce, "%08x", rand());
  2734. /* hash1 = hexenc(md5(user + ":" + realm + ":" + password)) */
  2735. MD5_Init(&md5ctx);
  2736. MD5_Update(&md5ctx, user.av_val, user.av_len);
  2737. MD5_Update(&md5ctx, ":", 1);
  2738. MD5_Update(&md5ctx, (void *)realm, sizeof(realm)-1);
  2739. MD5_Update(&md5ctx, ":", 1);
  2740. MD5_Update(&md5ctx, r->Link.pubPasswd.av_val, r->Link.pubPasswd.av_len);
  2741. MD5_Final(md5sum_val, &md5ctx);
  2742. RTMP_Log(RTMP_LOGDEBUG, "%s, md5(%s:%s:%s) =>", __FUNCTION__,
  2743. user.av_val, realm, r->Link.pubPasswd.av_val);
  2744. RTMP_LogHexString(RTMP_LOGDEBUG, md5sum_val, MD5_DIGEST_LENGTH);
  2745. hexenc(md5sum_val, MD5_DIGEST_LENGTH, hash1);
  2746. /* hash2 = hexenc(md5(method + ":/" + app + "/" + appInstance)) */
  2747. /* Extract appname + appinstance without query parameters */
  2748. apptmp = r->Link.app;
  2749. ptr = strchr(apptmp.av_val, '?');
  2750. if (ptr)
  2751. apptmp.av_len = ptr - apptmp.av_val;
  2752. MD5_Init(&md5ctx);
  2753. MD5_Update(&md5ctx, (void *)method, sizeof(method)-1);
  2754. MD5_Update(&md5ctx, ":/", 2);
  2755. MD5_Update(&md5ctx, apptmp.av_val, apptmp.av_len);
  2756. MD5_Final(md5sum_val, &md5ctx);
  2757. RTMP_Log(RTMP_LOGDEBUG, "%s, md5(%s:/%.*s) =>", __FUNCTION__,
  2758. method, apptmp.av_len, apptmp.av_val);
  2759. RTMP_LogHexString(RTMP_LOGDEBUG, md5sum_val, MD5_DIGEST_LENGTH);
  2760. hexenc(md5sum_val, MD5_DIGEST_LENGTH, hash2);
  2761. /* hash3 = hexenc(md5(hash1 + ":" + nonce + ":" + nchex + ":" + cnonce + ":" + qop + ":" + hash2)) */
  2762. MD5_Init(&md5ctx);
  2763. MD5_Update(&md5ctx, hash1, HEXHASH_LEN);
  2764. MD5_Update(&md5ctx, ":", 1);
  2765. MD5_Update(&md5ctx, nonce.av_val, nonce.av_len);
  2766. MD5_Update(&md5ctx, ":", 1);
  2767. MD5_Update(&md5ctx, nchex, sizeof(nchex)-1);
  2768. MD5_Update(&md5ctx, ":", 1);
  2769. MD5_Update(&md5ctx, cnonce, sizeof(cnonce)-1);
  2770. MD5_Update(&md5ctx, ":", 1);
  2771. MD5_Update(&md5ctx, (void *)qop, sizeof(qop)-1);
  2772. MD5_Update(&md5ctx, ":", 1);
  2773. MD5_Update(&md5ctx, hash2, HEXHASH_LEN);
  2774. MD5_Final(md5sum_val, &md5ctx);
  2775. RTMP_Log(RTMP_LOGDEBUG, "%s, md5(%s:%s:%s:%s:%s:%s) =>", __FUNCTION__,
  2776. hash1, nonce.av_val, nchex, cnonce, qop, hash2);
  2777. RTMP_LogHexString(RTMP_LOGDEBUG, md5sum_val, MD5_DIGEST_LENGTH);
  2778. hexenc(md5sum_val, MD5_DIGEST_LENGTH, hash3);
  2779. /* pubToken = &authmod=<authmod>&user=<username>&nonce=<nonce>&cnonce=<cnonce>&nc=<nchex>&response=<hash3> */
  2780. /* Append nonces and response to query string which already contains
  2781. * user + authmod */
  2782. pubToken.av_val = malloc(64 + sizeof(authmod)-1 + user.av_len + nonce.av_len + sizeof(cnonce)-1 + sizeof(nchex)-1 + HEXHASH_LEN);
  2783. sprintf(pubToken.av_val,
  2784. "&nonce=%s&cnonce=%s&nc=%s&response=%s",
  2785. nonce.av_val, cnonce, nchex, hash3);
  2786. pubToken.av_len = (int)strlen(pubToken.av_val);
  2787. RTMP_Log(RTMP_LOGDEBUG, "%s, pubToken2: %s", __FUNCTION__, pubToken.av_val);
  2788. r->Link.pFlags |= RTMP_PUB_RESP|RTMP_PUB_CLATE;
  2789. free(orig_ptr);
  2790. }
  2791. else if(strstr(description->av_val, "?reason=authfail") != NULL)
  2792. {
  2793. RTMP_Log(RTMP_LOGERROR, "%s, Authentication failed", __FUNCTION__);
  2794. r->Link.pFlags |= RTMP_PUB_CLEAN;
  2795. return 0;
  2796. }
  2797. else if(strstr(description->av_val, "?reason=nosuchuser") != NULL)
  2798. {
  2799. RTMP_Log(RTMP_LOGERROR, "%s, Authentication failed: no such user", __FUNCTION__);
  2800. r->Link.pFlags |= RTMP_PUB_CLEAN;
  2801. return 0;
  2802. }
  2803. else
  2804. {
  2805. RTMP_Log(RTMP_LOGERROR, "%s, Authentication failed: unknown auth mode: %s",
  2806. __FUNCTION__, description->av_val);
  2807. r->Link.pFlags |= RTMP_PUB_CLEAN;
  2808. return 0;
  2809. }
  2810. ptr = malloc(r->Link.app.av_len + pubToken.av_len);
  2811. strncpy(ptr, r->Link.app.av_val, r->Link.app.av_len);
  2812. strncpy(ptr + r->Link.app.av_len, pubToken.av_val, pubToken.av_len);
  2813. r->Link.app.av_len += pubToken.av_len;
  2814. if(r->Link.pFlags & RTMP_PUB_ALLOC)
  2815. free(r->Link.app.av_val);
  2816. r->Link.app.av_val = ptr;
  2817. ptr = malloc(r->Link.tcUrl.av_len + pubToken.av_len);
  2818. strncpy(ptr, r->Link.tcUrl.av_val, r->Link.tcUrl.av_len);
  2819. strncpy(ptr + r->Link.tcUrl.av_len, pubToken.av_val, pubToken.av_len);
  2820. r->Link.tcUrl.av_len += pubToken.av_len;
  2821. if(r->Link.pFlags & RTMP_PUB_ALLOC)
  2822. free(r->Link.tcUrl.av_val);
  2823. r->Link.tcUrl.av_val = ptr;
  2824. free(pubToken.av_val);
  2825. r->Link.pFlags |= RTMP_PUB_ALLOC;
  2826. RTMP_Log(RTMP_LOGDEBUG, "%s, new app: %.*s tcUrl: %.*s playpath: %s", __FUNCTION__,
  2827. r->Link.app.av_len, r->Link.app.av_val,
  2828. r->Link.tcUrl.av_len, r->Link.tcUrl.av_val,
  2829. r->Link.playpath.av_val);
  2830. }
  2831. else
  2832. {
  2833. return 0;
  2834. }
  2835. return 1;
  2836. }
  2837. #endif
  2838. SAVC(onBWDone);
  2839. SAVC(onFCSubscribe);
  2840. SAVC(onFCUnsubscribe);
  2841. SAVC(_onbwcheck);
  2842. SAVC(_onbwdone);
  2843. SAVC(_error);
  2844. SAVC(close);
  2845. SAVC(code);
  2846. SAVC(level);
  2847. SAVC(description);
  2848. SAVC(onStatus);
  2849. SAVC(playlist_ready);
  2850. static const AVal av_NetStream_Failed = AVC("NetStream.Failed");
  2851. static const AVal av_NetStream_Play_Failed = AVC("NetStream.Play.Failed");
  2852. static const AVal av_NetStream_Play_StreamNotFound =
  2853. AVC("NetStream.Play.StreamNotFound");
  2854. static const AVal av_NetConnection_Connect_InvalidApp =
  2855. AVC("NetConnection.Connect.InvalidApp");
  2856. static const AVal av_NetStream_Play_Start = AVC("NetStream.Play.Start");
  2857. static const AVal av_NetStream_Play_Complete = AVC("NetStream.Play.Complete");
  2858. static const AVal av_NetStream_Play_Stop = AVC("NetStream.Play.Stop");
  2859. static const AVal av_NetStream_Seek_Notify = AVC("NetStream.Seek.Notify");
  2860. static const AVal av_NetStream_Pause_Notify = AVC("NetStream.Pause.Notify");
  2861. static const AVal av_NetStream_Play_PublishNotify =
  2862. AVC("NetStream.Play.PublishNotify");
  2863. static const AVal av_NetStream_Play_UnpublishNotify =
  2864. AVC("NetStream.Play.UnpublishNotify");
  2865. static const AVal av_NetStream_Publish_Start = AVC("NetStream.Publish.Start");
  2866. static const AVal av_NetStream_Publish_Rejected = AVC("NetStream.Publish.Rejected");
  2867. static const AVal av_NetStream_Publish_Denied = AVC("NetStream.Publish.Denied");
  2868. #if 0
  2869. static const AVal av_NetConnection_Connect_Rejected =
  2870. AVC("NetConnection.Connect.Rejected");
  2871. #endif
  2872. /* Returns 0 for OK/Failed/error, 1 for 'Stop or Complete' */
  2873. static int
  2874. HandleInvoke(RTMP *r, const char *body, unsigned int nBodySize)
  2875. {
  2876. AMFObject obj;
  2877. AVal method;
  2878. double txn;
  2879. int ret = 0, nRes;
  2880. if (body[0] != 0x02) /* make sure it is a string method name we start with */
  2881. {
  2882. RTMP_Log(RTMP_LOGWARNING, "%s, Sanity failed. no string method in invoke packet",
  2883. __FUNCTION__);
  2884. return 0;
  2885. }
  2886. nRes = AMF_Decode(&obj, body, nBodySize, FALSE);
  2887. if (nRes < 0)
  2888. {
  2889. RTMP_Log(RTMP_LOGERROR, "%s, error decoding invoke packet", __FUNCTION__);
  2890. return 0;
  2891. }
  2892. AMF_Dump(&obj);
  2893. AMFProp_GetString(AMF_GetProp(&obj, NULL, 0), &method);
  2894. txn = AMFProp_GetNumber(AMF_GetProp(&obj, NULL, 1));
  2895. RTMP_Log(RTMP_LOGDEBUG, "%s, server invoking <%s>", __FUNCTION__, method.av_val);
  2896. if (AVMATCH(&method, &av__result))
  2897. {
  2898. AVal methodInvoked = {0};
  2899. int i;
  2900. for (i=0; i<r->m_numCalls; i++)
  2901. {
  2902. if (r->m_methodCalls[i].num == (int)txn)
  2903. {
  2904. methodInvoked = r->m_methodCalls[i].name;
  2905. AV_erase(r->m_methodCalls, &r->m_numCalls, i, FALSE);
  2906. break;
  2907. }
  2908. }
  2909. if (!methodInvoked.av_val)
  2910. {
  2911. RTMP_Log(RTMP_LOGDEBUG, "%s, received result id %f without matching request",
  2912. __FUNCTION__, txn);
  2913. goto leave;
  2914. }
  2915. RTMP_Log(RTMP_LOGDEBUG, "%s, received result for method call <%s>", __FUNCTION__,
  2916. methodInvoked.av_val);
  2917. if (AVMATCH(&methodInvoked, &av_connect))
  2918. {
  2919. if (r->Link.token.av_len)
  2920. {
  2921. AMFObjectProperty p;
  2922. if (RTMP_FindFirstMatchingProperty(&obj, &av_secureToken, &p))
  2923. {
  2924. DecodeTEA(&r->Link.token, &p.p_vu.p_aval);
  2925. SendSecureTokenResponse(r, &p.p_vu.p_aval);
  2926. }
  2927. }
  2928. if (r->Link.protocol & RTMP_FEATURE_WRITE)
  2929. {
  2930. SendReleaseStream(r);
  2931. SendFCPublish(r);
  2932. }
  2933. else
  2934. {
  2935. RTMP_SendServerBW(r);
  2936. RTMP_SendCtrl(r, 3, 0, 300);
  2937. }
  2938. RTMP_SendCreateStream(r);
  2939. if (!(r->Link.protocol & RTMP_FEATURE_WRITE))
  2940. {
  2941. /* Authenticate on Justin.tv legacy servers before sending FCSubscribe */
  2942. if (r->Link.usherToken.av_len)
  2943. SendUsherToken(r, &r->Link.usherToken);
  2944. /* Send the FCSubscribe if live stream or if subscribepath is set */
  2945. if (r->Link.subscribepath.av_len)
  2946. SendFCSubscribe(r, &r->Link.subscribepath);
  2947. else if (r->Link.lFlags & RTMP_LF_LIVE)
  2948. SendFCSubscribe(r, &r->Link.playpath);
  2949. }
  2950. }
  2951. else if (AVMATCH(&methodInvoked, &av_createStream))
  2952. {
  2953. r->m_stream_id = (int)AMFProp_GetNumber(AMF_GetProp(&obj, NULL, 3));
  2954. if (r->Link.protocol & RTMP_FEATURE_WRITE)
  2955. {
  2956. SendPublish(r);
  2957. }
  2958. else
  2959. {
  2960. if (r->Link.lFlags & RTMP_LF_PLST)
  2961. SendPlaylist(r);
  2962. SendPlay(r);
  2963. RTMP_SendCtrl(r, 3, r->m_stream_id, r->m_nBufferMS);
  2964. }
  2965. }
  2966. else if (AVMATCH(&methodInvoked, &av_play) ||
  2967. AVMATCH(&methodInvoked, &av_publish))
  2968. {
  2969. r->m_bPlaying = TRUE;
  2970. }
  2971. free(methodInvoked.av_val);
  2972. }
  2973. else if (AVMATCH(&method, &av_onBWDone))
  2974. {
  2975. if (!r->m_nBWCheckCounter)
  2976. SendCheckBW(r);
  2977. }
  2978. else if (AVMATCH(&method, &av_onFCSubscribe))
  2979. {
  2980. /* SendOnFCSubscribe(); */
  2981. }
  2982. else if (AVMATCH(&method, &av_onFCUnsubscribe))
  2983. {
  2984. RTMP_Close(r);
  2985. ret = 1;
  2986. }
  2987. else if (AVMATCH(&method, &av_ping))
  2988. {
  2989. SendPong(r, txn);
  2990. }
  2991. else if (AVMATCH(&method, &av__onbwcheck))
  2992. {
  2993. SendCheckBWResult(r, txn);
  2994. }
  2995. else if (AVMATCH(&method, &av__onbwdone))
  2996. {
  2997. int i;
  2998. for (i = 0; i < r->m_numCalls; i++)
  2999. if (AVMATCH(&r->m_methodCalls[i].name, &av__checkbw))
  3000. {
  3001. AV_erase(r->m_methodCalls, &r->m_numCalls, i, TRUE);
  3002. break;
  3003. }
  3004. }
  3005. else if (AVMATCH(&method, &av__error))
  3006. {
  3007. #if defined(CRYPTO) || defined(USE_ONLY_MD5)
  3008. AVal methodInvoked = {0};
  3009. int i;
  3010. if (r->Link.protocol & RTMP_FEATURE_WRITE)
  3011. {
  3012. for (i=0; i<r->m_numCalls; i++)
  3013. {
  3014. if (r->m_methodCalls[i].num == txn)
  3015. {
  3016. methodInvoked = r->m_methodCalls[i].name;
  3017. AV_erase(r->m_methodCalls, &r->m_numCalls, i, FALSE);
  3018. break;
  3019. }
  3020. }
  3021. if (!methodInvoked.av_val)
  3022. {
  3023. RTMP_Log(RTMP_LOGDEBUG, "%s, received result id %f without matching request",
  3024. __FUNCTION__, txn);
  3025. goto leave;
  3026. }
  3027. RTMP_Log(RTMP_LOGDEBUG, "%s, received error for method call <%s>", __FUNCTION__,
  3028. methodInvoked.av_val);
  3029. if (AVMATCH(&methodInvoked, &av_connect))
  3030. {
  3031. AMFObject obj2;
  3032. AVal code, level, description;
  3033. AMFProp_GetObject(AMF_GetProp(&obj, NULL, 3), &obj2);
  3034. AMFProp_GetString(AMF_GetProp(&obj2, &av_code, -1), &code);
  3035. AMFProp_GetString(AMF_GetProp(&obj2, &av_level, -1), &level);
  3036. AMFProp_GetString(AMF_GetProp(&obj2, &av_description, -1), &description);
  3037. RTMP_Log(RTMP_LOGDEBUG, "%s, error description: %s", __FUNCTION__, description.av_val);
  3038. /* if PublisherAuth returns 1, then reconnect */
  3039. PublisherAuth(r, &description);
  3040. }
  3041. }
  3042. else
  3043. {
  3044. RTMP_Log(RTMP_LOGERROR, "rtmp server sent error");
  3045. }
  3046. free(methodInvoked.av_val);
  3047. #else
  3048. RTMP_Log(RTMP_LOGERROR, "rtmp server sent error");
  3049. #endif
  3050. }
  3051. else if (AVMATCH(&method, &av_close))
  3052. {
  3053. RTMP_Log(RTMP_LOGERROR, "rtmp server requested close");
  3054. RTMP_Close(r);
  3055. #if defined(CRYPTO) || defined(USE_ONLY_MD5)
  3056. if ((r->Link.protocol & RTMP_FEATURE_WRITE) &&
  3057. !(r->Link.pFlags & RTMP_PUB_CLEAN) &&
  3058. ( !(r->Link.pFlags & RTMP_PUB_NAME) ||
  3059. !(r->Link.pFlags & RTMP_PUB_RESP) ||
  3060. (r->Link.pFlags & RTMP_PUB_CLATE) ) )
  3061. {
  3062. /* clean later */
  3063. if(r->Link.pFlags & RTMP_PUB_CLATE)
  3064. r->Link.pFlags |= RTMP_PUB_CLEAN;
  3065. RTMP_Log(RTMP_LOGERROR, "authenticating publisher");
  3066. if (!RTMP_Connect(r, NULL) || !RTMP_ConnectStream(r, 0))
  3067. goto leave;
  3068. }
  3069. #endif
  3070. }
  3071. else if (AVMATCH(&method, &av_onStatus))
  3072. {
  3073. AMFObject obj2;
  3074. AVal code, level, description;
  3075. AMFProp_GetObject(AMF_GetProp(&obj, NULL, 3), &obj2);
  3076. AMFProp_GetString(AMF_GetProp(&obj2, &av_code, -1), &code);
  3077. AMFProp_GetString(AMF_GetProp(&obj2, &av_level, -1), &level);
  3078. AMFProp_GetString(AMF_GetProp(&obj2, &av_description, -1), &description);
  3079. RTMP_Log(RTMP_LOGDEBUG, "%s, onStatus: %s", __FUNCTION__, code.av_val);
  3080. if (AVMATCH(&code, &av_NetStream_Failed)
  3081. || AVMATCH(&code, &av_NetStream_Play_Failed)
  3082. || AVMATCH(&code, &av_NetStream_Play_StreamNotFound)
  3083. || AVMATCH(&code, &av_NetConnection_Connect_InvalidApp)
  3084. || AVMATCH(&code, &av_NetStream_Publish_Rejected)
  3085. || AVMATCH(&code, &av_NetStream_Publish_Denied))
  3086. {
  3087. r->m_stream_id = -1;
  3088. RTMP_Close(r);
  3089. if (description.av_len)
  3090. RTMP_Log(RTMP_LOGERROR, "%s:\n%s (%s)", r->Link.tcUrl.av_val, code.av_val, description.av_val);
  3091. else
  3092. RTMP_Log(RTMP_LOGERROR, "%s:\n%s", r->Link.tcUrl.av_val, code.av_val);
  3093. }
  3094. else if (AVMATCH(&code, &av_NetStream_Play_Start)
  3095. || AVMATCH(&code, &av_NetStream_Play_PublishNotify))
  3096. {
  3097. int i;
  3098. r->m_bPlaying = TRUE;
  3099. for (i = 0; i < r->m_numCalls; i++)
  3100. {
  3101. if (AVMATCH(&r->m_methodCalls[i].name, &av_play))
  3102. {
  3103. AV_erase(r->m_methodCalls, &r->m_numCalls, i, TRUE);
  3104. break;
  3105. }
  3106. }
  3107. }
  3108. else if (AVMATCH(&code, &av_NetStream_Publish_Start))
  3109. {
  3110. int i;
  3111. r->m_bPlaying = TRUE;
  3112. for (i = 0; i < r->m_numCalls; i++)
  3113. {
  3114. if (AVMATCH(&r->m_methodCalls[i].name, &av_publish))
  3115. {
  3116. AV_erase(r->m_methodCalls, &r->m_numCalls, i, TRUE);
  3117. break;
  3118. }
  3119. }
  3120. }
  3121. /* Return 1 if this is a Play.Complete or Play.Stop */
  3122. else if (AVMATCH(&code, &av_NetStream_Play_Complete)
  3123. || AVMATCH(&code, &av_NetStream_Play_Stop)
  3124. || AVMATCH(&code, &av_NetStream_Play_UnpublishNotify))
  3125. {
  3126. RTMP_Close(r);
  3127. ret = 1;
  3128. }
  3129. else if (AVMATCH(&code, &av_NetStream_Seek_Notify))
  3130. {
  3131. r->m_read.flags &= ~RTMP_READ_SEEKING;
  3132. }
  3133. else if (AVMATCH(&code, &av_NetStream_Pause_Notify))
  3134. {
  3135. if (r->m_pausing == 1 || r->m_pausing == 2)
  3136. {
  3137. RTMP_SendPause(r, FALSE, r->m_pauseStamp);
  3138. r->m_pausing = 3;
  3139. }
  3140. }
  3141. }
  3142. else if (AVMATCH(&method, &av_playlist_ready))
  3143. {
  3144. int i;
  3145. for (i = 0; i < r->m_numCalls; i++)
  3146. {
  3147. if (AVMATCH(&r->m_methodCalls[i].name, &av_set_playlist))
  3148. {
  3149. AV_erase(r->m_methodCalls, &r->m_numCalls, i, TRUE);
  3150. break;
  3151. }
  3152. }
  3153. }
  3154. else
  3155. {
  3156. }
  3157. leave:
  3158. AMF_Reset(&obj);
  3159. return ret;
  3160. }
  3161. int
  3162. RTMP_FindFirstMatchingProperty(AMFObject *obj, const AVal *name,
  3163. AMFObjectProperty * p)
  3164. {
  3165. int n;
  3166. /* this is a small object search to locate the "duration" property */
  3167. for (n = 0; n < obj->o_num; n++)
  3168. {
  3169. AMFObjectProperty *prop = AMF_GetProp(obj, NULL, n);
  3170. if (AVMATCH(&prop->p_name, name))
  3171. {
  3172. memcpy(p, prop, sizeof(*prop));
  3173. return TRUE;
  3174. }
  3175. if (prop->p_type == AMF_OBJECT || prop->p_type == AMF_ECMA_ARRAY)
  3176. {
  3177. if (RTMP_FindFirstMatchingProperty(&prop->p_vu.p_object, name, p))
  3178. return TRUE;
  3179. }
  3180. }
  3181. return FALSE;
  3182. }
  3183. /* Like above, but only check if name is a prefix of property */
  3184. int
  3185. RTMP_FindPrefixProperty(AMFObject *obj, const AVal *name,
  3186. AMFObjectProperty * p)
  3187. {
  3188. int n;
  3189. for (n = 0; n < obj->o_num; n++)
  3190. {
  3191. AMFObjectProperty *prop = AMF_GetProp(obj, NULL, n);
  3192. if (prop->p_name.av_len > name->av_len &&
  3193. !memcmp(prop->p_name.av_val, name->av_val, name->av_len))
  3194. {
  3195. memcpy(p, prop, sizeof(*prop));
  3196. return TRUE;
  3197. }
  3198. if (prop->p_type == AMF_OBJECT)
  3199. {
  3200. if (RTMP_FindPrefixProperty(&prop->p_vu.p_object, name, p))
  3201. return TRUE;
  3202. }
  3203. }
  3204. return FALSE;
  3205. }
  3206. static int
  3207. DumpMetaData(AMFObject *obj)
  3208. {
  3209. AMFObjectProperty *prop;
  3210. int n, len;
  3211. for (n = 0; n < obj->o_num; n++)
  3212. {
  3213. char str[256] = "";
  3214. prop = AMF_GetProp(obj, NULL, n);
  3215. switch (prop->p_type)
  3216. {
  3217. case AMF_OBJECT:
  3218. case AMF_ECMA_ARRAY:
  3219. case AMF_STRICT_ARRAY:
  3220. if (prop->p_name.av_len)
  3221. RTMP_Log(RTMP_LOGINFO, "%.*s:", prop->p_name.av_len, prop->p_name.av_val);
  3222. DumpMetaData(&prop->p_vu.p_object);
  3223. break;
  3224. case AMF_NUMBER:
  3225. snprintf(str, 255, "%.2f", prop->p_vu.p_number);
  3226. break;
  3227. case AMF_BOOLEAN:
  3228. snprintf(str, 255, "%s",
  3229. prop->p_vu.p_number != 0. ? "TRUE" : "FALSE");
  3230. break;
  3231. case AMF_STRING:
  3232. len = snprintf(str, 255, "%.*s", prop->p_vu.p_aval.av_len,
  3233. prop->p_vu.p_aval.av_val);
  3234. if (len >= 1 && str[len-1] == '\n')
  3235. str[len-1] = '\0';
  3236. break;
  3237. case AMF_DATE:
  3238. snprintf(str, 255, "timestamp:%.2f", prop->p_vu.p_number);
  3239. break;
  3240. default:
  3241. snprintf(str, 255, "INVALID TYPE 0x%02x",
  3242. (unsigned char)prop->p_type);
  3243. }
  3244. if (str[0] && prop->p_name.av_len)
  3245. {
  3246. RTMP_Log(RTMP_LOGINFO, " %-22.*s%s", prop->p_name.av_len,
  3247. prop->p_name.av_val, str);
  3248. }
  3249. }
  3250. return FALSE;
  3251. }
  3252. SAVC(onMetaData);
  3253. SAVC(duration);
  3254. SAVC(video);
  3255. SAVC(audio);
  3256. static int
  3257. HandleMetadata(RTMP *r, char *body, unsigned int len)
  3258. {
  3259. /* allright we get some info here, so parse it and print it */
  3260. /* also keep duration or filesize to make a nice progress bar */
  3261. AMFObject obj;
  3262. AVal metastring;
  3263. int ret = FALSE;
  3264. int nRes = AMF_Decode(&obj, body, len, FALSE);
  3265. if (nRes < 0)
  3266. {
  3267. RTMP_Log(RTMP_LOGERROR, "%s, error decoding meta data packet", __FUNCTION__);
  3268. return FALSE;
  3269. }
  3270. AMF_Dump(&obj);
  3271. AMFProp_GetString(AMF_GetProp(&obj, NULL, 0), &metastring);
  3272. if (AVMATCH(&metastring, &av_onMetaData))
  3273. {
  3274. AMFObjectProperty prop;
  3275. /* Show metadata */
  3276. RTMP_Log(RTMP_LOGINFO, "Metadata:");
  3277. DumpMetaData(&obj);
  3278. if (RTMP_FindFirstMatchingProperty(&obj, &av_duration, &prop))
  3279. {
  3280. r->m_fDuration = prop.p_vu.p_number;
  3281. /*RTMP_Log(RTMP_LOGDEBUG, "Set duration: %.2f", m_fDuration); */
  3282. }
  3283. /* Search for audio or video tags */
  3284. if (RTMP_FindPrefixProperty(&obj, &av_video, &prop))
  3285. r->m_read.dataType |= 1;
  3286. if (RTMP_FindPrefixProperty(&obj, &av_audio, &prop))
  3287. r->m_read.dataType |= 4;
  3288. ret = TRUE;
  3289. }
  3290. AMF_Reset(&obj);
  3291. return ret;
  3292. }
  3293. static void
  3294. HandleChangeChunkSize(RTMP *r, const RTMPPacket *packet)
  3295. {
  3296. if (packet->m_nBodySize >= 4)
  3297. {
  3298. r->m_inChunkSize = AMF_DecodeInt32(packet->m_body);
  3299. RTMP_Log(RTMP_LOGDEBUG, "%s, received: chunk size change to %d", __FUNCTION__,
  3300. r->m_inChunkSize);
  3301. }
  3302. }
  3303. static void
  3304. HandleAudio(RTMP *r, const RTMPPacket *packet)
  3305. {
  3306. (void)r;
  3307. (void)packet;
  3308. }
  3309. static void
  3310. HandleVideo(RTMP *r, const RTMPPacket *packet)
  3311. {
  3312. (void)r;
  3313. (void)packet;
  3314. }
  3315. static void
  3316. HandleCtrl(RTMP *r, const RTMPPacket *packet)
  3317. {
  3318. short nType = -1;
  3319. unsigned int tmp;
  3320. if (packet->m_body && packet->m_nBodySize >= 2)
  3321. nType = AMF_DecodeInt16(packet->m_body);
  3322. RTMP_Log(RTMP_LOGDEBUG, "%s, received ctrl. type: %d, len: %d", __FUNCTION__, nType,
  3323. packet->m_nBodySize);
  3324. /*RTMP_LogHex(packet.m_body, packet.m_nBodySize); */
  3325. if (packet->m_nBodySize >= 6)
  3326. {
  3327. switch (nType)
  3328. {
  3329. case 0:
  3330. tmp = AMF_DecodeInt32(packet->m_body + 2);
  3331. RTMP_Log(RTMP_LOGDEBUG, "%s, Stream Begin %d", __FUNCTION__, tmp);
  3332. break;
  3333. case 1:
  3334. tmp = AMF_DecodeInt32(packet->m_body + 2);
  3335. RTMP_Log(RTMP_LOGDEBUG, "%s, Stream EOF %d", __FUNCTION__, tmp);
  3336. if (r->m_pausing == 1)
  3337. r->m_pausing = 2;
  3338. break;
  3339. case 2:
  3340. tmp = AMF_DecodeInt32(packet->m_body + 2);
  3341. RTMP_Log(RTMP_LOGDEBUG, "%s, Stream Dry %d", __FUNCTION__, tmp);
  3342. break;
  3343. case 4:
  3344. tmp = AMF_DecodeInt32(packet->m_body + 2);
  3345. RTMP_Log(RTMP_LOGDEBUG, "%s, Stream IsRecorded %d", __FUNCTION__, tmp);
  3346. break;
  3347. case 6: /* server ping. reply with pong. */
  3348. tmp = AMF_DecodeInt32(packet->m_body + 2);
  3349. RTMP_Log(RTMP_LOGDEBUG, "%s, Ping %d", __FUNCTION__, tmp);
  3350. RTMP_SendCtrl(r, 0x07, tmp, 0);
  3351. break;
  3352. /* FMS 3.5 servers send the following two controls to let the client
  3353. * know when the server has sent a complete buffer. I.e., when the
  3354. * server has sent an amount of data equal to m_nBufferMS in duration.
  3355. * The server meters its output so that data arrives at the client
  3356. * in realtime and no faster.
  3357. *
  3358. * The rtmpdump program tries to set m_nBufferMS as large as
  3359. * possible, to force the server to send data as fast as possible.
  3360. * In practice, the server appears to cap this at about 1 hour's
  3361. * worth of data. After the server has sent a complete buffer, and
  3362. * sends this BufferEmpty message, it will wait until the play
  3363. * duration of that buffer has passed before sending a new buffer.
  3364. * The BufferReady message will be sent when the new buffer starts.
  3365. * (There is no BufferReady message for the very first buffer;
  3366. * presumably the Stream Begin message is sufficient for that
  3367. * purpose.)
  3368. *
  3369. * If the network speed is much faster than the data bitrate, then
  3370. * there may be long delays between the end of one buffer and the
  3371. * start of the next.
  3372. *
  3373. * Since usually the network allows data to be sent at
  3374. * faster than realtime, and rtmpdump wants to download the data
  3375. * as fast as possible, we use this RTMP_LF_BUFX hack: when we
  3376. * get the BufferEmpty message, we send a Pause followed by an
  3377. * Unpause. This causes the server to send the next buffer immediately
  3378. * instead of waiting for the full duration to elapse. (That's
  3379. * also the purpose of the ToggleStream function, which rtmpdump
  3380. * calls if we get a read timeout.)
  3381. *
  3382. * Media player apps don't need this hack since they are just
  3383. * going to play the data in realtime anyway. It also doesn't work
  3384. * for live streams since they obviously can only be sent in
  3385. * realtime. And it's all moot if the network speed is actually
  3386. * slower than the media bitrate.
  3387. */
  3388. case 31:
  3389. tmp = AMF_DecodeInt32(packet->m_body + 2);
  3390. RTMP_Log(RTMP_LOGDEBUG, "%s, Stream BufferEmpty %d", __FUNCTION__, tmp);
  3391. if (!(r->Link.lFlags & RTMP_LF_BUFX))
  3392. break;
  3393. if (!r->m_pausing)
  3394. {
  3395. r->m_pauseStamp = r->m_mediaChannel < r->m_channelsAllocatedIn ?
  3396. r->m_channelTimestamp[r->m_mediaChannel] : 0;
  3397. RTMP_SendPause(r, TRUE, r->m_pauseStamp);
  3398. r->m_pausing = 1;
  3399. }
  3400. else if (r->m_pausing == 2)
  3401. {
  3402. RTMP_SendPause(r, FALSE, r->m_pauseStamp);
  3403. r->m_pausing = 3;
  3404. }
  3405. break;
  3406. case 32:
  3407. tmp = AMF_DecodeInt32(packet->m_body + 2);
  3408. RTMP_Log(RTMP_LOGDEBUG, "%s, Stream BufferReady %d", __FUNCTION__, tmp);
  3409. break;
  3410. default:
  3411. tmp = AMF_DecodeInt32(packet->m_body + 2);
  3412. RTMP_Log(RTMP_LOGDEBUG, "%s, Stream xx %d", __FUNCTION__, tmp);
  3413. break;
  3414. }
  3415. }
  3416. if (nType == 0x1A)
  3417. {
  3418. RTMP_Log(RTMP_LOGDEBUG, "%s, SWFVerification ping received: ", __FUNCTION__);
  3419. if (packet->m_nBodySize > 2 && packet->m_body[2] > 0x01)
  3420. {
  3421. RTMP_Log(RTMP_LOGERROR,
  3422. "%s: SWFVerification Type %d request not supported! Patches welcome...",
  3423. __FUNCTION__, packet->m_body[2]);
  3424. }
  3425. #ifdef CRYPTO
  3426. /*RTMP_LogHex(packet.m_body, packet.m_nBodySize); */
  3427. /* respond with HMAC SHA256 of decompressed SWF, key is the 30byte player key, also the last 30 bytes of the server handshake are applied */
  3428. else if (r->Link.SWFSize)
  3429. {
  3430. RTMP_SendCtrl(r, 0x1B, 0, 0);
  3431. }
  3432. else
  3433. {
  3434. RTMP_Log(RTMP_LOGERROR,
  3435. "%s: Ignoring SWFVerification request, use --swfVfy!",
  3436. __FUNCTION__);
  3437. }
  3438. #else
  3439. RTMP_Log(RTMP_LOGERROR,
  3440. "%s: Ignoring SWFVerification request, no CRYPTO support!",
  3441. __FUNCTION__);
  3442. #endif
  3443. }
  3444. }
  3445. static void
  3446. HandleServerBW(RTMP *r, const RTMPPacket *packet)
  3447. {
  3448. r->m_nServerBW = AMF_DecodeInt32(packet->m_body);
  3449. RTMP_Log(RTMP_LOGDEBUG, "%s: server BW = %d", __FUNCTION__, r->m_nServerBW);
  3450. }
  3451. static void
  3452. HandleClientBW(RTMP *r, const RTMPPacket *packet)
  3453. {
  3454. r->m_nClientBW = AMF_DecodeInt32(packet->m_body);
  3455. if (packet->m_nBodySize > 4)
  3456. r->m_nClientBW2 = packet->m_body[4];
  3457. else
  3458. r->m_nClientBW2 = -1;
  3459. RTMP_Log(RTMP_LOGDEBUG, "%s: client BW = %d %d", __FUNCTION__, r->m_nClientBW,
  3460. r->m_nClientBW2);
  3461. }
  3462. static int
  3463. DecodeInt32LE(const char *data)
  3464. {
  3465. unsigned char *c = (unsigned char *)data;
  3466. unsigned int val;
  3467. val = (c[3] << 24) | (c[2] << 16) | (c[1] << 8) | c[0];
  3468. return val;
  3469. }
  3470. static int
  3471. EncodeInt32LE(char *output, int nVal)
  3472. {
  3473. output[0] = nVal;
  3474. nVal >>= 8;
  3475. output[1] = nVal;
  3476. nVal >>= 8;
  3477. output[2] = nVal;
  3478. nVal >>= 8;
  3479. output[3] = nVal;
  3480. return 4;
  3481. }
  3482. int
  3483. RTMP_ReadPacket(RTMP *r, RTMPPacket *packet)
  3484. {
  3485. uint8_t hbuf[RTMP_MAX_HEADER_SIZE] = { 0 };
  3486. char *header = (char *)hbuf;
  3487. int nSize, hSize, nToRead, nChunk;
  3488. // int didAlloc = FALSE;
  3489. RTMP_Log(RTMP_LOGDEBUG2, "%s: fd=%d", __FUNCTION__, r->m_sb.sb_socket);
  3490. if (ReadN(r, (char *)hbuf, 1) == 0)
  3491. {
  3492. RTMP_Log(RTMP_LOGDEBUG, "%s, failed to read RTMP packet header", __FUNCTION__);
  3493. return FALSE;
  3494. }
  3495. packet->m_headerType = (hbuf[0] & 0xc0) >> 6;
  3496. packet->m_nChannel = (hbuf[0] & 0x3f);
  3497. header++;
  3498. if (packet->m_nChannel == 0)
  3499. {
  3500. if (ReadN(r, (char *)&hbuf[1], 1) != 1)
  3501. {
  3502. RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header 2nd byte",
  3503. __FUNCTION__);
  3504. return FALSE;
  3505. }
  3506. packet->m_nChannel = hbuf[1];
  3507. packet->m_nChannel += 64;
  3508. header++;
  3509. }
  3510. else if (packet->m_nChannel == 1)
  3511. {
  3512. int tmp;
  3513. if (ReadN(r, (char *)&hbuf[1], 2) != 2)
  3514. {
  3515. RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header 3nd byte",
  3516. __FUNCTION__);
  3517. return FALSE;
  3518. }
  3519. tmp = (hbuf[2] << 8) + hbuf[1];
  3520. packet->m_nChannel = tmp + 64;
  3521. RTMP_Log(RTMP_LOGDEBUG, "%s, m_nChannel: %0x", __FUNCTION__, packet->m_nChannel);
  3522. header += 2;
  3523. }
  3524. nSize = packetSize[packet->m_headerType];
  3525. if (packet->m_nChannel >= r->m_channelsAllocatedIn)
  3526. {
  3527. int n = packet->m_nChannel + 10;
  3528. int *timestamp = realloc(r->m_channelTimestamp, sizeof(int) * n);
  3529. RTMPPacket **packets = realloc(r->m_vecChannelsIn, sizeof(RTMPPacket*) * n);
  3530. if (!timestamp)
  3531. free(r->m_channelTimestamp);
  3532. if (!packets)
  3533. free(r->m_vecChannelsIn);
  3534. r->m_channelTimestamp = timestamp;
  3535. r->m_vecChannelsIn = packets;
  3536. if (!timestamp || !packets)
  3537. {
  3538. r->m_channelsAllocatedIn = 0;
  3539. return FALSE;
  3540. }
  3541. memset(r->m_channelTimestamp + r->m_channelsAllocatedIn, 0, sizeof(int) * (n - r->m_channelsAllocatedIn));
  3542. memset(r->m_vecChannelsIn + r->m_channelsAllocatedIn, 0, sizeof(RTMPPacket*) * (n - r->m_channelsAllocatedIn));
  3543. r->m_channelsAllocatedIn = n;
  3544. }
  3545. if (nSize == RTMP_LARGE_HEADER_SIZE) /* if we get a full header the timestamp is absolute */
  3546. packet->m_hasAbsTimestamp = TRUE;
  3547. else if (nSize < RTMP_LARGE_HEADER_SIZE)
  3548. {
  3549. /* using values from the last message of this channel */
  3550. if (r->m_vecChannelsIn[packet->m_nChannel])
  3551. memcpy(packet, r->m_vecChannelsIn[packet->m_nChannel],
  3552. sizeof(RTMPPacket));
  3553. }
  3554. nSize--;
  3555. if (nSize > 0 && ReadN(r, header, nSize) != nSize)
  3556. {
  3557. RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header. type: %x",
  3558. __FUNCTION__, (unsigned int)hbuf[0]);
  3559. return FALSE;
  3560. }
  3561. hSize = nSize + (header - (char *)hbuf);
  3562. if (nSize >= 3)
  3563. {
  3564. packet->m_nTimeStamp = AMF_DecodeInt24(header);
  3565. /*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); */
  3566. if (nSize >= 6)
  3567. {
  3568. packet->m_nBodySize = AMF_DecodeInt24(header + 3);
  3569. packet->m_nBytesRead = 0;
  3570. RTMPPacket_Free(packet);
  3571. if (nSize > 6)
  3572. {
  3573. packet->m_packetType = header[6];
  3574. if (nSize == 11)
  3575. packet->m_nInfoField2 = DecodeInt32LE(header + 7);
  3576. }
  3577. }
  3578. if (packet->m_nTimeStamp == 0xffffff)
  3579. {
  3580. if (ReadN(r, header + nSize, 4) != 4)
  3581. {
  3582. RTMP_Log(RTMP_LOGERROR, "%s, failed to read extended timestamp",
  3583. __FUNCTION__);
  3584. return FALSE;
  3585. }
  3586. packet->m_nTimeStamp = AMF_DecodeInt32(header + nSize);
  3587. hSize += 4;
  3588. }
  3589. }
  3590. RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t *)hbuf, hSize);
  3591. if (packet->m_nBodySize > 0 && packet->m_body == NULL)
  3592. {
  3593. if (!RTMPPacket_Alloc(packet, packet->m_nBodySize))
  3594. {
  3595. RTMP_Log(RTMP_LOGDEBUG, "%s, failed to allocate packet", __FUNCTION__);
  3596. return FALSE;
  3597. }
  3598. // didAlloc = TRUE;
  3599. packet->m_headerType = (hbuf[0] & 0xc0) >> 6;
  3600. }
  3601. nToRead = packet->m_nBodySize - packet->m_nBytesRead;
  3602. nChunk = r->m_inChunkSize;
  3603. if (nToRead < nChunk)
  3604. nChunk = nToRead;
  3605. /* Does the caller want the raw chunk? */
  3606. if (packet->m_chunk)
  3607. {
  3608. packet->m_chunk->c_headerSize = hSize;
  3609. memcpy(packet->m_chunk->c_header, hbuf, hSize);
  3610. packet->m_chunk->c_chunk = packet->m_body + packet->m_nBytesRead;
  3611. packet->m_chunk->c_chunkSize = nChunk;
  3612. }
  3613. if (ReadN(r, packet->m_body + packet->m_nBytesRead, nChunk) != nChunk)
  3614. {
  3615. RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet body. len: %u",
  3616. __FUNCTION__, packet->m_nBodySize);
  3617. return FALSE;
  3618. }
  3619. RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t *)packet->m_body + packet->m_nBytesRead, nChunk);
  3620. packet->m_nBytesRead += nChunk;
  3621. /* keep the packet as ref for other packets on this channel */
  3622. if (!r->m_vecChannelsIn[packet->m_nChannel])
  3623. r->m_vecChannelsIn[packet->m_nChannel] = malloc(sizeof(RTMPPacket));
  3624. memcpy(r->m_vecChannelsIn[packet->m_nChannel], packet, sizeof(RTMPPacket));
  3625. if (RTMPPacket_IsReady(packet))
  3626. {
  3627. /* make packet's timestamp absolute */
  3628. if (!packet->m_hasAbsTimestamp)
  3629. packet->m_nTimeStamp += r->m_channelTimestamp[packet->m_nChannel]; /* timestamps seem to be always relative!! */
  3630. r->m_channelTimestamp[packet->m_nChannel] = packet->m_nTimeStamp;
  3631. /* reset the data from the stored packet. we keep the header since we may use it later if a new packet for this channel */
  3632. /* arrives and requests to re-use some info (small packet header) */
  3633. r->m_vecChannelsIn[packet->m_nChannel]->m_body = NULL;
  3634. r->m_vecChannelsIn[packet->m_nChannel]->m_nBytesRead = 0;
  3635. r->m_vecChannelsIn[packet->m_nChannel]->m_hasAbsTimestamp = FALSE; /* can only be false if we reuse header */
  3636. }
  3637. else
  3638. {
  3639. packet->m_body = NULL; /* so it won't be erased on free */
  3640. }
  3641. return TRUE;
  3642. }
  3643. #ifndef CRYPTO
  3644. static int
  3645. HandShake(RTMP *r, int FP9HandShake)
  3646. {
  3647. int i;
  3648. uint32_t uptime, suptime;
  3649. int bMatch;
  3650. char type;
  3651. char clientbuf[RTMP_SIG_SIZE + 1], *clientsig = clientbuf + 1;
  3652. char serversig[RTMP_SIG_SIZE];
  3653. clientbuf[0] = 0x03; /* not encrypted */
  3654. uptime = htonl(RTMP_GetTime());
  3655. memcpy(clientsig, &uptime, 4);
  3656. memset(&clientsig[4], 0, 4);
  3657. #ifdef _DEBUG
  3658. for (i = 8; i < RTMP_SIG_SIZE; i++)
  3659. clientsig[i] = 0xff;
  3660. #else
  3661. for (i = 8; i < RTMP_SIG_SIZE; i++)
  3662. clientsig[i] = (char)(rand() % 256);
  3663. #endif
  3664. if (!WriteN(r, clientbuf, RTMP_SIG_SIZE + 1))
  3665. return FALSE;
  3666. if (ReadN(r, &type, 1) != 1) /* 0x03 or 0x06 */
  3667. return FALSE;
  3668. RTMP_Log(RTMP_LOGDEBUG, "%s: Type Answer : %02X", __FUNCTION__, type);
  3669. if (type != clientbuf[0])
  3670. RTMP_Log(RTMP_LOGWARNING, "%s: Type mismatch: client sent %d, server answered %d",
  3671. __FUNCTION__, clientbuf[0], type);
  3672. if (ReadN(r, serversig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE)
  3673. return FALSE;
  3674. /* decode server response */
  3675. memcpy(&suptime, serversig, 4);
  3676. suptime = ntohl(suptime);
  3677. RTMP_Log(RTMP_LOGDEBUG, "%s: Server Uptime : %d", __FUNCTION__, suptime);
  3678. RTMP_Log(RTMP_LOGDEBUG, "%s: FMS Version : %d.%d.%d.%d", __FUNCTION__,
  3679. serversig[4], serversig[5], serversig[6], serversig[7]);
  3680. /* 2nd part of handshake */
  3681. if (!WriteN(r, serversig, RTMP_SIG_SIZE))
  3682. return FALSE;
  3683. if (ReadN(r, serversig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE)
  3684. return FALSE;
  3685. bMatch = (memcmp(serversig, clientsig, RTMP_SIG_SIZE) == 0);
  3686. if (!bMatch)
  3687. {
  3688. RTMP_Log(RTMP_LOGWARNING, "%s, client signature does not match!", __FUNCTION__);
  3689. }
  3690. /* er, totally unused? */
  3691. (void)FP9HandShake;
  3692. return TRUE;
  3693. }
  3694. static int
  3695. SHandShake(RTMP *r)
  3696. {
  3697. int i;
  3698. char serverbuf[RTMP_SIG_SIZE + 1], *serversig = serverbuf + 1;
  3699. char clientsig[RTMP_SIG_SIZE];
  3700. uint32_t uptime;
  3701. int bMatch;
  3702. if (ReadN(r, serverbuf, 1) != 1) /* 0x03 or 0x06 */
  3703. return FALSE;
  3704. RTMP_Log(RTMP_LOGDEBUG, "%s: Type Request : %02X", __FUNCTION__, serverbuf[0]);
  3705. if (serverbuf[0] != 3)
  3706. {
  3707. RTMP_Log(RTMP_LOGERROR, "%s: Type unknown: client sent %02X",
  3708. __FUNCTION__, serverbuf[0]);
  3709. return FALSE;
  3710. }
  3711. uptime = htonl(RTMP_GetTime());
  3712. memcpy(serversig, &uptime, 4);
  3713. memset(&serversig[4], 0, 4);
  3714. #ifdef _DEBUG
  3715. for (i = 8; i < RTMP_SIG_SIZE; i++)
  3716. serversig[i] = 0xff;
  3717. #else
  3718. for (i = 8; i < RTMP_SIG_SIZE; i++)
  3719. serversig[i] = (char)(rand() % 256);
  3720. #endif
  3721. if (!WriteN(r, serverbuf, RTMP_SIG_SIZE + 1))
  3722. return FALSE;
  3723. if (ReadN(r, clientsig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE)
  3724. return FALSE;
  3725. /* decode client response */
  3726. memcpy(&uptime, clientsig, 4);
  3727. uptime = ntohl(uptime);
  3728. RTMP_Log(RTMP_LOGDEBUG, "%s: Client Uptime : %d", __FUNCTION__, uptime);
  3729. RTMP_Log(RTMP_LOGDEBUG, "%s: Player Version: %d.%d.%d.%d", __FUNCTION__,
  3730. clientsig[4], clientsig[5], clientsig[6], clientsig[7]);
  3731. /* 2nd part of handshake */
  3732. if (!WriteN(r, clientsig, RTMP_SIG_SIZE))
  3733. return FALSE;
  3734. if (ReadN(r, clientsig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE)
  3735. return FALSE;
  3736. bMatch = (memcmp(serversig, clientsig, RTMP_SIG_SIZE) == 0);
  3737. if (!bMatch)
  3738. {
  3739. RTMP_Log(RTMP_LOGWARNING, "%s, client signature does not match!", __FUNCTION__);
  3740. }
  3741. return TRUE;
  3742. }
  3743. #endif
  3744. int
  3745. RTMP_SendChunk(RTMP *r, RTMPChunk *chunk)
  3746. {
  3747. int wrote;
  3748. char hbuf[RTMP_MAX_HEADER_SIZE];
  3749. RTMP_Log(RTMP_LOGDEBUG2, "%s: fd=%d, size=%d", __FUNCTION__, r->m_sb.sb_socket,
  3750. chunk->c_chunkSize);
  3751. RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t *)chunk->c_header, chunk->c_headerSize);
  3752. if (chunk->c_chunkSize)
  3753. {
  3754. char *ptr = chunk->c_chunk - chunk->c_headerSize;
  3755. RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t *)chunk->c_chunk, chunk->c_chunkSize);
  3756. /* save header bytes we're about to overwrite */
  3757. memcpy(hbuf, ptr, chunk->c_headerSize);
  3758. memcpy(ptr, chunk->c_header, chunk->c_headerSize);
  3759. wrote = WriteN(r, ptr, chunk->c_headerSize + chunk->c_chunkSize);
  3760. memcpy(ptr, hbuf, chunk->c_headerSize);
  3761. }
  3762. else
  3763. wrote = WriteN(r, chunk->c_header, chunk->c_headerSize);
  3764. return wrote;
  3765. }
  3766. int
  3767. RTMP_SendPacket(RTMP *r, RTMPPacket *packet, int queue)
  3768. {
  3769. const RTMPPacket *prevPacket;
  3770. uint32_t last = 0;
  3771. int nSize;
  3772. int hSize, cSize;
  3773. char *header, *hptr, *hend, hbuf[RTMP_MAX_HEADER_SIZE], c;
  3774. uint32_t t;
  3775. char *buffer, *tbuf = NULL, *toff = NULL;
  3776. int nChunkSize;
  3777. int tlen;
  3778. if (packet->m_nChannel >= r->m_channelsAllocatedOut)
  3779. {
  3780. int n = packet->m_nChannel + 10;
  3781. RTMPPacket **packets = realloc(r->m_vecChannelsOut, sizeof(RTMPPacket*) * n);
  3782. if (!packets)
  3783. {
  3784. free(r->m_vecChannelsOut);
  3785. r->m_vecChannelsOut = NULL;
  3786. r->m_channelsAllocatedOut = 0;
  3787. return FALSE;
  3788. }
  3789. r->m_vecChannelsOut = packets;
  3790. memset(r->m_vecChannelsOut + r->m_channelsAllocatedOut, 0, sizeof(RTMPPacket*) * (n - r->m_channelsAllocatedOut));
  3791. r->m_channelsAllocatedOut = n;
  3792. }
  3793. prevPacket = r->m_vecChannelsOut[packet->m_nChannel];
  3794. if (prevPacket && packet->m_headerType != RTMP_PACKET_SIZE_LARGE)
  3795. {
  3796. /* compress a bit by using the prev packet's attributes */
  3797. if (prevPacket->m_nBodySize == packet->m_nBodySize
  3798. && prevPacket->m_packetType == packet->m_packetType
  3799. && packet->m_headerType == RTMP_PACKET_SIZE_MEDIUM)
  3800. packet->m_headerType = RTMP_PACKET_SIZE_SMALL;
  3801. if (prevPacket->m_nTimeStamp == packet->m_nTimeStamp
  3802. && packet->m_headerType == RTMP_PACKET_SIZE_SMALL)
  3803. packet->m_headerType = RTMP_PACKET_SIZE_MINIMUM;
  3804. last = prevPacket->m_nTimeStamp;
  3805. }
  3806. if (packet->m_headerType > 3) /* sanity */
  3807. {
  3808. RTMP_Log(RTMP_LOGERROR, "sanity failed!! trying to send header of type: 0x%02x.",
  3809. (unsigned char)packet->m_headerType);
  3810. return FALSE;
  3811. }
  3812. nSize = packetSize[packet->m_headerType];
  3813. hSize = nSize;
  3814. cSize = 0;
  3815. t = packet->m_nTimeStamp - last;
  3816. if (packet->m_body)
  3817. {
  3818. header = packet->m_body - nSize;
  3819. hend = packet->m_body;
  3820. }
  3821. else
  3822. {
  3823. header = hbuf + 6;
  3824. hend = hbuf + sizeof(hbuf);
  3825. }
  3826. if (packet->m_nChannel > 319)
  3827. cSize = 2;
  3828. else if (packet->m_nChannel > 63)
  3829. cSize = 1;
  3830. if (cSize)
  3831. {
  3832. header -= cSize;
  3833. hSize += cSize;
  3834. }
  3835. if (nSize > 1 && t >= 0xffffff)
  3836. {
  3837. header -= 4;
  3838. hSize += 4;
  3839. }
  3840. hptr = header;
  3841. c = packet->m_headerType << 6;
  3842. switch (cSize)
  3843. {
  3844. case 0:
  3845. c |= packet->m_nChannel;
  3846. break;
  3847. case 1:
  3848. break;
  3849. case 2:
  3850. c |= 1;
  3851. break;
  3852. }
  3853. *hptr++ = c;
  3854. if (cSize)
  3855. {
  3856. int tmp = packet->m_nChannel - 64;
  3857. *hptr++ = tmp & 0xff;
  3858. if (cSize == 2)
  3859. *hptr++ = tmp >> 8;
  3860. }
  3861. if (nSize > 1)
  3862. {
  3863. hptr = AMF_EncodeInt24(hptr, hend, t > 0xffffff ? 0xffffff : t);
  3864. }
  3865. if (nSize > 4)
  3866. {
  3867. hptr = AMF_EncodeInt24(hptr, hend, packet->m_nBodySize);
  3868. *hptr++ = packet->m_packetType;
  3869. }
  3870. if (nSize > 8)
  3871. hptr += EncodeInt32LE(hptr, packet->m_nInfoField2);
  3872. if (nSize > 1 && t >= 0xffffff)
  3873. hptr = AMF_EncodeInt32(hptr, hend, t);
  3874. nSize = packet->m_nBodySize;
  3875. buffer = packet->m_body;
  3876. nChunkSize = r->m_outChunkSize;
  3877. RTMP_Log(RTMP_LOGDEBUG2, "%s: fd=%d, size=%d", __FUNCTION__, r->m_sb.sb_socket,
  3878. nSize);
  3879. /* send all chunks in one HTTP request */
  3880. if (r->Link.protocol & RTMP_FEATURE_HTTP)
  3881. {
  3882. int chunks = (nSize+nChunkSize-1) / nChunkSize;
  3883. if (chunks > 1)
  3884. {
  3885. tlen = chunks * (cSize + 1) + nSize + hSize;
  3886. tbuf = malloc(tlen);
  3887. if (!tbuf)
  3888. return FALSE;
  3889. toff = tbuf;
  3890. }
  3891. }
  3892. while (nSize + hSize)
  3893. {
  3894. int wrote;
  3895. if (nSize < nChunkSize)
  3896. nChunkSize = nSize;
  3897. RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t *)header, hSize);
  3898. RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t *)buffer, nChunkSize);
  3899. if (tbuf)
  3900. {
  3901. memcpy(toff, header, nChunkSize + hSize);
  3902. toff += nChunkSize + hSize;
  3903. }
  3904. else
  3905. {
  3906. wrote = WriteN(r, header, nChunkSize + hSize);
  3907. if (!wrote)
  3908. return FALSE;
  3909. }
  3910. nSize -= nChunkSize;
  3911. buffer += nChunkSize;
  3912. hSize = 0;
  3913. if (nSize > 0)
  3914. {
  3915. header = buffer - 1;
  3916. hSize = 1;
  3917. if (cSize)
  3918. {
  3919. header -= cSize;
  3920. hSize += cSize;
  3921. }
  3922. *header = (0xc0 | c);
  3923. if (cSize)
  3924. {
  3925. int tmp = packet->m_nChannel - 64;
  3926. header[1] = tmp & 0xff;
  3927. if (cSize == 2)
  3928. header[2] = tmp >> 8;
  3929. }
  3930. }
  3931. }
  3932. if (tbuf)
  3933. {
  3934. int wrote = WriteN(r, tbuf, toff-tbuf);
  3935. free(tbuf);
  3936. tbuf = NULL;
  3937. if (!wrote)
  3938. return FALSE;
  3939. }
  3940. /* we invoked a remote method */
  3941. if (packet->m_packetType == RTMP_PACKET_TYPE_INVOKE)
  3942. {
  3943. AVal method;
  3944. char *ptr;
  3945. ptr = packet->m_body + 1;
  3946. AMF_DecodeString(ptr, &method);
  3947. RTMP_Log(RTMP_LOGDEBUG, "Invoking %s", method.av_val);
  3948. /* keep it in call queue till result arrives */
  3949. if (queue)
  3950. {
  3951. int txn;
  3952. ptr += 3 + method.av_len;
  3953. txn = (int)AMF_DecodeNumber(ptr);
  3954. AV_queue(&r->m_methodCalls, &r->m_numCalls, &method, txn);
  3955. }
  3956. }
  3957. if (!r->m_vecChannelsOut[packet->m_nChannel])
  3958. r->m_vecChannelsOut[packet->m_nChannel] = malloc(sizeof(RTMPPacket));
  3959. memcpy(r->m_vecChannelsOut[packet->m_nChannel], packet, sizeof(RTMPPacket));
  3960. return TRUE;
  3961. }
  3962. int
  3963. RTMP_Serve(RTMP *r)
  3964. {
  3965. return SHandShake(r);
  3966. }
  3967. void
  3968. RTMP_Close(RTMP *r)
  3969. {
  3970. int i;
  3971. if (RTMP_IsConnected(r))
  3972. {
  3973. if (r->m_stream_id > 0)
  3974. {
  3975. i = r->m_stream_id;
  3976. r->m_stream_id = 0;
  3977. if ((r->Link.protocol & RTMP_FEATURE_WRITE))
  3978. SendFCUnpublish(r);
  3979. SendDeleteStream(r, i);
  3980. }
  3981. if (r->m_clientID.av_val)
  3982. {
  3983. HTTP_Post(r, RTMPT_CLOSE, "", 1);
  3984. free(r->m_clientID.av_val);
  3985. r->m_clientID.av_val = NULL;
  3986. r->m_clientID.av_len = 0;
  3987. }
  3988. RTMPSockBuf_Close(&r->m_sb);
  3989. }
  3990. r->m_stream_id = -1;
  3991. r->m_sb.sb_socket = -1;
  3992. r->m_nBWCheckCounter = 0;
  3993. r->m_nBytesIn = 0;
  3994. r->m_nBytesInSent = 0;
  3995. if (r->m_read.flags & RTMP_READ_HEADER)
  3996. {
  3997. free(r->m_read.buf);
  3998. r->m_read.buf = NULL;
  3999. }
  4000. r->m_read.dataType = 0;
  4001. r->m_read.flags = 0;
  4002. r->m_read.status = 0;
  4003. r->m_read.nResumeTS = 0;
  4004. r->m_read.nIgnoredFrameCounter = 0;
  4005. r->m_read.nIgnoredFlvFrameCounter = 0;
  4006. r->m_write.m_nBytesRead = 0;
  4007. RTMPPacket_Free(&r->m_write);
  4008. for (i = 0; i < r->m_channelsAllocatedIn; i++)
  4009. {
  4010. if (r->m_vecChannelsIn[i])
  4011. {
  4012. RTMPPacket_Free(r->m_vecChannelsIn[i]);
  4013. free(r->m_vecChannelsIn[i]);
  4014. r->m_vecChannelsIn[i] = NULL;
  4015. }
  4016. }
  4017. free(r->m_vecChannelsIn);
  4018. r->m_vecChannelsIn = NULL;
  4019. free(r->m_channelTimestamp);
  4020. r->m_channelTimestamp = NULL;
  4021. r->m_channelsAllocatedIn = 0;
  4022. for (i = 0; i < r->m_channelsAllocatedOut; i++)
  4023. {
  4024. if (r->m_vecChannelsOut[i])
  4025. {
  4026. free(r->m_vecChannelsOut[i]);
  4027. r->m_vecChannelsOut[i] = NULL;
  4028. }
  4029. }
  4030. free(r->m_vecChannelsOut);
  4031. r->m_vecChannelsOut = NULL;
  4032. r->m_channelsAllocatedOut = 0;
  4033. AV_clear(r->m_methodCalls, r->m_numCalls);
  4034. r->m_methodCalls = NULL;
  4035. r->m_numCalls = 0;
  4036. r->m_numInvokes = 0;
  4037. r->m_bPlaying = FALSE;
  4038. r->m_sb.sb_size = 0;
  4039. r->m_msgCounter = 0;
  4040. r->m_resplen = 0;
  4041. r->m_unackd = 0;
  4042. if (r->Link.lFlags & RTMP_LF_FTCU)
  4043. {
  4044. free(r->Link.tcUrl.av_val);
  4045. r->Link.tcUrl.av_val = NULL;
  4046. r->Link.lFlags ^= RTMP_LF_FTCU;
  4047. }
  4048. #if defined(CRYPTO) || defined(USE_ONLY_MD5)
  4049. if (!(r->Link.protocol & RTMP_FEATURE_WRITE) || (r->Link.pFlags & RTMP_PUB_CLEAN))
  4050. {
  4051. free(r->Link.playpath0.av_val);
  4052. r->Link.playpath0.av_val = NULL;
  4053. }
  4054. if ((r->Link.protocol & RTMP_FEATURE_WRITE) &&
  4055. (r->Link.pFlags & RTMP_PUB_CLEAN) &&
  4056. (r->Link.pFlags & RTMP_PUB_ALLOC))
  4057. {
  4058. free(r->Link.app.av_val);
  4059. r->Link.app.av_val = NULL;
  4060. free(r->Link.tcUrl.av_val);
  4061. r->Link.tcUrl.av_val = NULL;
  4062. }
  4063. #elif defined(CRYPTO)
  4064. if (r->Link.dh)
  4065. {
  4066. MDH_free(r->Link.dh);
  4067. r->Link.dh = NULL;
  4068. }
  4069. if (r->Link.rc4keyIn)
  4070. {
  4071. RC4_free(r->Link.rc4keyIn);
  4072. r->Link.rc4keyIn = NULL;
  4073. }
  4074. if (r->Link.rc4keyOut)
  4075. {
  4076. RC4_free(r->Link.rc4keyOut);
  4077. r->Link.rc4keyOut = NULL;
  4078. }
  4079. #else
  4080. free(r->Link.playpath0.av_val);
  4081. r->Link.playpath0.av_val = NULL;
  4082. #endif
  4083. }
  4084. int
  4085. RTMPSockBuf_Fill(RTMPSockBuf *sb)
  4086. {
  4087. int nBytes;
  4088. if (!sb->sb_size)
  4089. sb->sb_start = sb->sb_buf;
  4090. while (1)
  4091. {
  4092. nBytes = (int)sizeof(sb->sb_buf) - 1 - sb->sb_size - (sb->sb_start - sb->sb_buf);
  4093. #if defined(CRYPTO) && !defined(NO_SSL)
  4094. if (sb->sb_ssl)
  4095. {
  4096. nBytes = TLS_read(sb->sb_ssl, sb->sb_start + sb->sb_size, nBytes);
  4097. }
  4098. else
  4099. #endif
  4100. {
  4101. nBytes = recv(sb->sb_socket, sb->sb_start + sb->sb_size, nBytes, 0);
  4102. }
  4103. if (nBytes > 0)
  4104. {
  4105. sb->sb_size += nBytes;
  4106. }
  4107. else if (nBytes == 0)
  4108. {
  4109. RTMP_Log(RTMP_LOGERROR, "%s, remote host closed connection",
  4110. __FUNCTION__);
  4111. }
  4112. else
  4113. {
  4114. int level;
  4115. int sockerr = GetSockError();
  4116. if (sockerr == EWOULDBLOCK || sockerr == EAGAIN)
  4117. level = RTMP_LOGDEBUG;
  4118. else
  4119. level = RTMP_LOGERROR;
  4120. RTMP_Log(level, "%s, recv returned %d. GetSockError(): %d (%s)",
  4121. __FUNCTION__, nBytes, sockerr, socketerror(sockerr));
  4122. if (sockerr == EINTR && !RTMP_ctrlC)
  4123. continue;
  4124. if (sockerr == EWOULDBLOCK || sockerr == EAGAIN)
  4125. {
  4126. sb->sb_timedout = TRUE;
  4127. nBytes = 0;
  4128. }
  4129. }
  4130. break;
  4131. }
  4132. return nBytes;
  4133. }
  4134. int
  4135. RTMPSockBuf_Send(RTMPSockBuf *sb, const char *buf, int len)
  4136. {
  4137. int rc;
  4138. #if defined(RTMP_NETSTACK_DUMP)
  4139. fwrite(buf, 1, len, netstackdump);
  4140. #endif
  4141. #if defined(CRYPTO) && !defined(NO_SSL)
  4142. if (sb->sb_ssl)
  4143. {
  4144. rc = TLS_write(sb->sb_ssl, buf, len);
  4145. }
  4146. else
  4147. #endif
  4148. {
  4149. rc = send(sb->sb_socket, buf, len, 0);
  4150. }
  4151. return rc;
  4152. }
  4153. int
  4154. RTMPSockBuf_Close(RTMPSockBuf *sb)
  4155. {
  4156. #if defined(CRYPTO) && !defined(NO_SSL)
  4157. if (sb->sb_ssl)
  4158. {
  4159. TLS_shutdown(sb->sb_ssl);
  4160. TLS_close(sb->sb_ssl);
  4161. sb->sb_ssl = NULL;
  4162. }
  4163. #endif
  4164. if (sb->sb_socket != -1)
  4165. return closesocket(sb->sb_socket);
  4166. return 0;
  4167. }
  4168. #define HEX2BIN(a) (((a)&0x40)?((a)&0xf)+9:((a)&0xf))
  4169. static void
  4170. DecodeTEA(AVal *key, AVal *text)
  4171. {
  4172. uint32_t *v, k[4] = { 0 }, u;
  4173. uint32_t z, y, sum = 0, e, DELTA = 0x9e3779b9;
  4174. int32_t p, q;
  4175. int i, n;
  4176. unsigned char *ptr, *out;
  4177. /* prep key: pack 1st 16 chars into 4 LittleEndian ints */
  4178. ptr = (unsigned char *)key->av_val;
  4179. u = 0;
  4180. n = 0;
  4181. v = k;
  4182. p = key->av_len > 16 ? 16 : key->av_len;
  4183. for (i = 0; i < p; i++)
  4184. {
  4185. u |= ptr[i] << (n * 8);
  4186. if (n == 3)
  4187. {
  4188. *v++ = u;
  4189. u = 0;
  4190. n = 0;
  4191. }
  4192. else
  4193. {
  4194. n++;
  4195. }
  4196. }
  4197. /* any trailing chars */
  4198. if (u)
  4199. *v = u;
  4200. /* prep text: hex2bin, multiples of 4 */
  4201. n = (text->av_len + 7) / 8;
  4202. out = malloc(n * 8);
  4203. ptr = (unsigned char *)text->av_val;
  4204. v = (uint32_t *) out;
  4205. for (i = 0; i < n; i++)
  4206. {
  4207. u = (HEX2BIN(ptr[0]) << 4) + HEX2BIN(ptr[1]);
  4208. u |= ((HEX2BIN(ptr[2]) << 4) + HEX2BIN(ptr[3])) << 8;
  4209. u |= ((HEX2BIN(ptr[4]) << 4) + HEX2BIN(ptr[5])) << 16;
  4210. u |= ((HEX2BIN(ptr[6]) << 4) + HEX2BIN(ptr[7])) << 24;
  4211. *v++ = u;
  4212. ptr += 8;
  4213. }
  4214. v = (uint32_t *) out;
  4215. /* http://www.movable-type.co.uk/scripts/tea-block.html */
  4216. #define MX (((z>>5)^(y<<2)) + ((y>>3)^(z<<4))) ^ ((sum^y) + (k[(p&3)^e]^z));
  4217. z = v[n - 1];
  4218. y = v[0];
  4219. q = 6 + 52 / n;
  4220. sum = q * DELTA;
  4221. while (sum != 0)
  4222. {
  4223. e = sum >> 2 & 3;
  4224. for (p = n - 1; p > 0; p--)
  4225. z = v[p - 1], y = v[p] -= MX;
  4226. z = v[n - 1];
  4227. y = v[0] -= MX;
  4228. sum -= DELTA;
  4229. }
  4230. text->av_len /= 2;
  4231. memcpy(text->av_val, out, text->av_len);
  4232. free(out);
  4233. }
  4234. static int
  4235. HTTP_Post(RTMP *r, RTMPTCmd cmd, const char *buf, int len)
  4236. {
  4237. char hbuf[512];
  4238. int hlen = snprintf(hbuf, sizeof(hbuf), "POST /%s%s/%d HTTP/1.1\r\n"
  4239. "Host: %.*s:%d\r\n"
  4240. "Accept: */*\r\n"
  4241. "User-Agent: Shockwave Flash\r\n"
  4242. "Connection: Keep-Alive\r\n"
  4243. "Cache-Control: no-cache\r\n"
  4244. "Content-type: application/x-fcs\r\n"
  4245. "Content-length: %d\r\n\r\n", RTMPT_cmds[cmd],
  4246. r->m_clientID.av_val ? r->m_clientID.av_val : "",
  4247. r->m_msgCounter, r->Link.hostname.av_len, r->Link.hostname.av_val,
  4248. r->Link.port, len);
  4249. RTMPSockBuf_Send(&r->m_sb, hbuf, hlen);
  4250. hlen = RTMPSockBuf_Send(&r->m_sb, buf, len);
  4251. r->m_msgCounter++;
  4252. r->m_unackd++;
  4253. return hlen;
  4254. }
  4255. static int
  4256. HTTP_read(RTMP *r, int fill)
  4257. {
  4258. char *ptr;
  4259. int hlen;
  4260. restart:
  4261. if (fill)
  4262. RTMPSockBuf_Fill(&r->m_sb);
  4263. if (r->m_sb.sb_size < 13)
  4264. {
  4265. if (fill)
  4266. goto restart;
  4267. return -2;
  4268. }
  4269. if (strncmp(r->m_sb.sb_start, "HTTP/1.1 200 ", 13))
  4270. return -1;
  4271. r->m_sb.sb_start[r->m_sb.sb_size] = '\0';
  4272. if (!strstr(r->m_sb.sb_start, "\r\n\r\n"))
  4273. {
  4274. if (fill)
  4275. goto restart;
  4276. return -2;
  4277. }
  4278. ptr = r->m_sb.sb_start + sizeof("HTTP/1.1 200");
  4279. while ((ptr = strstr(ptr, "Content-")))
  4280. {
  4281. if (!strncasecmp(ptr+8, "length:", 7)) break;
  4282. ptr += 8;
  4283. }
  4284. if (!ptr)
  4285. return -1;
  4286. hlen = atoi(ptr+16);
  4287. ptr = strstr(ptr+16, "\r\n\r\n");
  4288. if (!ptr)
  4289. return -1;
  4290. ptr += 4;
  4291. if (ptr + (r->m_clientID.av_val ? 1 : hlen) > r->m_sb.sb_start + r->m_sb.sb_size)
  4292. {
  4293. if (fill)
  4294. goto restart;
  4295. return -2;
  4296. }
  4297. r->m_sb.sb_size -= ptr - r->m_sb.sb_start;
  4298. r->m_sb.sb_start = ptr;
  4299. r->m_unackd--;
  4300. if (!r->m_clientID.av_val)
  4301. {
  4302. r->m_clientID.av_len = hlen;
  4303. r->m_clientID.av_val = malloc(hlen+1);
  4304. if (!r->m_clientID.av_val)
  4305. return -1;
  4306. r->m_clientID.av_val[0] = '/';
  4307. memcpy(r->m_clientID.av_val+1, ptr, hlen-1);
  4308. r->m_clientID.av_val[hlen] = 0;
  4309. r->m_sb.sb_size = 0;
  4310. }
  4311. else
  4312. {
  4313. r->m_polling = *ptr++;
  4314. r->m_resplen = hlen - 1;
  4315. r->m_sb.sb_start++;
  4316. r->m_sb.sb_size--;
  4317. }
  4318. return 0;
  4319. }
  4320. #define MAX_IGNORED_FRAMES 50
  4321. /* Read from the stream until we get a media packet.
  4322. * Returns -3 if Play.Close/Stop, -2 if fatal error, -1 if no more media
  4323. * packets, 0 if ignorable error, >0 if there is a media packet
  4324. */
  4325. static int
  4326. Read_1_Packet(RTMP *r, char *buf, unsigned int buflen)
  4327. {
  4328. uint32_t prevTagSize = 0;
  4329. int rtnGetNextMediaPacket = 0, ret = RTMP_READ_EOF;
  4330. RTMPPacket packet = { 0 };
  4331. int recopy = FALSE;
  4332. unsigned int size;
  4333. char *ptr, *pend;
  4334. uint32_t nTimeStamp = 0;
  4335. unsigned int len;
  4336. rtnGetNextMediaPacket = RTMP_GetNextMediaPacket(r, &packet);
  4337. while (rtnGetNextMediaPacket)
  4338. {
  4339. char *packetBody = packet.m_body;
  4340. unsigned int nPacketLen = packet.m_nBodySize;
  4341. /* Return RTMP_READ_COMPLETE if this was completed nicely with
  4342. * invoke message Play.Stop or Play.Complete
  4343. */
  4344. if (rtnGetNextMediaPacket == 2)
  4345. {
  4346. RTMP_Log(RTMP_LOGDEBUG,
  4347. "Got Play.Complete or Play.Stop from server. "
  4348. "Assuming stream is complete");
  4349. ret = RTMP_READ_COMPLETE;
  4350. break;
  4351. }
  4352. r->m_read.dataType |= (((packet.m_packetType == RTMP_PACKET_TYPE_AUDIO) << 2) |
  4353. (packet.m_packetType == RTMP_PACKET_TYPE_VIDEO));
  4354. if (packet.m_packetType == RTMP_PACKET_TYPE_VIDEO && nPacketLen <= 5)
  4355. {
  4356. RTMP_Log(RTMP_LOGDEBUG, "ignoring too small video packet: size: %d",
  4357. nPacketLen);
  4358. ret = RTMP_READ_IGNORE;
  4359. break;
  4360. }
  4361. if (packet.m_packetType == RTMP_PACKET_TYPE_AUDIO && nPacketLen <= 1)
  4362. {
  4363. RTMP_Log(RTMP_LOGDEBUG, "ignoring too small audio packet: size: %d",
  4364. nPacketLen);
  4365. ret = RTMP_READ_IGNORE;
  4366. break;
  4367. }
  4368. if (r->m_read.flags & RTMP_READ_SEEKING)
  4369. {
  4370. ret = RTMP_READ_IGNORE;
  4371. break;
  4372. }
  4373. #ifdef _DEBUG
  4374. RTMP_Log(RTMP_LOGDEBUG, "type: %02X, size: %d, TS: %d ms, abs TS: %d",
  4375. packet.m_packetType, nPacketLen, packet.m_nTimeStamp,
  4376. packet.m_hasAbsTimestamp);
  4377. if (packet.m_packetType == RTMP_PACKET_TYPE_VIDEO)
  4378. RTMP_Log(RTMP_LOGDEBUG, "frametype: %02X", (*packetBody & 0xf0));
  4379. #endif
  4380. if (r->m_read.flags & RTMP_READ_RESUME)
  4381. {
  4382. /* check the header if we get one */
  4383. if (packet.m_nTimeStamp == 0)
  4384. {
  4385. if (r->m_read.nMetaHeaderSize > 0
  4386. && packet.m_packetType == RTMP_PACKET_TYPE_INFO)
  4387. {
  4388. AMFObject metaObj;
  4389. int nRes =
  4390. AMF_Decode(&metaObj, packetBody, nPacketLen, FALSE);
  4391. if (nRes >= 0)
  4392. {
  4393. AVal metastring;
  4394. AMFProp_GetString(AMF_GetProp(&metaObj, NULL, 0),
  4395. &metastring);
  4396. if (AVMATCH(&metastring, &av_onMetaData))
  4397. {
  4398. /* compare */
  4399. if ((r->m_read.nMetaHeaderSize != nPacketLen) ||
  4400. (memcmp
  4401. (r->m_read.metaHeader, packetBody,
  4402. r->m_read.nMetaHeaderSize) != 0))
  4403. {
  4404. ret = RTMP_READ_ERROR;
  4405. }
  4406. }
  4407. AMF_Reset(&metaObj);
  4408. if (ret == RTMP_READ_ERROR)
  4409. break;
  4410. }
  4411. }
  4412. /* check first keyframe to make sure we got the right position
  4413. * in the stream! (the first non ignored frame)
  4414. */
  4415. if (r->m_read.nInitialFrameSize > 0)
  4416. {
  4417. /* video or audio data */
  4418. if (packet.m_packetType == r->m_read.initialFrameType
  4419. && r->m_read.nInitialFrameSize == nPacketLen)
  4420. {
  4421. /* we don't compare the sizes since the packet can
  4422. * contain several FLV packets, just make sure the
  4423. * first frame is our keyframe (which we are going
  4424. * to rewrite)
  4425. */
  4426. if (memcmp
  4427. (r->m_read.initialFrame, packetBody,
  4428. r->m_read.nInitialFrameSize) == 0)
  4429. {
  4430. RTMP_Log(RTMP_LOGDEBUG, "Checked keyframe successfully!");
  4431. r->m_read.flags |= RTMP_READ_GOTKF;
  4432. /* ignore it! (what about audio data after it? it is
  4433. * handled by ignoring all 0ms frames, see below)
  4434. */
  4435. ret = RTMP_READ_IGNORE;
  4436. break;
  4437. }
  4438. }
  4439. /* hande FLV streams, even though the server resends the
  4440. * keyframe as an extra video packet it is also included
  4441. * in the first FLV stream chunk and we have to compare
  4442. * it and filter it out !!
  4443. */
  4444. if (packet.m_packetType == RTMP_PACKET_TYPE_FLASH_VIDEO)
  4445. {
  4446. /* basically we have to find the keyframe with the
  4447. * correct TS being nResumeTS
  4448. */
  4449. unsigned int pos = 0;
  4450. uint32_t ts = 0;
  4451. while (pos + 11 < nPacketLen)
  4452. {
  4453. /* size without header (11) and prevTagSize (4) */
  4454. uint32_t dataSize =
  4455. AMF_DecodeInt24(packetBody + pos + 1);
  4456. ts = AMF_DecodeInt24(packetBody + pos + 4);
  4457. ts |= (packetBody[pos + 7] << 24);
  4458. #ifdef _DEBUG
  4459. RTMP_Log(RTMP_LOGDEBUG,
  4460. "keyframe search: FLV Packet: type %02X, dataSize: %d, timeStamp: %d ms",
  4461. packetBody[pos], dataSize, ts);
  4462. #endif
  4463. /* ok, is it a keyframe?:
  4464. * well doesn't work for audio!
  4465. */
  4466. if (packetBody[pos /*6928, test 0 */ ] ==
  4467. r->m_read.initialFrameType
  4468. /* && (packetBody[11]&0xf0) == 0x10 */ )
  4469. {
  4470. if (ts == r->m_read.nResumeTS)
  4471. {
  4472. RTMP_Log(RTMP_LOGDEBUG,
  4473. "Found keyframe with resume-keyframe timestamp!");
  4474. if (r->m_read.nInitialFrameSize != dataSize
  4475. || memcmp(r->m_read.initialFrame,
  4476. packetBody + pos + 11,
  4477. r->m_read.
  4478. nInitialFrameSize) != 0)
  4479. {
  4480. RTMP_Log(RTMP_LOGERROR,
  4481. "FLV Stream: Keyframe doesn't match!");
  4482. ret = RTMP_READ_ERROR;
  4483. break;
  4484. }
  4485. r->m_read.flags |= RTMP_READ_GOTFLVK;
  4486. /* skip this packet?
  4487. * check whether skippable:
  4488. */
  4489. if (pos + 11 + dataSize + 4 > nPacketLen)
  4490. {
  4491. RTMP_Log(RTMP_LOGWARNING,
  4492. "Non skipable packet since it doesn't end with chunk, stream corrupt!");
  4493. ret = RTMP_READ_ERROR;
  4494. break;
  4495. }
  4496. packetBody += (pos + 11 + dataSize + 4);
  4497. nPacketLen -= (pos + 11 + dataSize + 4);
  4498. goto stopKeyframeSearch;
  4499. }
  4500. else if (r->m_read.nResumeTS < ts)
  4501. {
  4502. /* the timestamp ts will only increase with
  4503. * further packets, wait for seek
  4504. */
  4505. goto stopKeyframeSearch;
  4506. }
  4507. }
  4508. pos += (11 + dataSize + 4);
  4509. }
  4510. if (ts < r->m_read.nResumeTS)
  4511. {
  4512. RTMP_Log(RTMP_LOGERROR,
  4513. "First packet does not contain keyframe, all "
  4514. "timestamps are smaller than the keyframe "
  4515. "timestamp; probably the resume seek failed?");
  4516. }
  4517. stopKeyframeSearch:
  4518. ;
  4519. if (!(r->m_read.flags & RTMP_READ_GOTFLVK))
  4520. {
  4521. RTMP_Log(RTMP_LOGERROR,
  4522. "Couldn't find the seeked keyframe in this chunk!");
  4523. ret = RTMP_READ_IGNORE;
  4524. break;
  4525. }
  4526. }
  4527. }
  4528. }
  4529. if (packet.m_nTimeStamp > 0
  4530. && (r->m_read.flags & (RTMP_READ_GOTKF|RTMP_READ_GOTFLVK)))
  4531. {
  4532. /* another problem is that the server can actually change from
  4533. * 09/08 video/audio packets to an FLV stream or vice versa and
  4534. * our keyframe check will prevent us from going along with the
  4535. * new stream if we resumed.
  4536. *
  4537. * in this case set the 'found keyframe' variables to true.
  4538. * We assume that if we found one keyframe somewhere and were
  4539. * already beyond TS > 0 we have written data to the output
  4540. * which means we can accept all forthcoming data including the
  4541. * change between 08/09 <-> FLV packets
  4542. */
  4543. r->m_read.flags |= (RTMP_READ_GOTKF|RTMP_READ_GOTFLVK);
  4544. }
  4545. /* skip till we find our keyframe
  4546. * (seeking might put us somewhere before it)
  4547. */
  4548. if (!(r->m_read.flags & RTMP_READ_GOTKF) &&
  4549. packet.m_packetType != RTMP_PACKET_TYPE_FLASH_VIDEO)
  4550. {
  4551. RTMP_Log(RTMP_LOGWARNING,
  4552. "Stream does not start with requested frame, ignoring data... ");
  4553. r->m_read.nIgnoredFrameCounter++;
  4554. if (r->m_read.nIgnoredFrameCounter > MAX_IGNORED_FRAMES)
  4555. ret = RTMP_READ_ERROR; /* fatal error, couldn't continue stream */
  4556. else
  4557. ret = RTMP_READ_IGNORE;
  4558. break;
  4559. }
  4560. /* ok, do the same for FLV streams */
  4561. if (!(r->m_read.flags & RTMP_READ_GOTFLVK) &&
  4562. packet.m_packetType == RTMP_PACKET_TYPE_FLASH_VIDEO)
  4563. {
  4564. RTMP_Log(RTMP_LOGWARNING,
  4565. "Stream does not start with requested FLV frame, ignoring data... ");
  4566. r->m_read.nIgnoredFlvFrameCounter++;
  4567. if (r->m_read.nIgnoredFlvFrameCounter > MAX_IGNORED_FRAMES)
  4568. ret = RTMP_READ_ERROR;
  4569. else
  4570. ret = RTMP_READ_IGNORE;
  4571. break;
  4572. }
  4573. /* we have to ignore the 0ms frames since these are the first
  4574. * keyframes; we've got these so don't mess around with multiple
  4575. * copies sent by the server to us! (if the keyframe is found at a
  4576. * later position there is only one copy and it will be ignored by
  4577. * the preceding if clause)
  4578. */
  4579. if (!(r->m_read.flags & RTMP_READ_NO_IGNORE) &&
  4580. packet.m_packetType != RTMP_PACKET_TYPE_FLASH_VIDEO)
  4581. {
  4582. /* exclude type RTMP_PACKET_TYPE_FLASH_VIDEO since it can
  4583. * contain several FLV packets
  4584. */
  4585. if (packet.m_nTimeStamp == 0)
  4586. {
  4587. ret = RTMP_READ_IGNORE;
  4588. break;
  4589. }
  4590. else
  4591. {
  4592. /* stop ignoring packets */
  4593. r->m_read.flags |= RTMP_READ_NO_IGNORE;
  4594. }
  4595. }
  4596. }
  4597. /* calculate packet size and allocate slop buffer if necessary */
  4598. size = nPacketLen +
  4599. ((packet.m_packetType == RTMP_PACKET_TYPE_AUDIO
  4600. || packet.m_packetType == RTMP_PACKET_TYPE_VIDEO
  4601. || packet.m_packetType == RTMP_PACKET_TYPE_INFO) ? 11 : 0) +
  4602. (packet.m_packetType != RTMP_PACKET_TYPE_FLASH_VIDEO ? 4 : 0);
  4603. if (size + 4 > buflen)
  4604. {
  4605. /* the extra 4 is for the case of an FLV stream without a last
  4606. * prevTagSize (we need extra 4 bytes to append it) */
  4607. r->m_read.buf = malloc(size + 4);
  4608. if (r->m_read.buf == 0)
  4609. {
  4610. RTMP_Log(RTMP_LOGERROR, "Couldn't allocate memory!");
  4611. ret = RTMP_READ_ERROR; /* fatal error */
  4612. break;
  4613. }
  4614. recopy = TRUE;
  4615. ptr = r->m_read.buf;
  4616. }
  4617. else
  4618. {
  4619. ptr = buf;
  4620. }
  4621. pend = ptr + size + 4;
  4622. /* use to return timestamp of last processed packet */
  4623. /* audio (0x08), video (0x09) or metadata (0x12) packets :
  4624. * construct 11 byte header then add rtmp packet's data */
  4625. if (packet.m_packetType == RTMP_PACKET_TYPE_AUDIO
  4626. || packet.m_packetType == RTMP_PACKET_TYPE_VIDEO
  4627. || packet.m_packetType == RTMP_PACKET_TYPE_INFO)
  4628. {
  4629. nTimeStamp = r->m_read.nResumeTS + packet.m_nTimeStamp;
  4630. prevTagSize = 11 + nPacketLen;
  4631. *ptr = packet.m_packetType;
  4632. ptr++;
  4633. ptr = AMF_EncodeInt24(ptr, pend, nPacketLen);
  4634. #if 0
  4635. if(packet.m_packetType == RTMP_PACKET_TYPE_VIDEO)
  4636. {
  4637. /* H264 fix: */
  4638. if((packetBody[0] & 0x0f) == 7) /* CodecId = H264 */
  4639. {
  4640. uint8_t packetType = *(packetBody+1);
  4641. uint32_t ts = AMF_DecodeInt24(packetBody+2); /* composition time */
  4642. int32_t cts = (ts+0xff800000)^0xff800000;
  4643. RTMP_Log(RTMP_LOGDEBUG, "cts : %d\n", cts);
  4644. nTimeStamp -= cts;
  4645. /* get rid of the composition time */
  4646. CRTMP::EncodeInt24(packetBody+2, 0);
  4647. }
  4648. RTMP_Log(RTMP_LOGDEBUG, "VIDEO: nTimeStamp: 0x%08X (%d)\n", nTimeStamp, nTimeStamp);
  4649. }
  4650. #endif
  4651. ptr = AMF_EncodeInt24(ptr, pend, nTimeStamp);
  4652. *ptr = (char)((nTimeStamp & 0xFF000000) >> 24);
  4653. ptr++;
  4654. /* stream id */
  4655. ptr = AMF_EncodeInt24(ptr, pend, 0);
  4656. }
  4657. memcpy(ptr, packetBody, nPacketLen);
  4658. len = nPacketLen;
  4659. /* correct tagSize and obtain timestamp if we have an FLV stream */
  4660. if (packet.m_packetType == RTMP_PACKET_TYPE_FLASH_VIDEO)
  4661. {
  4662. unsigned int pos = 0;
  4663. int delta;
  4664. /* grab first timestamp and see if it needs fixing */
  4665. nTimeStamp = AMF_DecodeInt24(packetBody + 4);
  4666. nTimeStamp |= (packetBody[7] << 24);
  4667. delta = packet.m_nTimeStamp - nTimeStamp + r->m_read.nResumeTS;
  4668. while (pos + 11 < nPacketLen)
  4669. {
  4670. /* size without header (11) and without prevTagSize (4) */
  4671. uint32_t dataSize = AMF_DecodeInt24(packetBody + pos + 1);
  4672. nTimeStamp = AMF_DecodeInt24(packetBody + pos + 4);
  4673. nTimeStamp |= (packetBody[pos + 7] << 24);
  4674. if (delta)
  4675. {
  4676. nTimeStamp += delta;
  4677. AMF_EncodeInt24(ptr+pos+4, pend, nTimeStamp);
  4678. ptr[pos+7] = nTimeStamp>>24;
  4679. }
  4680. /* set data type */
  4681. r->m_read.dataType |= (((*(packetBody + pos) == 0x08) << 2) |
  4682. (*(packetBody + pos) == 0x09));
  4683. if (pos + 11 + dataSize + 4 > nPacketLen)
  4684. {
  4685. if (pos + 11 + dataSize > nPacketLen)
  4686. {
  4687. RTMP_Log(RTMP_LOGERROR,
  4688. "Wrong data size (%u), stream corrupted, aborting!",
  4689. dataSize);
  4690. ret = RTMP_READ_ERROR;
  4691. break;
  4692. }
  4693. RTMP_Log(RTMP_LOGWARNING, "No tagSize found, appending!");
  4694. /* we have to append a last tagSize! */
  4695. prevTagSize = dataSize + 11;
  4696. AMF_EncodeInt32(ptr + pos + 11 + dataSize, pend,
  4697. prevTagSize);
  4698. size += 4;
  4699. len += 4;
  4700. }
  4701. else
  4702. {
  4703. prevTagSize =
  4704. AMF_DecodeInt32(packetBody + pos + 11 + dataSize);
  4705. #ifdef _DEBUG
  4706. RTMP_Log(RTMP_LOGDEBUG,
  4707. "FLV Packet: type %02X, dataSize: %u, tagSize: %u, timeStamp: %u ms",
  4708. (unsigned char)packetBody[pos], dataSize, prevTagSize,
  4709. nTimeStamp);
  4710. #endif
  4711. if (prevTagSize != (dataSize + 11))
  4712. {
  4713. #ifdef _DEBUG
  4714. RTMP_Log(RTMP_LOGWARNING,
  4715. "Tag and data size are not consitent, writing tag size according to dataSize+11: %d",
  4716. dataSize + 11);
  4717. #endif
  4718. prevTagSize = dataSize + 11;
  4719. AMF_EncodeInt32(ptr + pos + 11 + dataSize, pend,
  4720. prevTagSize);
  4721. }
  4722. }
  4723. pos += prevTagSize + 4; /*(11+dataSize+4); */
  4724. }
  4725. }
  4726. ptr += len;
  4727. if (packet.m_packetType != RTMP_PACKET_TYPE_FLASH_VIDEO)
  4728. {
  4729. /* FLV tag packets contain their own prevTagSize */
  4730. AMF_EncodeInt32(ptr, pend, prevTagSize);
  4731. }
  4732. /* In non-live this nTimeStamp can contain an absolute TS.
  4733. * Update ext timestamp with this absolute offset in non-live mode
  4734. * otherwise report the relative one
  4735. */
  4736. /* RTMP_Log(RTMP_LOGDEBUG, "type: %02X, size: %d, pktTS: %dms, TS: %dms, bLiveStream: %d", packet.m_packetType, nPacketLen, packet.m_nTimeStamp, nTimeStamp, r->Link.lFlags & RTMP_LF_LIVE); */
  4737. r->m_read.timestamp = (r->Link.lFlags & RTMP_LF_LIVE) ? packet.m_nTimeStamp : nTimeStamp;
  4738. ret = size;
  4739. break;
  4740. }
  4741. if (rtnGetNextMediaPacket)
  4742. RTMPPacket_Free(&packet);
  4743. if (recopy)
  4744. {
  4745. len = (unsigned int)(ret) > buflen ? buflen : (unsigned int)ret;
  4746. memcpy(buf, r->m_read.buf, len);
  4747. r->m_read.bufpos = r->m_read.buf + len;
  4748. r->m_read.buflen = ret - len;
  4749. }
  4750. return ret;
  4751. }
  4752. static const char flvHeader[] = { 'F', 'L', 'V', 0x01,
  4753. 0x00, /* 0x04 == audio, 0x01 == video */
  4754. 0x00, 0x00, 0x00, 0x09,
  4755. 0x00, 0x00, 0x00, 0x00
  4756. };
  4757. #define HEADERBUF (128*1024)
  4758. int
  4759. RTMP_Read(RTMP *r, char *buf, int size)
  4760. {
  4761. int nRead = 0, total = 0;
  4762. /* can't continue */
  4763. fail:
  4764. switch (r->m_read.status)
  4765. {
  4766. case RTMP_READ_EOF:
  4767. case RTMP_READ_COMPLETE:
  4768. return 0;
  4769. case RTMP_READ_ERROR: /* corrupted stream, resume failed */
  4770. SetSockError(EINVAL);
  4771. return -1;
  4772. default:
  4773. break;
  4774. }
  4775. /* first time thru */
  4776. if (!(r->m_read.flags & RTMP_READ_HEADER))
  4777. {
  4778. if (!(r->m_read.flags & RTMP_READ_RESUME))
  4779. {
  4780. char *mybuf = malloc(HEADERBUF), *end = mybuf + HEADERBUF;
  4781. int cnt = 0;
  4782. r->m_read.buf = mybuf;
  4783. r->m_read.buflen = HEADERBUF;
  4784. memcpy(mybuf, flvHeader, sizeof(flvHeader));
  4785. r->m_read.buf += sizeof(flvHeader);
  4786. r->m_read.buflen -= sizeof(flvHeader);
  4787. while (r->m_read.timestamp == 0)
  4788. {
  4789. nRead = Read_1_Packet(r, r->m_read.buf, r->m_read.buflen);
  4790. if (nRead < 0)
  4791. {
  4792. free(mybuf);
  4793. r->m_read.buf = NULL;
  4794. r->m_read.buflen = 0;
  4795. r->m_read.status = nRead;
  4796. goto fail;
  4797. }
  4798. /* buffer overflow, fix buffer and give up */
  4799. if (r->m_read.buf < mybuf || r->m_read.buf > end)
  4800. {
  4801. mybuf = realloc(mybuf, cnt + nRead);
  4802. memcpy(mybuf+cnt, r->m_read.buf, nRead);
  4803. r->m_read.buf = mybuf+cnt+nRead;
  4804. break;
  4805. }
  4806. cnt += nRead;
  4807. r->m_read.buf += nRead;
  4808. r->m_read.buflen -= nRead;
  4809. if (r->m_read.dataType == 5)
  4810. break;
  4811. }
  4812. mybuf[4] = r->m_read.dataType;
  4813. r->m_read.buflen = r->m_read.buf - mybuf;
  4814. r->m_read.buf = mybuf;
  4815. r->m_read.bufpos = mybuf;
  4816. }
  4817. r->m_read.flags |= RTMP_READ_HEADER;
  4818. }
  4819. if ((r->m_read.flags & RTMP_READ_SEEKING) && r->m_read.buf)
  4820. {
  4821. /* drop whatever's here */
  4822. free(r->m_read.buf);
  4823. r->m_read.buf = NULL;
  4824. r->m_read.bufpos = NULL;
  4825. r->m_read.buflen = 0;
  4826. }
  4827. /* If there's leftover data buffered, use it up */
  4828. if (r->m_read.buf)
  4829. {
  4830. nRead = r->m_read.buflen;
  4831. if (nRead > size)
  4832. nRead = size;
  4833. memcpy(buf, r->m_read.bufpos, nRead);
  4834. r->m_read.buflen -= nRead;
  4835. if (!r->m_read.buflen)
  4836. {
  4837. free(r->m_read.buf);
  4838. r->m_read.buf = NULL;
  4839. r->m_read.bufpos = NULL;
  4840. }
  4841. else
  4842. {
  4843. r->m_read.bufpos += nRead;
  4844. }
  4845. buf += nRead;
  4846. total += nRead;
  4847. size -= nRead;
  4848. }
  4849. while (size > 0 && (nRead = Read_1_Packet(r, buf, size)) >= 0)
  4850. {
  4851. if (!nRead) continue;
  4852. buf += nRead;
  4853. total += nRead;
  4854. size -= nRead;
  4855. break;
  4856. }
  4857. if (nRead < 0)
  4858. r->m_read.status = nRead;
  4859. if (size < 0)
  4860. total += size;
  4861. return total;
  4862. }
  4863. static const AVal av_setDataFrame = AVC("@setDataFrame");
  4864. int
  4865. RTMP_Write(RTMP *r, const char *buf, int size)
  4866. {
  4867. RTMPPacket *pkt = &r->m_write;
  4868. char *pend, *enc;
  4869. int s2 = size, ret, num;
  4870. pkt->m_nChannel = 0x04; /* source channel */
  4871. pkt->m_nInfoField2 = r->m_stream_id;
  4872. while (s2)
  4873. {
  4874. if (!pkt->m_nBytesRead)
  4875. {
  4876. if (size < 11)
  4877. {
  4878. /* FLV pkt too small */
  4879. return 0;
  4880. }
  4881. if (buf[0] == 'F' && buf[1] == 'L' && buf[2] == 'V')
  4882. {
  4883. buf += 13;
  4884. s2 -= 13;
  4885. }
  4886. pkt->m_packetType = *buf++;
  4887. pkt->m_nBodySize = AMF_DecodeInt24(buf);
  4888. buf += 3;
  4889. pkt->m_nTimeStamp = AMF_DecodeInt24(buf);
  4890. buf += 3;
  4891. pkt->m_nTimeStamp |= *buf++ << 24;
  4892. buf += 3;
  4893. s2 -= 11;
  4894. if (((pkt->m_packetType == RTMP_PACKET_TYPE_AUDIO
  4895. || pkt->m_packetType == RTMP_PACKET_TYPE_VIDEO) &&
  4896. !pkt->m_nTimeStamp) || pkt->m_packetType == RTMP_PACKET_TYPE_INFO)
  4897. {
  4898. pkt->m_headerType = RTMP_PACKET_SIZE_LARGE;
  4899. if (pkt->m_packetType == RTMP_PACKET_TYPE_INFO)
  4900. pkt->m_nBodySize += 16;
  4901. }
  4902. else
  4903. {
  4904. pkt->m_headerType = RTMP_PACKET_SIZE_MEDIUM;
  4905. }
  4906. if (!RTMPPacket_Alloc(pkt, pkt->m_nBodySize))
  4907. {
  4908. RTMP_Log(RTMP_LOGDEBUG, "%s, failed to allocate packet", __FUNCTION__);
  4909. return FALSE;
  4910. }
  4911. enc = pkt->m_body;
  4912. pend = enc + pkt->m_nBodySize;
  4913. if (pkt->m_packetType == RTMP_PACKET_TYPE_INFO)
  4914. {
  4915. enc = AMF_EncodeString(enc, pend, &av_setDataFrame);
  4916. pkt->m_nBytesRead = enc - pkt->m_body;
  4917. }
  4918. }
  4919. else
  4920. {
  4921. enc = pkt->m_body + pkt->m_nBytesRead;
  4922. }
  4923. num = pkt->m_nBodySize - pkt->m_nBytesRead;
  4924. if (num > s2)
  4925. num = s2;
  4926. memcpy(enc, buf, num);
  4927. pkt->m_nBytesRead += num;
  4928. s2 -= num;
  4929. buf += num;
  4930. if (pkt->m_nBytesRead == pkt->m_nBodySize)
  4931. {
  4932. ret = RTMP_SendPacket(r, pkt, FALSE);
  4933. RTMPPacket_Free(pkt);
  4934. pkt->m_nBytesRead = 0;
  4935. if (!ret)
  4936. return -1;
  4937. buf += 4;
  4938. s2 -= 4;
  4939. if (s2 < 0)
  4940. break;
  4941. }
  4942. }
  4943. return size+s2;
  4944. }