Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

strophe.js 179KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492
  1. /** File: strophe.js
  2. * A JavaScript library for XMPP BOSH/XMPP over Websocket.
  3. *
  4. * This is the JavaScript version of the Strophe library. Since JavaScript
  5. * had no facilities for persistent TCP connections, this library uses
  6. * Bidirectional-streams Over Synchronous HTTP (BOSH) to emulate
  7. * a persistent, stateful, two-way connection to an XMPP server. More
  8. * information on BOSH can be found in XEP 124.
  9. *
  10. * This version of Strophe also works with WebSockets.
  11. * For more information on XMPP-over WebSocket see this RFC:
  12. * http://tools.ietf.org/html/rfc7395
  13. */
  14. /* All of the Strophe globals are defined in this special function below so
  15. * that references to the globals become closures. This will ensure that
  16. * on page reload, these references will still be available to callbacks
  17. * that are still executing.
  18. */
  19. /* jshint ignore:start */
  20. (function (callback) {
  21. /* jshint ignore:end */
  22. // This code was written by Tyler Akins and has been placed in the
  23. // public domain. It would be nice if you left this header intact.
  24. // Base64 code from Tyler Akins -- http://rumkin.com
  25. (function (root, factory) {
  26. if (typeof define === 'function' && define.amd) {
  27. define('strophe-base64', function () {
  28. return factory();
  29. });
  30. } else {
  31. // Browser globals
  32. root.Base64 = factory();
  33. }
  34. }(this, function () {
  35. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  36. var obj = {
  37. /**
  38. * Encodes a string in base64
  39. * @param {String} input The string to encode in base64.
  40. */
  41. encode: function (input) {
  42. var output = "";
  43. var chr1, chr2, chr3;
  44. var enc1, enc2, enc3, enc4;
  45. var i = 0;
  46. do {
  47. chr1 = input.charCodeAt(i++);
  48. chr2 = input.charCodeAt(i++);
  49. chr3 = input.charCodeAt(i++);
  50. enc1 = chr1 >> 2;
  51. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  52. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  53. enc4 = chr3 & 63;
  54. if (isNaN(chr2)) {
  55. enc2 = ((chr1 & 3) << 4);
  56. enc3 = enc4 = 64;
  57. } else if (isNaN(chr3)) {
  58. enc4 = 64;
  59. }
  60. output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  61. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  62. } while (i < input.length);
  63. return output;
  64. },
  65. /**
  66. * Decodes a base64 string.
  67. * @param {String} input The string to decode.
  68. */
  69. decode: function (input) {
  70. var output = "";
  71. var chr1, chr2, chr3;
  72. var enc1, enc2, enc3, enc4;
  73. var i = 0;
  74. // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
  75. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  76. do {
  77. enc1 = keyStr.indexOf(input.charAt(i++));
  78. enc2 = keyStr.indexOf(input.charAt(i++));
  79. enc3 = keyStr.indexOf(input.charAt(i++));
  80. enc4 = keyStr.indexOf(input.charAt(i++));
  81. chr1 = (enc1 << 2) | (enc2 >> 4);
  82. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  83. chr3 = ((enc3 & 3) << 6) | enc4;
  84. output = output + String.fromCharCode(chr1);
  85. if (enc3 != 64) {
  86. output = output + String.fromCharCode(chr2);
  87. }
  88. if (enc4 != 64) {
  89. output = output + String.fromCharCode(chr3);
  90. }
  91. } while (i < input.length);
  92. return output;
  93. }
  94. };
  95. return obj;
  96. }));
  97. /*
  98. * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
  99. * in FIPS PUB 180-1
  100. * Version 2.1a Copyright Paul Johnston 2000 - 2002.
  101. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  102. * Distributed under the BSD License
  103. * See http://pajhome.org.uk/crypt/md5 for details.
  104. */
  105. /* jshint undef: true, unused: true:, noarg: true, latedef: true */
  106. /* global define */
  107. /* Some functions and variables have been stripped for use with Strophe */
  108. (function (root, factory) {
  109. if (typeof define === 'function' && define.amd) {
  110. define('strophe-sha1', function () {
  111. return factory();
  112. });
  113. } else {
  114. // Browser globals
  115. root.SHA1 = factory();
  116. }
  117. }(this, function () {
  118. /*
  119. * Calculate the SHA-1 of an array of big-endian words, and a bit length
  120. */
  121. function core_sha1(x, len)
  122. {
  123. /* append padding */
  124. x[len >> 5] |= 0x80 << (24 - len % 32);
  125. x[((len + 64 >> 9) << 4) + 15] = len;
  126. var w = new Array(80);
  127. var a = 1732584193;
  128. var b = -271733879;
  129. var c = -1732584194;
  130. var d = 271733878;
  131. var e = -1009589776;
  132. var i, j, t, olda, oldb, oldc, oldd, olde;
  133. for (i = 0; i < x.length; i += 16)
  134. {
  135. olda = a;
  136. oldb = b;
  137. oldc = c;
  138. oldd = d;
  139. olde = e;
  140. for (j = 0; j < 80; j++)
  141. {
  142. if (j < 16) { w[j] = x[i + j]; }
  143. else { w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); }
  144. t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
  145. safe_add(safe_add(e, w[j]), sha1_kt(j)));
  146. e = d;
  147. d = c;
  148. c = rol(b, 30);
  149. b = a;
  150. a = t;
  151. }
  152. a = safe_add(a, olda);
  153. b = safe_add(b, oldb);
  154. c = safe_add(c, oldc);
  155. d = safe_add(d, oldd);
  156. e = safe_add(e, olde);
  157. }
  158. return [a, b, c, d, e];
  159. }
  160. /*
  161. * Perform the appropriate triplet combination function for the current
  162. * iteration
  163. */
  164. function sha1_ft(t, b, c, d)
  165. {
  166. if (t < 20) { return (b & c) | ((~b) & d); }
  167. if (t < 40) { return b ^ c ^ d; }
  168. if (t < 60) { return (b & c) | (b & d) | (c & d); }
  169. return b ^ c ^ d;
  170. }
  171. /*
  172. * Determine the appropriate additive constant for the current iteration
  173. */
  174. function sha1_kt(t)
  175. {
  176. return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
  177. (t < 60) ? -1894007588 : -899497514;
  178. }
  179. /*
  180. * Calculate the HMAC-SHA1 of a key and some data
  181. */
  182. function core_hmac_sha1(key, data)
  183. {
  184. var bkey = str2binb(key);
  185. if (bkey.length > 16) { bkey = core_sha1(bkey, key.length * 8); }
  186. var ipad = new Array(16), opad = new Array(16);
  187. for (var i = 0; i < 16; i++)
  188. {
  189. ipad[i] = bkey[i] ^ 0x36363636;
  190. opad[i] = bkey[i] ^ 0x5C5C5C5C;
  191. }
  192. var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * 8);
  193. return core_sha1(opad.concat(hash), 512 + 160);
  194. }
  195. /*
  196. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  197. * to work around bugs in some JS interpreters.
  198. */
  199. function safe_add(x, y)
  200. {
  201. var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  202. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  203. return (msw << 16) | (lsw & 0xFFFF);
  204. }
  205. /*
  206. * Bitwise rotate a 32-bit number to the left.
  207. */
  208. function rol(num, cnt)
  209. {
  210. return (num << cnt) | (num >>> (32 - cnt));
  211. }
  212. /*
  213. * Convert an 8-bit or 16-bit string to an array of big-endian words
  214. * In 8-bit function, characters >255 have their hi-byte silently ignored.
  215. */
  216. function str2binb(str)
  217. {
  218. var bin = [];
  219. var mask = 255;
  220. for (var i = 0; i < str.length * 8; i += 8)
  221. {
  222. bin[i>>5] |= (str.charCodeAt(i / 8) & mask) << (24 - i%32);
  223. }
  224. return bin;
  225. }
  226. /*
  227. * Convert an array of big-endian words to a string
  228. */
  229. function binb2str(bin)
  230. {
  231. var str = "";
  232. var mask = 255;
  233. for (var i = 0; i < bin.length * 32; i += 8)
  234. {
  235. str += String.fromCharCode((bin[i>>5] >>> (24 - i%32)) & mask);
  236. }
  237. return str;
  238. }
  239. /*
  240. * Convert an array of big-endian words to a base-64 string
  241. */
  242. function binb2b64(binarray)
  243. {
  244. var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  245. var str = "";
  246. var triplet, j;
  247. for (var i = 0; i < binarray.length * 4; i += 3)
  248. {
  249. triplet = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16) |
  250. (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 ) |
  251. ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
  252. for (j = 0; j < 4; j++)
  253. {
  254. if (i * 8 + j * 6 > binarray.length * 32) { str += "="; }
  255. else { str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); }
  256. }
  257. }
  258. return str;
  259. }
  260. /*
  261. * These are the functions you'll usually want to call
  262. * They take string arguments and return either hex or base-64 encoded strings
  263. */
  264. return {
  265. b64_hmac_sha1: function (key, data){ return binb2b64(core_hmac_sha1(key, data)); },
  266. b64_sha1: function (s) { return binb2b64(core_sha1(str2binb(s),s.length * 8)); },
  267. binb2str: binb2str,
  268. core_hmac_sha1: core_hmac_sha1,
  269. str_hmac_sha1: function (key, data){ return binb2str(core_hmac_sha1(key, data)); },
  270. str_sha1: function (s) { return binb2str(core_sha1(str2binb(s),s.length * 8)); },
  271. };
  272. }));
  273. /*
  274. * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  275. * Digest Algorithm, as defined in RFC 1321.
  276. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
  277. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  278. * Distributed under the BSD License
  279. * See http://pajhome.org.uk/crypt/md5 for more info.
  280. */
  281. /*
  282. * Everything that isn't used by Strophe has been stripped here!
  283. */
  284. (function (root, factory) {
  285. if (typeof define === 'function' && define.amd) {
  286. define('strophe-md5', function () {
  287. return factory();
  288. });
  289. } else {
  290. // Browser globals
  291. root.MD5 = factory();
  292. }
  293. }(this, function (b) {
  294. /*
  295. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  296. * to work around bugs in some JS interpreters.
  297. */
  298. var safe_add = function (x, y) {
  299. var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  300. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  301. return (msw << 16) | (lsw & 0xFFFF);
  302. };
  303. /*
  304. * Bitwise rotate a 32-bit number to the left.
  305. */
  306. var bit_rol = function (num, cnt) {
  307. return (num << cnt) | (num >>> (32 - cnt));
  308. };
  309. /*
  310. * Convert a string to an array of little-endian words
  311. */
  312. var str2binl = function (str) {
  313. var bin = [];
  314. for(var i = 0; i < str.length * 8; i += 8)
  315. {
  316. bin[i>>5] |= (str.charCodeAt(i / 8) & 255) << (i%32);
  317. }
  318. return bin;
  319. };
  320. /*
  321. * Convert an array of little-endian words to a string
  322. */
  323. var binl2str = function (bin) {
  324. var str = "";
  325. for(var i = 0; i < bin.length * 32; i += 8)
  326. {
  327. str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & 255);
  328. }
  329. return str;
  330. };
  331. /*
  332. * Convert an array of little-endian words to a hex string.
  333. */
  334. var binl2hex = function (binarray) {
  335. var hex_tab = "0123456789abcdef";
  336. var str = "";
  337. for(var i = 0; i < binarray.length * 4; i++)
  338. {
  339. str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
  340. hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
  341. }
  342. return str;
  343. };
  344. /*
  345. * These functions implement the four basic operations the algorithm uses.
  346. */
  347. var md5_cmn = function (q, a, b, x, s, t) {
  348. return safe_add(bit_rol(safe_add(safe_add(a, q),safe_add(x, t)), s),b);
  349. };
  350. var md5_ff = function (a, b, c, d, x, s, t) {
  351. return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
  352. };
  353. var md5_gg = function (a, b, c, d, x, s, t) {
  354. return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
  355. };
  356. var md5_hh = function (a, b, c, d, x, s, t) {
  357. return md5_cmn(b ^ c ^ d, a, b, x, s, t);
  358. };
  359. var md5_ii = function (a, b, c, d, x, s, t) {
  360. return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
  361. };
  362. /*
  363. * Calculate the MD5 of an array of little-endian words, and a bit length
  364. */
  365. var core_md5 = function (x, len) {
  366. /* append padding */
  367. x[len >> 5] |= 0x80 << ((len) % 32);
  368. x[(((len + 64) >>> 9) << 4) + 14] = len;
  369. var a = 1732584193;
  370. var b = -271733879;
  371. var c = -1732584194;
  372. var d = 271733878;
  373. var olda, oldb, oldc, oldd;
  374. for (var i = 0; i < x.length; i += 16)
  375. {
  376. olda = a;
  377. oldb = b;
  378. oldc = c;
  379. oldd = d;
  380. a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
  381. d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
  382. c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
  383. b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
  384. a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
  385. d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
  386. c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
  387. b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
  388. a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
  389. d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
  390. c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
  391. b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
  392. a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
  393. d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
  394. c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
  395. b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
  396. a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
  397. d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
  398. c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
  399. b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
  400. a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
  401. d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
  402. c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
  403. b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
  404. a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
  405. d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
  406. c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
  407. b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
  408. a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
  409. d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
  410. c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
  411. b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
  412. a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
  413. d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
  414. c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
  415. b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
  416. a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
  417. d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
  418. c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
  419. b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
  420. a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
  421. d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
  422. c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
  423. b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
  424. a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
  425. d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
  426. c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
  427. b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
  428. a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
  429. d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
  430. c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
  431. b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
  432. a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
  433. d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
  434. c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
  435. b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
  436. a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
  437. d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
  438. c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
  439. b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
  440. a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
  441. d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
  442. c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
  443. b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
  444. a = safe_add(a, olda);
  445. b = safe_add(b, oldb);
  446. c = safe_add(c, oldc);
  447. d = safe_add(d, oldd);
  448. }
  449. return [a, b, c, d];
  450. };
  451. var obj = {
  452. /*
  453. * These are the functions you'll usually want to call.
  454. * They take string arguments and return either hex or base-64 encoded
  455. * strings.
  456. */
  457. hexdigest: function (s) {
  458. return binl2hex(core_md5(str2binl(s), s.length * 8));
  459. },
  460. hash: function (s) {
  461. return binl2str(core_md5(str2binl(s), s.length * 8));
  462. }
  463. };
  464. return obj;
  465. }));
  466. /*
  467. This program is distributed under the terms of the MIT license.
  468. Please see the LICENSE file for details.
  469. Copyright 2006-2008, OGG, LLC
  470. */
  471. /* jshint undef: true, unused: true:, noarg: true, latedef: true */
  472. /** PrivateFunction: Function.prototype.bind
  473. * Bind a function to an instance.
  474. *
  475. * This Function object extension method creates a bound method similar
  476. * to those in Python. This means that the 'this' object will point
  477. * to the instance you want. See
  478. * <a href='https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind'>MDC's bind() documentation</a> and
  479. * <a href='http://benjamin.smedbergs.us/blog/2007-01-03/bound-functions-and-function-imports-in-javascript/'>Bound Functions and Function Imports in JavaScript</a>
  480. * for a complete explanation.
  481. *
  482. * This extension already exists in some browsers (namely, Firefox 3), but
  483. * we provide it to support those that don't.
  484. *
  485. * Parameters:
  486. * (Object) obj - The object that will become 'this' in the bound function.
  487. * (Object) argN - An option argument that will be prepended to the
  488. * arguments given for the function call
  489. *
  490. * Returns:
  491. * The bound function.
  492. */
  493. if (!Function.prototype.bind) {
  494. Function.prototype.bind = function (obj /*, arg1, arg2, ... */)
  495. {
  496. var func = this;
  497. var _slice = Array.prototype.slice;
  498. var _concat = Array.prototype.concat;
  499. var _args = _slice.call(arguments, 1);
  500. return function () {
  501. return func.apply(obj ? obj : this,
  502. _concat.call(_args,
  503. _slice.call(arguments, 0)));
  504. };
  505. };
  506. }
  507. /** PrivateFunction: Array.isArray
  508. * This is a polyfill for the ES5 Array.isArray method.
  509. */
  510. if (!Array.isArray) {
  511. Array.isArray = function(arg) {
  512. return Object.prototype.toString.call(arg) === '[object Array]';
  513. };
  514. }
  515. /** PrivateFunction: Array.prototype.indexOf
  516. * Return the index of an object in an array.
  517. *
  518. * This function is not supplied by some JavaScript implementations, so
  519. * we provide it if it is missing. This code is from:
  520. * http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:indexOf
  521. *
  522. * Parameters:
  523. * (Object) elt - The object to look for.
  524. * (Integer) from - The index from which to start looking. (optional).
  525. *
  526. * Returns:
  527. * The index of elt in the array or -1 if not found.
  528. */
  529. if (!Array.prototype.indexOf)
  530. {
  531. Array.prototype.indexOf = function(elt /*, from*/)
  532. {
  533. var len = this.length;
  534. var from = Number(arguments[1]) || 0;
  535. from = (from < 0) ? Math.ceil(from) : Math.floor(from);
  536. if (from < 0) {
  537. from += len;
  538. }
  539. for (; from < len; from++) {
  540. if (from in this && this[from] === elt) {
  541. return from;
  542. }
  543. }
  544. return -1;
  545. };
  546. }
  547. /*
  548. This program is distributed under the terms of the MIT license.
  549. Please see the LICENSE file for details.
  550. Copyright 2006-2008, OGG, LLC
  551. */
  552. /* jshint undef: true, unused: true:, noarg: true, latedef: true */
  553. /*global define, document, window, setTimeout, clearTimeout, console, ActiveXObject, DOMParser */
  554. (function (root, factory) {
  555. if (typeof define === 'function' && define.amd) {
  556. define('strophe-core', [
  557. 'strophe-sha1',
  558. 'strophe-base64',
  559. 'strophe-md5',
  560. "strophe-polyfill"
  561. ], function () {
  562. return factory.apply(this, arguments);
  563. });
  564. } else {
  565. // Browser globals
  566. var o = factory(root.SHA1, root.Base64, root.MD5);
  567. window.Strophe = o.Strophe;
  568. window.$build = o.$build;
  569. window.$iq = o.$iq;
  570. window.$msg = o.$msg;
  571. window.$pres = o.$pres;
  572. window.SHA1 = o.SHA1;
  573. window.Base64 = o.Base64;
  574. window.MD5 = o.MD5;
  575. window.b64_hmac_sha1 = o.SHA1.b64_hmac_sha1;
  576. window.b64_sha1 = o.SHA1.b64_sha1;
  577. window.str_hmac_sha1 = o.SHA1.str_hmac_sha1;
  578. window.str_sha1 = o.SHA1.str_sha1;
  579. }
  580. }(this, function (SHA1, Base64, MD5) {
  581. var Strophe;
  582. /** Function: $build
  583. * Create a Strophe.Builder.
  584. * This is an alias for 'new Strophe.Builder(name, attrs)'.
  585. *
  586. * Parameters:
  587. * (String) name - The root element name.
  588. * (Object) attrs - The attributes for the root element in object notation.
  589. *
  590. * Returns:
  591. * A new Strophe.Builder object.
  592. */
  593. function $build(name, attrs) { return new Strophe.Builder(name, attrs); }
  594. /** Function: $msg
  595. * Create a Strophe.Builder with a <message/> element as the root.
  596. *
  597. * Parmaeters:
  598. * (Object) attrs - The <message/> element attributes in object notation.
  599. *
  600. * Returns:
  601. * A new Strophe.Builder object.
  602. */
  603. function $msg(attrs) { return new Strophe.Builder("message", attrs); }
  604. /** Function: $iq
  605. * Create a Strophe.Builder with an <iq/> element as the root.
  606. *
  607. * Parameters:
  608. * (Object) attrs - The <iq/> element attributes in object notation.
  609. *
  610. * Returns:
  611. * A new Strophe.Builder object.
  612. */
  613. function $iq(attrs) { return new Strophe.Builder("iq", attrs); }
  614. /** Function: $pres
  615. * Create a Strophe.Builder with a <presence/> element as the root.
  616. *
  617. * Parameters:
  618. * (Object) attrs - The <presence/> element attributes in object notation.
  619. *
  620. * Returns:
  621. * A new Strophe.Builder object.
  622. */
  623. function $pres(attrs) { return new Strophe.Builder("presence", attrs); }
  624. /** Class: Strophe
  625. * An object container for all Strophe library functions.
  626. *
  627. * This class is just a container for all the objects and constants
  628. * used in the library. It is not meant to be instantiated, but to
  629. * provide a namespace for library objects, constants, and functions.
  630. */
  631. Strophe = {
  632. /** Constant: VERSION
  633. * The version of the Strophe library. Unreleased builds will have
  634. * a version of head-HASH where HASH is a partial revision.
  635. */
  636. VERSION: "1.2.2",
  637. /** Constants: XMPP Namespace Constants
  638. * Common namespace constants from the XMPP RFCs and XEPs.
  639. *
  640. * NS.HTTPBIND - HTTP BIND namespace from XEP 124.
  641. * NS.BOSH - BOSH namespace from XEP 206.
  642. * NS.CLIENT - Main XMPP client namespace.
  643. * NS.AUTH - Legacy authentication namespace.
  644. * NS.ROSTER - Roster operations namespace.
  645. * NS.PROFILE - Profile namespace.
  646. * NS.DISCO_INFO - Service discovery info namespace from XEP 30.
  647. * NS.DISCO_ITEMS - Service discovery items namespace from XEP 30.
  648. * NS.MUC - Multi-User Chat namespace from XEP 45.
  649. * NS.SASL - XMPP SASL namespace from RFC 3920.
  650. * NS.STREAM - XMPP Streams namespace from RFC 3920.
  651. * NS.BIND - XMPP Binding namespace from RFC 3920.
  652. * NS.SESSION - XMPP Session namespace from RFC 3920.
  653. * NS.XHTML_IM - XHTML-IM namespace from XEP 71.
  654. * NS.XHTML - XHTML body namespace from XEP 71.
  655. */
  656. NS: {
  657. HTTPBIND: "http://jabber.org/protocol/httpbind",
  658. BOSH: "urn:xmpp:xbosh",
  659. CLIENT: "jabber:client",
  660. AUTH: "jabber:iq:auth",
  661. ROSTER: "jabber:iq:roster",
  662. PROFILE: "jabber:iq:profile",
  663. DISCO_INFO: "http://jabber.org/protocol/disco#info",
  664. DISCO_ITEMS: "http://jabber.org/protocol/disco#items",
  665. MUC: "http://jabber.org/protocol/muc",
  666. SASL: "urn:ietf:params:xml:ns:xmpp-sasl",
  667. STREAM: "http://etherx.jabber.org/streams",
  668. FRAMING: "urn:ietf:params:xml:ns:xmpp-framing",
  669. BIND: "urn:ietf:params:xml:ns:xmpp-bind",
  670. SESSION: "urn:ietf:params:xml:ns:xmpp-session",
  671. VERSION: "jabber:iq:version",
  672. STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas",
  673. XHTML_IM: "http://jabber.org/protocol/xhtml-im",
  674. XHTML: "http://www.w3.org/1999/xhtml"
  675. },
  676. /** Constants: XHTML_IM Namespace
  677. * contains allowed tags, tag attributes, and css properties.
  678. * Used in the createHtml function to filter incoming html into the allowed XHTML-IM subset.
  679. * See http://xmpp.org/extensions/xep-0071.html#profile-summary for the list of recommended
  680. * allowed tags and their attributes.
  681. */
  682. XHTML: {
  683. tags: ['a','blockquote','br','cite','em','img','li','ol','p','span','strong','ul','body'],
  684. attributes: {
  685. 'a': ['href'],
  686. 'blockquote': ['style'],
  687. 'br': [],
  688. 'cite': ['style'],
  689. 'em': [],
  690. 'img': ['src', 'alt', 'style', 'height', 'width'],
  691. 'li': ['style'],
  692. 'ol': ['style'],
  693. 'p': ['style'],
  694. 'span': ['style'],
  695. 'strong': [],
  696. 'ul': ['style'],
  697. 'body': []
  698. },
  699. css: ['background-color','color','font-family','font-size','font-style','font-weight','margin-left','margin-right','text-align','text-decoration'],
  700. /** Function: XHTML.validTag
  701. *
  702. * Utility method to determine whether a tag is allowed
  703. * in the XHTML_IM namespace.
  704. *
  705. * XHTML tag names are case sensitive and must be lower case.
  706. */
  707. validTag: function(tag) {
  708. for (var i = 0; i < Strophe.XHTML.tags.length; i++) {
  709. if (tag == Strophe.XHTML.tags[i]) {
  710. return true;
  711. }
  712. }
  713. return false;
  714. },
  715. /** Function: XHTML.validAttribute
  716. *
  717. * Utility method to determine whether an attribute is allowed
  718. * as recommended per XEP-0071
  719. *
  720. * XHTML attribute names are case sensitive and must be lower case.
  721. */
  722. validAttribute: function(tag, attribute) {
  723. if(typeof Strophe.XHTML.attributes[tag] !== 'undefined' && Strophe.XHTML.attributes[tag].length > 0) {
  724. for(var i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
  725. if(attribute == Strophe.XHTML.attributes[tag][i]) {
  726. return true;
  727. }
  728. }
  729. }
  730. return false;
  731. },
  732. validCSS: function(style)
  733. {
  734. for(var i = 0; i < Strophe.XHTML.css.length; i++) {
  735. if(style == Strophe.XHTML.css[i]) {
  736. return true;
  737. }
  738. }
  739. return false;
  740. }
  741. },
  742. /** Constants: Connection Status Constants
  743. * Connection status constants for use by the connection handler
  744. * callback.
  745. *
  746. * Status.ERROR - An error has occurred
  747. * Status.CONNECTING - The connection is currently being made
  748. * Status.CONNFAIL - The connection attempt failed
  749. * Status.AUTHENTICATING - The connection is authenticating
  750. * Status.AUTHFAIL - The authentication attempt failed
  751. * Status.CONNECTED - The connection has succeeded
  752. * Status.DISCONNECTED - The connection has been terminated
  753. * Status.DISCONNECTING - The connection is currently being terminated
  754. * Status.ATTACHED - The connection has been attached
  755. */
  756. Status: {
  757. ERROR: 0,
  758. CONNECTING: 1,
  759. CONNFAIL: 2,
  760. AUTHENTICATING: 3,
  761. AUTHFAIL: 4,
  762. CONNECTED: 5,
  763. DISCONNECTED: 6,
  764. DISCONNECTING: 7,
  765. ATTACHED: 8,
  766. REDIRECT: 9
  767. },
  768. /** Constants: Log Level Constants
  769. * Logging level indicators.
  770. *
  771. * LogLevel.DEBUG - Debug output
  772. * LogLevel.INFO - Informational output
  773. * LogLevel.WARN - Warnings
  774. * LogLevel.ERROR - Errors
  775. * LogLevel.FATAL - Fatal errors
  776. */
  777. LogLevel: {
  778. DEBUG: 0,
  779. INFO: 1,
  780. WARN: 2,
  781. ERROR: 3,
  782. FATAL: 4
  783. },
  784. /** PrivateConstants: DOM Element Type Constants
  785. * DOM element types.
  786. *
  787. * ElementType.NORMAL - Normal element.
  788. * ElementType.TEXT - Text data element.
  789. * ElementType.FRAGMENT - XHTML fragment element.
  790. */
  791. ElementType: {
  792. NORMAL: 1,
  793. TEXT: 3,
  794. CDATA: 4,
  795. FRAGMENT: 11
  796. },
  797. /** PrivateConstants: Timeout Values
  798. * Timeout values for error states. These values are in seconds.
  799. * These should not be changed unless you know exactly what you are
  800. * doing.
  801. *
  802. * TIMEOUT - Timeout multiplier. A waiting request will be considered
  803. * failed after Math.floor(TIMEOUT * wait) seconds have elapsed.
  804. * This defaults to 1.1, and with default wait, 66 seconds.
  805. * SECONDARY_TIMEOUT - Secondary timeout multiplier. In cases where
  806. * Strophe can detect early failure, it will consider the request
  807. * failed if it doesn't return after
  808. * Math.floor(SECONDARY_TIMEOUT * wait) seconds have elapsed.
  809. * This defaults to 0.1, and with default wait, 6 seconds.
  810. */
  811. TIMEOUT: 1.1,
  812. SECONDARY_TIMEOUT: 0.1,
  813. /** Function: addNamespace
  814. * This function is used to extend the current namespaces in
  815. * Strophe.NS. It takes a key and a value with the key being the
  816. * name of the new namespace, with its actual value.
  817. * For example:
  818. * Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub");
  819. *
  820. * Parameters:
  821. * (String) name - The name under which the namespace will be
  822. * referenced under Strophe.NS
  823. * (String) value - The actual namespace.
  824. */
  825. addNamespace: function (name, value)
  826. {
  827. Strophe.NS[name] = value;
  828. },
  829. /** Function: forEachChild
  830. * Map a function over some or all child elements of a given element.
  831. *
  832. * This is a small convenience function for mapping a function over
  833. * some or all of the children of an element. If elemName is null, all
  834. * children will be passed to the function, otherwise only children
  835. * whose tag names match elemName will be passed.
  836. *
  837. * Parameters:
  838. * (XMLElement) elem - The element to operate on.
  839. * (String) elemName - The child element tag name filter.
  840. * (Function) func - The function to apply to each child. This
  841. * function should take a single argument, a DOM element.
  842. */
  843. forEachChild: function (elem, elemName, func)
  844. {
  845. var i, childNode;
  846. for (i = 0; i < elem.childNodes.length; i++) {
  847. childNode = elem.childNodes[i];
  848. if (childNode.nodeType == Strophe.ElementType.NORMAL &&
  849. (!elemName || this.isTagEqual(childNode, elemName))) {
  850. func(childNode);
  851. }
  852. }
  853. },
  854. /** Function: isTagEqual
  855. * Compare an element's tag name with a string.
  856. *
  857. * This function is case sensitive.
  858. *
  859. * Parameters:
  860. * (XMLElement) el - A DOM element.
  861. * (String) name - The element name.
  862. *
  863. * Returns:
  864. * true if the element's tag name matches _el_, and false
  865. * otherwise.
  866. */
  867. isTagEqual: function (el, name)
  868. {
  869. return el.tagName == name;
  870. },
  871. /** PrivateVariable: _xmlGenerator
  872. * _Private_ variable that caches a DOM document to
  873. * generate elements.
  874. */
  875. _xmlGenerator: null,
  876. /** PrivateFunction: _makeGenerator
  877. * _Private_ function that creates a dummy XML DOM document to serve as
  878. * an element and text node generator.
  879. */
  880. _makeGenerator: function () {
  881. var doc;
  882. // IE9 does implement createDocument(); however, using it will cause the browser to leak memory on page unload.
  883. // Here, we test for presence of createDocument() plus IE's proprietary documentMode attribute, which would be
  884. // less than 10 in the case of IE9 and below.
  885. if (document.implementation.createDocument === undefined ||
  886. document.implementation.createDocument && document.documentMode && document.documentMode < 10) {
  887. doc = this._getIEXmlDom();
  888. doc.appendChild(doc.createElement('strophe'));
  889. } else {
  890. doc = document.implementation
  891. .createDocument('jabber:client', 'strophe', null);
  892. }
  893. return doc;
  894. },
  895. /** Function: xmlGenerator
  896. * Get the DOM document to generate elements.
  897. *
  898. * Returns:
  899. * The currently used DOM document.
  900. */
  901. xmlGenerator: function () {
  902. if (!Strophe._xmlGenerator) {
  903. Strophe._xmlGenerator = Strophe._makeGenerator();
  904. }
  905. return Strophe._xmlGenerator;
  906. },
  907. /** PrivateFunction: _getIEXmlDom
  908. * Gets IE xml doc object
  909. *
  910. * Returns:
  911. * A Microsoft XML DOM Object
  912. * See Also:
  913. * http://msdn.microsoft.com/en-us/library/ms757837%28VS.85%29.aspx
  914. */
  915. _getIEXmlDom : function() {
  916. var doc = null;
  917. var docStrings = [
  918. "Msxml2.DOMDocument.6.0",
  919. "Msxml2.DOMDocument.5.0",
  920. "Msxml2.DOMDocument.4.0",
  921. "MSXML2.DOMDocument.3.0",
  922. "MSXML2.DOMDocument",
  923. "MSXML.DOMDocument",
  924. "Microsoft.XMLDOM"
  925. ];
  926. for (var d = 0; d < docStrings.length; d++) {
  927. if (doc === null) {
  928. try {
  929. doc = new ActiveXObject(docStrings[d]);
  930. } catch (e) {
  931. doc = null;
  932. }
  933. } else {
  934. break;
  935. }
  936. }
  937. return doc;
  938. },
  939. /** Function: xmlElement
  940. * Create an XML DOM element.
  941. *
  942. * This function creates an XML DOM element correctly across all
  943. * implementations. Note that these are not HTML DOM elements, which
  944. * aren't appropriate for XMPP stanzas.
  945. *
  946. * Parameters:
  947. * (String) name - The name for the element.
  948. * (Array|Object) attrs - An optional array or object containing
  949. * key/value pairs to use as element attributes. The object should
  950. * be in the format {'key': 'value'} or {key: 'value'}. The array
  951. * should have the format [['key1', 'value1'], ['key2', 'value2']].
  952. * (String) text - The text child data for the element.
  953. *
  954. * Returns:
  955. * A new XML DOM element.
  956. */
  957. xmlElement: function (name)
  958. {
  959. if (!name) { return null; }
  960. var node = Strophe.xmlGenerator().createElement(name);
  961. // FIXME: this should throw errors if args are the wrong type or
  962. // there are more than two optional args
  963. var a, i, k;
  964. for (a = 1; a < arguments.length; a++) {
  965. var arg = arguments[a];
  966. if (!arg) { continue; }
  967. if (typeof(arg) == "string" ||
  968. typeof(arg) == "number") {
  969. node.appendChild(Strophe.xmlTextNode(arg));
  970. } else if (typeof(arg) == "object" &&
  971. typeof(arg.sort) == "function") {
  972. for (i = 0; i < arg.length; i++) {
  973. var attr = arg[i];
  974. if (typeof(attr) == "object" &&
  975. typeof(attr.sort) == "function" &&
  976. attr[1] !== undefined) {
  977. node.setAttribute(attr[0], attr[1]);
  978. }
  979. }
  980. } else if (typeof(arg) == "object") {
  981. for (k in arg) {
  982. if (arg.hasOwnProperty(k)) {
  983. if (arg[k] !== undefined) {
  984. node.setAttribute(k, arg[k]);
  985. }
  986. }
  987. }
  988. }
  989. }
  990. return node;
  991. },
  992. /* Function: xmlescape
  993. * Excapes invalid xml characters.
  994. *
  995. * Parameters:
  996. * (String) text - text to escape.
  997. *
  998. * Returns:
  999. * Escaped text.
  1000. */
  1001. xmlescape: function(text)
  1002. {
  1003. text = text.replace(/\&/g, "&amp;");
  1004. text = text.replace(/</g, "&lt;");
  1005. text = text.replace(/>/g, "&gt;");
  1006. text = text.replace(/'/g, "&apos;");
  1007. text = text.replace(/"/g, "&quot;");
  1008. return text;
  1009. },
  1010. /* Function: xmlunescape
  1011. * Unexcapes invalid xml characters.
  1012. *
  1013. * Parameters:
  1014. * (String) text - text to unescape.
  1015. *
  1016. * Returns:
  1017. * Unescaped text.
  1018. */
  1019. xmlunescape: function(text)
  1020. {
  1021. text = text.replace(/\&amp;/g, "&");
  1022. text = text.replace(/&lt;/g, "<");
  1023. text = text.replace(/&gt;/g, ">");
  1024. text = text.replace(/&apos;/g, "'");
  1025. text = text.replace(/&quot;/g, "\"");
  1026. return text;
  1027. },
  1028. /** Function: xmlTextNode
  1029. * Creates an XML DOM text node.
  1030. *
  1031. * Provides a cross implementation version of document.createTextNode.
  1032. *
  1033. * Parameters:
  1034. * (String) text - The content of the text node.
  1035. *
  1036. * Returns:
  1037. * A new XML DOM text node.
  1038. */
  1039. xmlTextNode: function (text)
  1040. {
  1041. return Strophe.xmlGenerator().createTextNode(text);
  1042. },
  1043. /** Function: xmlHtmlNode
  1044. * Creates an XML DOM html node.
  1045. *
  1046. * Parameters:
  1047. * (String) html - The content of the html node.
  1048. *
  1049. * Returns:
  1050. * A new XML DOM text node.
  1051. */
  1052. xmlHtmlNode: function (html)
  1053. {
  1054. var node;
  1055. //ensure text is escaped
  1056. if (window.DOMParser) {
  1057. var parser = new DOMParser();
  1058. node = parser.parseFromString(html, "text/xml");
  1059. } else {
  1060. node = new ActiveXObject("Microsoft.XMLDOM");
  1061. node.async="false";
  1062. node.loadXML(html);
  1063. }
  1064. return node;
  1065. },
  1066. /** Function: getText
  1067. * Get the concatenation of all text children of an element.
  1068. *
  1069. * Parameters:
  1070. * (XMLElement) elem - A DOM element.
  1071. *
  1072. * Returns:
  1073. * A String with the concatenated text of all text element children.
  1074. */
  1075. getText: function (elem)
  1076. {
  1077. if (!elem) { return null; }
  1078. var str = "";
  1079. if (elem.childNodes.length === 0 && elem.nodeType ==
  1080. Strophe.ElementType.TEXT) {
  1081. str += elem.nodeValue;
  1082. }
  1083. for (var i = 0; i < elem.childNodes.length; i++) {
  1084. if (elem.childNodes[i].nodeType == Strophe.ElementType.TEXT) {
  1085. str += elem.childNodes[i].nodeValue;
  1086. }
  1087. }
  1088. return Strophe.xmlescape(str);
  1089. },
  1090. /** Function: copyElement
  1091. * Copy an XML DOM element.
  1092. *
  1093. * This function copies a DOM element and all its descendants and returns
  1094. * the new copy.
  1095. *
  1096. * Parameters:
  1097. * (XMLElement) elem - A DOM element.
  1098. *
  1099. * Returns:
  1100. * A new, copied DOM element tree.
  1101. */
  1102. copyElement: function (elem)
  1103. {
  1104. var i, el;
  1105. if (elem.nodeType == Strophe.ElementType.NORMAL) {
  1106. el = Strophe.xmlElement(elem.tagName);
  1107. for (i = 0; i < elem.attributes.length; i++) {
  1108. el.setAttribute(elem.attributes[i].nodeName,
  1109. elem.attributes[i].value);
  1110. }
  1111. for (i = 0; i < elem.childNodes.length; i++) {
  1112. el.appendChild(Strophe.copyElement(elem.childNodes[i]));
  1113. }
  1114. } else if (elem.nodeType == Strophe.ElementType.TEXT) {
  1115. el = Strophe.xmlGenerator().createTextNode(elem.nodeValue);
  1116. }
  1117. return el;
  1118. },
  1119. /** Function: createHtml
  1120. * Copy an HTML DOM element into an XML DOM.
  1121. *
  1122. * This function copies a DOM element and all its descendants and returns
  1123. * the new copy.
  1124. *
  1125. * Parameters:
  1126. * (HTMLElement) elem - A DOM element.
  1127. *
  1128. * Returns:
  1129. * A new, copied DOM element tree.
  1130. */
  1131. createHtml: function (elem)
  1132. {
  1133. var i, el, j, tag, attribute, value, css, cssAttrs, attr, cssName, cssValue;
  1134. if (elem.nodeType == Strophe.ElementType.NORMAL) {
  1135. tag = elem.nodeName.toLowerCase(); // XHTML tags must be lower case.
  1136. if(Strophe.XHTML.validTag(tag)) {
  1137. try {
  1138. el = Strophe.xmlElement(tag);
  1139. for(i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
  1140. attribute = Strophe.XHTML.attributes[tag][i];
  1141. value = elem.getAttribute(attribute);
  1142. if(typeof value == 'undefined' || value === null || value === '' || value === false || value === 0) {
  1143. continue;
  1144. }
  1145. if(attribute == 'style' && typeof value == 'object') {
  1146. if(typeof value.cssText != 'undefined') {
  1147. value = value.cssText; // we're dealing with IE, need to get CSS out
  1148. }
  1149. }
  1150. // filter out invalid css styles
  1151. if(attribute == 'style') {
  1152. css = [];
  1153. cssAttrs = value.split(';');
  1154. for(j = 0; j < cssAttrs.length; j++) {
  1155. attr = cssAttrs[j].split(':');
  1156. cssName = attr[0].replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase();
  1157. if(Strophe.XHTML.validCSS(cssName)) {
  1158. cssValue = attr[1].replace(/^\s*/, "").replace(/\s*$/, "");
  1159. css.push(cssName + ': ' + cssValue);
  1160. }
  1161. }
  1162. if(css.length > 0) {
  1163. value = css.join('; ');
  1164. el.setAttribute(attribute, value);
  1165. }
  1166. } else {
  1167. el.setAttribute(attribute, value);
  1168. }
  1169. }
  1170. for (i = 0; i < elem.childNodes.length; i++) {
  1171. el.appendChild(Strophe.createHtml(elem.childNodes[i]));
  1172. }
  1173. } catch(e) { // invalid elements
  1174. el = Strophe.xmlTextNode('');
  1175. }
  1176. } else {
  1177. el = Strophe.xmlGenerator().createDocumentFragment();
  1178. for (i = 0; i < elem.childNodes.length; i++) {
  1179. el.appendChild(Strophe.createHtml(elem.childNodes[i]));
  1180. }
  1181. }
  1182. } else if (elem.nodeType == Strophe.ElementType.FRAGMENT) {
  1183. el = Strophe.xmlGenerator().createDocumentFragment();
  1184. for (i = 0; i < elem.childNodes.length; i++) {
  1185. el.appendChild(Strophe.createHtml(elem.childNodes[i]));
  1186. }
  1187. } else if (elem.nodeType == Strophe.ElementType.TEXT) {
  1188. el = Strophe.xmlTextNode(elem.nodeValue);
  1189. }
  1190. return el;
  1191. },
  1192. /** Function: escapeNode
  1193. * Escape the node part (also called local part) of a JID.
  1194. *
  1195. * Parameters:
  1196. * (String) node - A node (or local part).
  1197. *
  1198. * Returns:
  1199. * An escaped node (or local part).
  1200. */
  1201. escapeNode: function (node)
  1202. {
  1203. if (typeof node !== "string") { return node; }
  1204. return node.replace(/^\s+|\s+$/g, '')
  1205. .replace(/\\/g, "\\5c")
  1206. .replace(/ /g, "\\20")
  1207. .replace(/\"/g, "\\22")
  1208. .replace(/\&/g, "\\26")
  1209. .replace(/\'/g, "\\27")
  1210. .replace(/\//g, "\\2f")
  1211. .replace(/:/g, "\\3a")
  1212. .replace(/</g, "\\3c")
  1213. .replace(/>/g, "\\3e")
  1214. .replace(/@/g, "\\40");
  1215. },
  1216. /** Function: unescapeNode
  1217. * Unescape a node part (also called local part) of a JID.
  1218. *
  1219. * Parameters:
  1220. * (String) node - A node (or local part).
  1221. *
  1222. * Returns:
  1223. * An unescaped node (or local part).
  1224. */
  1225. unescapeNode: function (node)
  1226. {
  1227. if (typeof node !== "string") { return node; }
  1228. return node.replace(/\\20/g, " ")
  1229. .replace(/\\22/g, '"')
  1230. .replace(/\\26/g, "&")
  1231. .replace(/\\27/g, "'")
  1232. .replace(/\\2f/g, "/")
  1233. .replace(/\\3a/g, ":")
  1234. .replace(/\\3c/g, "<")
  1235. .replace(/\\3e/g, ">")
  1236. .replace(/\\40/g, "@")
  1237. .replace(/\\5c/g, "\\");
  1238. },
  1239. /** Function: getNodeFromJid
  1240. * Get the node portion of a JID String.
  1241. *
  1242. * Parameters:
  1243. * (String) jid - A JID.
  1244. *
  1245. * Returns:
  1246. * A String containing the node.
  1247. */
  1248. getNodeFromJid: function (jid)
  1249. {
  1250. if (jid.indexOf("@") < 0) { return null; }
  1251. return jid.split("@")[0];
  1252. },
  1253. /** Function: getDomainFromJid
  1254. * Get the domain portion of a JID String.
  1255. *
  1256. * Parameters:
  1257. * (String) jid - A JID.
  1258. *
  1259. * Returns:
  1260. * A String containing the domain.
  1261. */
  1262. getDomainFromJid: function (jid)
  1263. {
  1264. var bare = Strophe.getBareJidFromJid(jid);
  1265. if (bare.indexOf("@") < 0) {
  1266. return bare;
  1267. } else {
  1268. var parts = bare.split("@");
  1269. parts.splice(0, 1);
  1270. return parts.join('@');
  1271. }
  1272. },
  1273. /** Function: getResourceFromJid
  1274. * Get the resource portion of a JID String.
  1275. *
  1276. * Parameters:
  1277. * (String) jid - A JID.
  1278. *
  1279. * Returns:
  1280. * A String containing the resource.
  1281. */
  1282. getResourceFromJid: function (jid)
  1283. {
  1284. var s = jid.split("/");
  1285. if (s.length < 2) { return null; }
  1286. s.splice(0, 1);
  1287. return s.join('/');
  1288. },
  1289. /** Function: getBareJidFromJid
  1290. * Get the bare JID from a JID String.
  1291. *
  1292. * Parameters:
  1293. * (String) jid - A JID.
  1294. *
  1295. * Returns:
  1296. * A String containing the bare JID.
  1297. */
  1298. getBareJidFromJid: function (jid)
  1299. {
  1300. return jid ? jid.split("/")[0] : null;
  1301. },
  1302. /** Function: log
  1303. * User overrideable logging function.
  1304. *
  1305. * This function is called whenever the Strophe library calls any
  1306. * of the logging functions. The default implementation of this
  1307. * function does nothing. If client code wishes to handle the logging
  1308. * messages, it should override this with
  1309. * > Strophe.log = function (level, msg) {
  1310. * > (user code here)
  1311. * > };
  1312. *
  1313. * Please note that data sent and received over the wire is logged
  1314. * via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput().
  1315. *
  1316. * The different levels and their meanings are
  1317. *
  1318. * DEBUG - Messages useful for debugging purposes.
  1319. * INFO - Informational messages. This is mostly information like
  1320. * 'disconnect was called' or 'SASL auth succeeded'.
  1321. * WARN - Warnings about potential problems. This is mostly used
  1322. * to report transient connection errors like request timeouts.
  1323. * ERROR - Some error occurred.
  1324. * FATAL - A non-recoverable fatal error occurred.
  1325. *
  1326. * Parameters:
  1327. * (Integer) level - The log level of the log message. This will
  1328. * be one of the values in Strophe.LogLevel.
  1329. * (String) msg - The log message.
  1330. */
  1331. /* jshint ignore:start */
  1332. log: function (level, msg)
  1333. {
  1334. return;
  1335. },
  1336. /* jshint ignore:end */
  1337. /** Function: debug
  1338. * Log a message at the Strophe.LogLevel.DEBUG level.
  1339. *
  1340. * Parameters:
  1341. * (String) msg - The log message.
  1342. */
  1343. debug: function(msg)
  1344. {
  1345. this.log(this.LogLevel.DEBUG, msg);
  1346. },
  1347. /** Function: info
  1348. * Log a message at the Strophe.LogLevel.INFO level.
  1349. *
  1350. * Parameters:
  1351. * (String) msg - The log message.
  1352. */
  1353. info: function (msg)
  1354. {
  1355. this.log(this.LogLevel.INFO, msg);
  1356. },
  1357. /** Function: warn
  1358. * Log a message at the Strophe.LogLevel.WARN level.
  1359. *
  1360. * Parameters:
  1361. * (String) msg - The log message.
  1362. */
  1363. warn: function (msg)
  1364. {
  1365. this.log(this.LogLevel.WARN, msg);
  1366. },
  1367. /** Function: error
  1368. * Log a message at the Strophe.LogLevel.ERROR level.
  1369. *
  1370. * Parameters:
  1371. * (String) msg - The log message.
  1372. */
  1373. error: function (msg)
  1374. {
  1375. this.log(this.LogLevel.ERROR, msg);
  1376. },
  1377. /** Function: fatal
  1378. * Log a message at the Strophe.LogLevel.FATAL level.
  1379. *
  1380. * Parameters:
  1381. * (String) msg - The log message.
  1382. */
  1383. fatal: function (msg)
  1384. {
  1385. this.log(this.LogLevel.FATAL, msg);
  1386. },
  1387. /** Function: serialize
  1388. * Render a DOM element and all descendants to a String.
  1389. *
  1390. * Parameters:
  1391. * (XMLElement) elem - A DOM element.
  1392. *
  1393. * Returns:
  1394. * The serialized element tree as a String.
  1395. */
  1396. serialize: function (elem)
  1397. {
  1398. var result;
  1399. if (!elem) { return null; }
  1400. if (typeof(elem.tree) === "function") {
  1401. elem = elem.tree();
  1402. }
  1403. var nodeName = elem.nodeName;
  1404. var i, child;
  1405. if (elem.getAttribute("_realname")) {
  1406. nodeName = elem.getAttribute("_realname");
  1407. }
  1408. result = "<" + nodeName;
  1409. for (i = 0; i < elem.attributes.length; i++) {
  1410. if(elem.attributes[i].nodeName != "_realname") {
  1411. result += " " + elem.attributes[i].nodeName +
  1412. "='" + elem.attributes[i].value
  1413. .replace(/&/g, "&amp;")
  1414. .replace(/\'/g, "&apos;")
  1415. .replace(/>/g, "&gt;")
  1416. .replace(/</g, "&lt;") + "'";
  1417. }
  1418. }
  1419. if (elem.childNodes.length > 0) {
  1420. result += ">";
  1421. for (i = 0; i < elem.childNodes.length; i++) {
  1422. child = elem.childNodes[i];
  1423. switch( child.nodeType ){
  1424. case Strophe.ElementType.NORMAL:
  1425. // normal element, so recurse
  1426. result += Strophe.serialize(child);
  1427. break;
  1428. case Strophe.ElementType.TEXT:
  1429. // text element to escape values
  1430. result += Strophe.xmlescape(child.nodeValue);
  1431. break;
  1432. case Strophe.ElementType.CDATA:
  1433. // cdata section so don't escape values
  1434. result += "<![CDATA["+child.nodeValue+"]]>";
  1435. }
  1436. }
  1437. result += "</" + nodeName + ">";
  1438. } else {
  1439. result += "/>";
  1440. }
  1441. return result;
  1442. },
  1443. /** PrivateVariable: _requestId
  1444. * _Private_ variable that keeps track of the request ids for
  1445. * connections.
  1446. */
  1447. _requestId: 0,
  1448. /** PrivateVariable: Strophe.connectionPlugins
  1449. * _Private_ variable Used to store plugin names that need
  1450. * initialization on Strophe.Connection construction.
  1451. */
  1452. _connectionPlugins: {},
  1453. /** Function: addConnectionPlugin
  1454. * Extends the Strophe.Connection object with the given plugin.
  1455. *
  1456. * Parameters:
  1457. * (String) name - The name of the extension.
  1458. * (Object) ptype - The plugin's prototype.
  1459. */
  1460. addConnectionPlugin: function (name, ptype)
  1461. {
  1462. Strophe._connectionPlugins[name] = ptype;
  1463. }
  1464. };
  1465. /** Class: Strophe.Builder
  1466. * XML DOM builder.
  1467. *
  1468. * This object provides an interface similar to JQuery but for building
  1469. * DOM element easily and rapidly. All the functions except for toString()
  1470. * and tree() return the object, so calls can be chained. Here's an
  1471. * example using the $iq() builder helper.
  1472. * > $iq({to: 'you', from: 'me', type: 'get', id: '1'})
  1473. * > .c('query', {xmlns: 'strophe:example'})
  1474. * > .c('example')
  1475. * > .toString()
  1476. * The above generates this XML fragment
  1477. * > <iq to='you' from='me' type='get' id='1'>
  1478. * > <query xmlns='strophe:example'>
  1479. * > <example/>
  1480. * > </query>
  1481. * > </iq>
  1482. * The corresponding DOM manipulations to get a similar fragment would be
  1483. * a lot more tedious and probably involve several helper variables.
  1484. *
  1485. * Since adding children makes new operations operate on the child, up()
  1486. * is provided to traverse up the tree. To add two children, do
  1487. * > builder.c('child1', ...).up().c('child2', ...)
  1488. * The next operation on the Builder will be relative to the second child.
  1489. */
  1490. /** Constructor: Strophe.Builder
  1491. * Create a Strophe.Builder object.
  1492. *
  1493. * The attributes should be passed in object notation. For example
  1494. * > var b = new Builder('message', {to: 'you', from: 'me'});
  1495. * or
  1496. * > var b = new Builder('messsage', {'xml:lang': 'en'});
  1497. *
  1498. * Parameters:
  1499. * (String) name - The name of the root element.
  1500. * (Object) attrs - The attributes for the root element in object notation.
  1501. *
  1502. * Returns:
  1503. * A new Strophe.Builder.
  1504. */
  1505. Strophe.Builder = function (name, attrs)
  1506. {
  1507. // Set correct namespace for jabber:client elements
  1508. if (name == "presence" || name == "message" || name == "iq") {
  1509. if (attrs && !attrs.xmlns) {
  1510. attrs.xmlns = Strophe.NS.CLIENT;
  1511. } else if (!attrs) {
  1512. attrs = {xmlns: Strophe.NS.CLIENT};
  1513. }
  1514. }
  1515. // Holds the tree being built.
  1516. this.nodeTree = Strophe.xmlElement(name, attrs);
  1517. // Points to the current operation node.
  1518. this.node = this.nodeTree;
  1519. };
  1520. Strophe.Builder.prototype = {
  1521. /** Function: tree
  1522. * Return the DOM tree.
  1523. *
  1524. * This function returns the current DOM tree as an element object. This
  1525. * is suitable for passing to functions like Strophe.Connection.send().
  1526. *
  1527. * Returns:
  1528. * The DOM tree as a element object.
  1529. */
  1530. tree: function ()
  1531. {
  1532. return this.nodeTree;
  1533. },
  1534. /** Function: toString
  1535. * Serialize the DOM tree to a String.
  1536. *
  1537. * This function returns a string serialization of the current DOM
  1538. * tree. It is often used internally to pass data to a
  1539. * Strophe.Request object.
  1540. *
  1541. * Returns:
  1542. * The serialized DOM tree in a String.
  1543. */
  1544. toString: function ()
  1545. {
  1546. return Strophe.serialize(this.nodeTree);
  1547. },
  1548. /** Function: up
  1549. * Make the current parent element the new current element.
  1550. *
  1551. * This function is often used after c() to traverse back up the tree.
  1552. * For example, to add two children to the same element
  1553. * > builder.c('child1', {}).up().c('child2', {});
  1554. *
  1555. * Returns:
  1556. * The Stophe.Builder object.
  1557. */
  1558. up: function ()
  1559. {
  1560. this.node = this.node.parentNode;
  1561. return this;
  1562. },
  1563. /** Function: attrs
  1564. * Add or modify attributes of the current element.
  1565. *
  1566. * The attributes should be passed in object notation. This function
  1567. * does not move the current element pointer.
  1568. *
  1569. * Parameters:
  1570. * (Object) moreattrs - The attributes to add/modify in object notation.
  1571. *
  1572. * Returns:
  1573. * The Strophe.Builder object.
  1574. */
  1575. attrs: function (moreattrs)
  1576. {
  1577. for (var k in moreattrs) {
  1578. if (moreattrs.hasOwnProperty(k)) {
  1579. if (moreattrs[k] === undefined) {
  1580. this.node.removeAttribute(k);
  1581. } else {
  1582. this.node.setAttribute(k, moreattrs[k]);
  1583. }
  1584. }
  1585. }
  1586. return this;
  1587. },
  1588. /** Function: c
  1589. * Add a child to the current element and make it the new current
  1590. * element.
  1591. *
  1592. * This function moves the current element pointer to the child,
  1593. * unless text is provided. If you need to add another child, it
  1594. * is necessary to use up() to go back to the parent in the tree.
  1595. *
  1596. * Parameters:
  1597. * (String) name - The name of the child.
  1598. * (Object) attrs - The attributes of the child in object notation.
  1599. * (String) text - The text to add to the child.
  1600. *
  1601. * Returns:
  1602. * The Strophe.Builder object.
  1603. */
  1604. c: function (name, attrs, text)
  1605. {
  1606. var child = Strophe.xmlElement(name, attrs, text);
  1607. this.node.appendChild(child);
  1608. if (typeof text !== "string") {
  1609. this.node = child;
  1610. }
  1611. return this;
  1612. },
  1613. /** Function: cnode
  1614. * Add a child to the current element and make it the new current
  1615. * element.
  1616. *
  1617. * This function is the same as c() except that instead of using a
  1618. * name and an attributes object to create the child it uses an
  1619. * existing DOM element object.
  1620. *
  1621. * Parameters:
  1622. * (XMLElement) elem - A DOM element.
  1623. *
  1624. * Returns:
  1625. * The Strophe.Builder object.
  1626. */
  1627. cnode: function (elem)
  1628. {
  1629. var impNode;
  1630. var xmlGen = Strophe.xmlGenerator();
  1631. try {
  1632. impNode = (xmlGen.importNode !== undefined);
  1633. }
  1634. catch (e) {
  1635. impNode = false;
  1636. }
  1637. var newElem = impNode ?
  1638. xmlGen.importNode(elem, true) :
  1639. Strophe.copyElement(elem);
  1640. this.node.appendChild(newElem);
  1641. this.node = newElem;
  1642. return this;
  1643. },
  1644. /** Function: t
  1645. * Add a child text element.
  1646. *
  1647. * This *does not* make the child the new current element since there
  1648. * are no children of text elements.
  1649. *
  1650. * Parameters:
  1651. * (String) text - The text data to append to the current element.
  1652. *
  1653. * Returns:
  1654. * The Strophe.Builder object.
  1655. */
  1656. t: function (text)
  1657. {
  1658. var child = Strophe.xmlTextNode(text);
  1659. this.node.appendChild(child);
  1660. return this;
  1661. },
  1662. /** Function: h
  1663. * Replace current element contents with the HTML passed in.
  1664. *
  1665. * This *does not* make the child the new current element
  1666. *
  1667. * Parameters:
  1668. * (String) html - The html to insert as contents of current element.
  1669. *
  1670. * Returns:
  1671. * The Strophe.Builder object.
  1672. */
  1673. h: function (html)
  1674. {
  1675. var fragment = document.createElement('body');
  1676. // force the browser to try and fix any invalid HTML tags
  1677. fragment.innerHTML = html;
  1678. // copy cleaned html into an xml dom
  1679. var xhtml = Strophe.createHtml(fragment);
  1680. while(xhtml.childNodes.length > 0) {
  1681. this.node.appendChild(xhtml.childNodes[0]);
  1682. }
  1683. return this;
  1684. }
  1685. };
  1686. /** PrivateClass: Strophe.Handler
  1687. * _Private_ helper class for managing stanza handlers.
  1688. *
  1689. * A Strophe.Handler encapsulates a user provided callback function to be
  1690. * executed when matching stanzas are received by the connection.
  1691. * Handlers can be either one-off or persistant depending on their
  1692. * return value. Returning true will cause a Handler to remain active, and
  1693. * returning false will remove the Handler.
  1694. *
  1695. * Users will not use Strophe.Handler objects directly, but instead they
  1696. * will use Strophe.Connection.addHandler() and
  1697. * Strophe.Connection.deleteHandler().
  1698. */
  1699. /** PrivateConstructor: Strophe.Handler
  1700. * Create and initialize a new Strophe.Handler.
  1701. *
  1702. * Parameters:
  1703. * (Function) handler - A function to be executed when the handler is run.
  1704. * (String) ns - The namespace to match.
  1705. * (String) name - The element name to match.
  1706. * (String) type - The element type to match.
  1707. * (String) id - The element id attribute to match.
  1708. * (String) from - The element from attribute to match.
  1709. * (Object) options - Handler options
  1710. *
  1711. * Returns:
  1712. * A new Strophe.Handler object.
  1713. */
  1714. Strophe.Handler = function (handler, ns, name, type, id, from, options)
  1715. {
  1716. this.handler = handler;
  1717. this.ns = ns;
  1718. this.name = name;
  1719. this.type = type;
  1720. this.id = id;
  1721. this.options = options || {matchBare: false};
  1722. // default matchBare to false if undefined
  1723. if (!this.options.matchBare) {
  1724. this.options.matchBare = false;
  1725. }
  1726. if (this.options.matchBare) {
  1727. this.from = from ? Strophe.getBareJidFromJid(from) : null;
  1728. } else {
  1729. this.from = from;
  1730. }
  1731. // whether the handler is a user handler or a system handler
  1732. this.user = true;
  1733. };
  1734. Strophe.Handler.prototype = {
  1735. /** PrivateFunction: isMatch
  1736. * Tests if a stanza matches the Strophe.Handler.
  1737. *
  1738. * Parameters:
  1739. * (XMLElement) elem - The XML element to test.
  1740. *
  1741. * Returns:
  1742. * true if the stanza matches and false otherwise.
  1743. */
  1744. isMatch: function (elem)
  1745. {
  1746. var nsMatch;
  1747. var from = null;
  1748. if (this.options.matchBare) {
  1749. from = Strophe.getBareJidFromJid(elem.getAttribute('from'));
  1750. } else {
  1751. from = elem.getAttribute('from');
  1752. }
  1753. nsMatch = false;
  1754. if (!this.ns) {
  1755. nsMatch = true;
  1756. } else {
  1757. var that = this;
  1758. Strophe.forEachChild(elem, null, function (elem) {
  1759. if (elem.getAttribute("xmlns") == that.ns) {
  1760. nsMatch = true;
  1761. }
  1762. });
  1763. nsMatch = nsMatch || elem.getAttribute("xmlns") == this.ns;
  1764. }
  1765. var elem_type = elem.getAttribute("type");
  1766. if (nsMatch &&
  1767. (!this.name || Strophe.isTagEqual(elem, this.name)) &&
  1768. (!this.type || (Array.isArray(this.type) ? this.type.indexOf(elem_type) != -1 : elem_type == this.type)) &&
  1769. (!this.id || elem.getAttribute("id") == this.id) &&
  1770. (!this.from || from == this.from)) {
  1771. return true;
  1772. }
  1773. return false;
  1774. },
  1775. /** PrivateFunction: run
  1776. * Run the callback on a matching stanza.
  1777. *
  1778. * Parameters:
  1779. * (XMLElement) elem - The DOM element that triggered the
  1780. * Strophe.Handler.
  1781. *
  1782. * Returns:
  1783. * A boolean indicating if the handler should remain active.
  1784. */
  1785. run: function (elem)
  1786. {
  1787. var result = null;
  1788. try {
  1789. result = this.handler(elem);
  1790. } catch (e) {
  1791. if (e.sourceURL) {
  1792. Strophe.fatal("error: " + this.handler +
  1793. " " + e.sourceURL + ":" +
  1794. e.line + " - " + e.name + ": " + e.message);
  1795. } else if (e.fileName) {
  1796. if (typeof(console) != "undefined") {
  1797. console.trace();
  1798. console.error(this.handler, " - error - ", e, e.message);
  1799. }
  1800. Strophe.fatal("error: " + this.handler + " " +
  1801. e.fileName + ":" + e.lineNumber + " - " +
  1802. e.name + ": " + e.message);
  1803. } else {
  1804. Strophe.fatal("error: " + e.message + "\n" + e.stack);
  1805. }
  1806. throw e;
  1807. }
  1808. return result;
  1809. },
  1810. /** PrivateFunction: toString
  1811. * Get a String representation of the Strophe.Handler object.
  1812. *
  1813. * Returns:
  1814. * A String.
  1815. */
  1816. toString: function ()
  1817. {
  1818. return "{Handler: " + this.handler + "(" + this.name + "," +
  1819. this.id + "," + this.ns + ")}";
  1820. }
  1821. };
  1822. /** PrivateClass: Strophe.TimedHandler
  1823. * _Private_ helper class for managing timed handlers.
  1824. *
  1825. * A Strophe.TimedHandler encapsulates a user provided callback that
  1826. * should be called after a certain period of time or at regular
  1827. * intervals. The return value of the callback determines whether the
  1828. * Strophe.TimedHandler will continue to fire.
  1829. *
  1830. * Users will not use Strophe.TimedHandler objects directly, but instead
  1831. * they will use Strophe.Connection.addTimedHandler() and
  1832. * Strophe.Connection.deleteTimedHandler().
  1833. */
  1834. /** PrivateConstructor: Strophe.TimedHandler
  1835. * Create and initialize a new Strophe.TimedHandler object.
  1836. *
  1837. * Parameters:
  1838. * (Integer) period - The number of milliseconds to wait before the
  1839. * handler is called.
  1840. * (Function) handler - The callback to run when the handler fires. This
  1841. * function should take no arguments.
  1842. *
  1843. * Returns:
  1844. * A new Strophe.TimedHandler object.
  1845. */
  1846. Strophe.TimedHandler = function (period, handler)
  1847. {
  1848. this.period = period;
  1849. this.handler = handler;
  1850. this.lastCalled = new Date().getTime();
  1851. this.user = true;
  1852. };
  1853. Strophe.TimedHandler.prototype = {
  1854. /** PrivateFunction: run
  1855. * Run the callback for the Strophe.TimedHandler.
  1856. *
  1857. * Returns:
  1858. * true if the Strophe.TimedHandler should be called again, and false
  1859. * otherwise.
  1860. */
  1861. run: function ()
  1862. {
  1863. this.lastCalled = new Date().getTime();
  1864. return this.handler();
  1865. },
  1866. /** PrivateFunction: reset
  1867. * Reset the last called time for the Strophe.TimedHandler.
  1868. */
  1869. reset: function ()
  1870. {
  1871. this.lastCalled = new Date().getTime();
  1872. },
  1873. /** PrivateFunction: toString
  1874. * Get a string representation of the Strophe.TimedHandler object.
  1875. *
  1876. * Returns:
  1877. * The string representation.
  1878. */
  1879. toString: function ()
  1880. {
  1881. return "{TimedHandler: " + this.handler + "(" + this.period +")}";
  1882. }
  1883. };
  1884. /** Class: Strophe.Connection
  1885. * XMPP Connection manager.
  1886. *
  1887. * This class is the main part of Strophe. It manages a BOSH or websocket
  1888. * connection to an XMPP server and dispatches events to the user callbacks
  1889. * as data arrives. It supports SASL PLAIN, SASL DIGEST-MD5, SASL SCRAM-SHA1
  1890. * and legacy authentication.
  1891. *
  1892. * After creating a Strophe.Connection object, the user will typically
  1893. * call connect() with a user supplied callback to handle connection level
  1894. * events like authentication failure, disconnection, or connection
  1895. * complete.
  1896. *
  1897. * The user will also have several event handlers defined by using
  1898. * addHandler() and addTimedHandler(). These will allow the user code to
  1899. * respond to interesting stanzas or do something periodically with the
  1900. * connection. These handlers will be active once authentication is
  1901. * finished.
  1902. *
  1903. * To send data to the connection, use send().
  1904. */
  1905. /** Constructor: Strophe.Connection
  1906. * Create and initialize a Strophe.Connection object.
  1907. *
  1908. * The transport-protocol for this connection will be chosen automatically
  1909. * based on the given service parameter. URLs starting with "ws://" or
  1910. * "wss://" will use WebSockets, URLs starting with "http://", "https://"
  1911. * or without a protocol will use BOSH.
  1912. *
  1913. * To make Strophe connect to the current host you can leave out the protocol
  1914. * and host part and just pass the path, e.g.
  1915. *
  1916. * > var conn = new Strophe.Connection("/http-bind/");
  1917. *
  1918. * WebSocket options:
  1919. *
  1920. * If you want to connect to the current host with a WebSocket connection you
  1921. * can tell Strophe to use WebSockets through a "protocol" attribute in the
  1922. * optional options parameter. Valid values are "ws" for WebSocket and "wss"
  1923. * for Secure WebSocket.
  1924. * So to connect to "wss://CURRENT_HOSTNAME/xmpp-websocket" you would call
  1925. *
  1926. * > var conn = new Strophe.Connection("/xmpp-websocket/", {protocol: "wss"});
  1927. *
  1928. * Note that relative URLs _NOT_ starting with a "/" will also include the path
  1929. * of the current site.
  1930. *
  1931. * Also because downgrading security is not permitted by browsers, when using
  1932. * relative URLs both BOSH and WebSocket connections will use their secure
  1933. * variants if the current connection to the site is also secure (https).
  1934. *
  1935. * BOSH options:
  1936. *
  1937. * By adding "sync" to the options, you can control if requests will
  1938. * be made synchronously or not. The default behaviour is asynchronous.
  1939. * If you want to make requests synchronous, make "sync" evaluate to true:
  1940. * > var conn = new Strophe.Connection("/http-bind/", {sync: true});
  1941. *
  1942. * You can also toggle this on an already established connection:
  1943. * > conn.options.sync = true;
  1944. *
  1945. * The "customHeaders" option can be used to provide custom HTTP headers to be
  1946. * included in the XMLHttpRequests made.
  1947. *
  1948. * The "keepalive" option can be used to instruct Strophe to maintain the
  1949. * current BOSH session across interruptions such as webpage reloads.
  1950. *
  1951. * It will do this by caching the sessions tokens in sessionStorage, and when
  1952. * "restore" is called it will check whether there are cached tokens with
  1953. * which it can resume an existing session.
  1954. *
  1955. * Parameters:
  1956. * (String) service - The BOSH or WebSocket service URL.
  1957. * (Object) options - A hash of configuration options
  1958. *
  1959. * Returns:
  1960. * A new Strophe.Connection object.
  1961. */
  1962. Strophe.Connection = function (service, options)
  1963. {
  1964. // The service URL
  1965. this.service = service;
  1966. // Configuration options
  1967. this.options = options || {};
  1968. var proto = this.options.protocol || "";
  1969. // Select protocal based on service or options
  1970. if (service.indexOf("ws:") === 0 || service.indexOf("wss:") === 0 ||
  1971. proto.indexOf("ws") === 0) {
  1972. this._proto = new Strophe.Websocket(this);
  1973. } else {
  1974. this._proto = new Strophe.Bosh(this);
  1975. }
  1976. /* The connected JID. */
  1977. this.jid = "";
  1978. /* the JIDs domain */
  1979. this.domain = null;
  1980. /* stream:features */
  1981. this.features = null;
  1982. // SASL
  1983. this._sasl_data = {};
  1984. this.do_session = false;
  1985. this.do_bind = false;
  1986. // handler lists
  1987. this.timedHandlers = [];
  1988. this.handlers = [];
  1989. this.removeTimeds = [];
  1990. this.removeHandlers = [];
  1991. this.addTimeds = [];
  1992. this.addHandlers = [];
  1993. this._authentication = {};
  1994. this._idleTimeout = null;
  1995. this._disconnectTimeout = null;
  1996. this.authenticated = false;
  1997. this.connected = false;
  1998. this.disconnecting = false;
  1999. this.do_authentication = true;
  2000. this.paused = false;
  2001. this.restored = false;
  2002. this._data = [];
  2003. this._uniqueId = 0;
  2004. this._sasl_success_handler = null;
  2005. this._sasl_failure_handler = null;
  2006. this._sasl_challenge_handler = null;
  2007. // Max retries before disconnecting
  2008. this.maxRetries = 5;
  2009. // setup onIdle callback every 1/10th of a second
  2010. this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
  2011. // initialize plugins
  2012. for (var k in Strophe._connectionPlugins) {
  2013. if (Strophe._connectionPlugins.hasOwnProperty(k)) {
  2014. var ptype = Strophe._connectionPlugins[k];
  2015. // jslint complaints about the below line, but this is fine
  2016. var F = function () {}; // jshint ignore:line
  2017. F.prototype = ptype;
  2018. this[k] = new F();
  2019. this[k].init(this);
  2020. }
  2021. }
  2022. };
  2023. Strophe.Connection.prototype = {
  2024. /** Function: reset
  2025. * Reset the connection.
  2026. *
  2027. * This function should be called after a connection is disconnected
  2028. * before that connection is reused.
  2029. */
  2030. reset: function ()
  2031. {
  2032. this._proto._reset();
  2033. // SASL
  2034. this.do_session = false;
  2035. this.do_bind = false;
  2036. // handler lists
  2037. this.timedHandlers = [];
  2038. this.handlers = [];
  2039. this.removeTimeds = [];
  2040. this.removeHandlers = [];
  2041. this.addTimeds = [];
  2042. this.addHandlers = [];
  2043. this._authentication = {};
  2044. this.authenticated = false;
  2045. this.connected = false;
  2046. this.disconnecting = false;
  2047. this.restored = false;
  2048. this._data = [];
  2049. this._requests = [];
  2050. this._uniqueId = 0;
  2051. },
  2052. /** Function: pause
  2053. * Pause the request manager.
  2054. *
  2055. * This will prevent Strophe from sending any more requests to the
  2056. * server. This is very useful for temporarily pausing
  2057. * BOSH-Connections while a lot of send() calls are happening quickly.
  2058. * This causes Strophe to send the data in a single request, saving
  2059. * many request trips.
  2060. */
  2061. pause: function ()
  2062. {
  2063. this.paused = true;
  2064. },
  2065. /** Function: resume
  2066. * Resume the request manager.
  2067. *
  2068. * This resumes after pause() has been called.
  2069. */
  2070. resume: function ()
  2071. {
  2072. this.paused = false;
  2073. },
  2074. /** Function: getUniqueId
  2075. * Generate a unique ID for use in <iq/> elements.
  2076. *
  2077. * All <iq/> stanzas are required to have unique id attributes. This
  2078. * function makes creating these easy. Each connection instance has
  2079. * a counter which starts from zero, and the value of this counter
  2080. * plus a colon followed by the suffix becomes the unique id. If no
  2081. * suffix is supplied, the counter is used as the unique id.
  2082. *
  2083. * Suffixes are used to make debugging easier when reading the stream
  2084. * data, and their use is recommended. The counter resets to 0 for
  2085. * every new connection for the same reason. For connections to the
  2086. * same server that authenticate the same way, all the ids should be
  2087. * the same, which makes it easy to see changes. This is useful for
  2088. * automated testing as well.
  2089. *
  2090. * Parameters:
  2091. * (String) suffix - A optional suffix to append to the id.
  2092. *
  2093. * Returns:
  2094. * A unique string to be used for the id attribute.
  2095. */
  2096. getUniqueId: function (suffix)
  2097. {
  2098. if (typeof(suffix) == "string" || typeof(suffix) == "number") {
  2099. return ++this._uniqueId + ":" + suffix;
  2100. } else {
  2101. return ++this._uniqueId + "";
  2102. }
  2103. },
  2104. /** Function: connect
  2105. * Starts the connection process.
  2106. *
  2107. * As the connection process proceeds, the user supplied callback will
  2108. * be triggered multiple times with status updates. The callback
  2109. * should take two arguments - the status code and the error condition.
  2110. *
  2111. * The status code will be one of the values in the Strophe.Status
  2112. * constants. The error condition will be one of the conditions
  2113. * defined in RFC 3920 or the condition 'strophe-parsererror'.
  2114. *
  2115. * The Parameters _wait_, _hold_ and _route_ are optional and only relevant
  2116. * for BOSH connections. Please see XEP 124 for a more detailed explanation
  2117. * of the optional parameters.
  2118. *
  2119. * Parameters:
  2120. * (String) jid - The user's JID. This may be a bare JID,
  2121. * or a full JID. If a node is not supplied, SASL ANONYMOUS
  2122. * authentication will be attempted.
  2123. * (String) pass - The user's password.
  2124. * (Function) callback - The connect callback function.
  2125. * (Integer) wait - The optional HTTPBIND wait value. This is the
  2126. * time the server will wait before returning an empty result for
  2127. * a request. The default setting of 60 seconds is recommended.
  2128. * (Integer) hold - The optional HTTPBIND hold value. This is the
  2129. * number of connections the server will hold at one time. This
  2130. * should almost always be set to 1 (the default).
  2131. * (String) route - The optional route value.
  2132. * (String) authcid - The optional alternative authentication identity
  2133. * (username) if intending to impersonate another user.
  2134. */
  2135. connect: function (jid, pass, callback, wait, hold, route, authcid)
  2136. {
  2137. this.jid = jid;
  2138. /** Variable: authzid
  2139. * Authorization identity.
  2140. */
  2141. this.authzid = Strophe.getBareJidFromJid(this.jid);
  2142. /** Variable: authcid
  2143. * Authentication identity (User name).
  2144. */
  2145. this.authcid = authcid || Strophe.getNodeFromJid(this.jid);
  2146. /** Variable: pass
  2147. * Authentication identity (User password).
  2148. */
  2149. this.pass = pass;
  2150. /** Variable: servtype
  2151. * Digest MD5 compatibility.
  2152. */
  2153. this.servtype = "xmpp";
  2154. this.connect_callback = callback;
  2155. this.disconnecting = false;
  2156. this.connected = false;
  2157. this.authenticated = false;
  2158. this.restored = false;
  2159. // parse jid for domain
  2160. this.domain = Strophe.getDomainFromJid(this.jid);
  2161. this._changeConnectStatus(Strophe.Status.CONNECTING, null);
  2162. this._proto._connect(wait, hold, route);
  2163. },
  2164. /** Function: attach
  2165. * Attach to an already created and authenticated BOSH session.
  2166. *
  2167. * This function is provided to allow Strophe to attach to BOSH
  2168. * sessions which have been created externally, perhaps by a Web
  2169. * application. This is often used to support auto-login type features
  2170. * without putting user credentials into the page.
  2171. *
  2172. * Parameters:
  2173. * (String) jid - The full JID that is bound by the session.
  2174. * (String) sid - The SID of the BOSH session.
  2175. * (String) rid - The current RID of the BOSH session. This RID
  2176. * will be used by the next request.
  2177. * (Function) callback The connect callback function.
  2178. * (Integer) wait - The optional HTTPBIND wait value. This is the
  2179. * time the server will wait before returning an empty result for
  2180. * a request. The default setting of 60 seconds is recommended.
  2181. * Other settings will require tweaks to the Strophe.TIMEOUT value.
  2182. * (Integer) hold - The optional HTTPBIND hold value. This is the
  2183. * number of connections the server will hold at one time. This
  2184. * should almost always be set to 1 (the default).
  2185. * (Integer) wind - The optional HTTBIND window value. This is the
  2186. * allowed range of request ids that are valid. The default is 5.
  2187. */
  2188. attach: function (jid, sid, rid, callback, wait, hold, wind)
  2189. {
  2190. if (this._proto instanceof Strophe.Bosh) {
  2191. this._proto._attach(jid, sid, rid, callback, wait, hold, wind);
  2192. } else {
  2193. throw {
  2194. name: 'StropheSessionError',
  2195. message: 'The "attach" method can only be used with a BOSH connection.'
  2196. };
  2197. }
  2198. },
  2199. /** Function: restore
  2200. * Attempt to restore a cached BOSH session.
  2201. *
  2202. * This function is only useful in conjunction with providing the
  2203. * "keepalive":true option when instantiating a new Strophe.Connection.
  2204. *
  2205. * When "keepalive" is set to true, Strophe will cache the BOSH tokens
  2206. * RID (Request ID) and SID (Session ID) and then when this function is
  2207. * called, it will attempt to restore the session from those cached
  2208. * tokens.
  2209. *
  2210. * This function must therefore be called instead of connect or attach.
  2211. *
  2212. * For an example on how to use it, please see examples/restore.js
  2213. *
  2214. * Parameters:
  2215. * (String) jid - The user's JID. This may be a bare JID or a full JID.
  2216. * (Function) callback - The connect callback function.
  2217. * (Integer) wait - The optional HTTPBIND wait value. This is the
  2218. * time the server will wait before returning an empty result for
  2219. * a request. The default setting of 60 seconds is recommended.
  2220. * (Integer) hold - The optional HTTPBIND hold value. This is the
  2221. * number of connections the server will hold at one time. This
  2222. * should almost always be set to 1 (the default).
  2223. * (Integer) wind - The optional HTTBIND window value. This is the
  2224. * allowed range of request ids that are valid. The default is 5.
  2225. */
  2226. restore: function (jid, callback, wait, hold, wind)
  2227. {
  2228. if (this._sessionCachingSupported()) {
  2229. this._proto._restore(jid, callback, wait, hold, wind);
  2230. } else {
  2231. throw {
  2232. name: 'StropheSessionError',
  2233. message: 'The "restore" method can only be used with a BOSH connection.'
  2234. };
  2235. }
  2236. },
  2237. /** PrivateFunction: _sessionCachingSupported
  2238. * Checks whether sessionStorage and JSON are supported and whether we're
  2239. * using BOSH.
  2240. */
  2241. _sessionCachingSupported: function ()
  2242. {
  2243. if (this._proto instanceof Strophe.Bosh) {
  2244. if (!JSON) { return false; }
  2245. try {
  2246. window.sessionStorage.setItem('_strophe_', '_strophe_');
  2247. window.sessionStorage.removeItem('_strophe_');
  2248. } catch (e) {
  2249. return false;
  2250. }
  2251. return true;
  2252. }
  2253. return false;
  2254. },
  2255. /** Function: xmlInput
  2256. * User overrideable function that receives XML data coming into the
  2257. * connection.
  2258. *
  2259. * The default function does nothing. User code can override this with
  2260. * > Strophe.Connection.xmlInput = function (elem) {
  2261. * > (user code)
  2262. * > };
  2263. *
  2264. * Due to limitations of current Browsers' XML-Parsers the opening and closing
  2265. * <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.
  2266. *
  2267. * BOSH-Connections will have all stanzas wrapped in a <body> tag. See
  2268. * <Strophe.Bosh.strip> if you want to strip this tag.
  2269. *
  2270. * Parameters:
  2271. * (XMLElement) elem - The XML data received by the connection.
  2272. */
  2273. /* jshint unused:false */
  2274. xmlInput: function (elem)
  2275. {
  2276. return;
  2277. },
  2278. /* jshint unused:true */
  2279. /** Function: xmlOutput
  2280. * User overrideable function that receives XML data sent to the
  2281. * connection.
  2282. *
  2283. * The default function does nothing. User code can override this with
  2284. * > Strophe.Connection.xmlOutput = function (elem) {
  2285. * > (user code)
  2286. * > };
  2287. *
  2288. * Due to limitations of current Browsers' XML-Parsers the opening and closing
  2289. * <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.
  2290. *
  2291. * BOSH-Connections will have all stanzas wrapped in a <body> tag. See
  2292. * <Strophe.Bosh.strip> if you want to strip this tag.
  2293. *
  2294. * Parameters:
  2295. * (XMLElement) elem - The XMLdata sent by the connection.
  2296. */
  2297. /* jshint unused:false */
  2298. xmlOutput: function (elem)
  2299. {
  2300. return;
  2301. },
  2302. /* jshint unused:true */
  2303. /** Function: rawInput
  2304. * User overrideable function that receives raw data coming into the
  2305. * connection.
  2306. *
  2307. * The default function does nothing. User code can override this with
  2308. * > Strophe.Connection.rawInput = function (data) {
  2309. * > (user code)
  2310. * > };
  2311. *
  2312. * Parameters:
  2313. * (String) data - The data received by the connection.
  2314. */
  2315. /* jshint unused:false */
  2316. rawInput: function (data)
  2317. {
  2318. return;
  2319. },
  2320. /* jshint unused:true */
  2321. /** Function: rawOutput
  2322. * User overrideable function that receives raw data sent to the
  2323. * connection.
  2324. *
  2325. * The default function does nothing. User code can override this with
  2326. * > Strophe.Connection.rawOutput = function (data) {
  2327. * > (user code)
  2328. * > };
  2329. *
  2330. * Parameters:
  2331. * (String) data - The data sent by the connection.
  2332. */
  2333. /* jshint unused:false */
  2334. rawOutput: function (data)
  2335. {
  2336. return;
  2337. },
  2338. /* jshint unused:true */
  2339. /** Function: send
  2340. * Send a stanza.
  2341. *
  2342. * This function is called to push data onto the send queue to
  2343. * go out over the wire. Whenever a request is sent to the BOSH
  2344. * server, all pending data is sent and the queue is flushed.
  2345. *
  2346. * Parameters:
  2347. * (XMLElement |
  2348. * [XMLElement] |
  2349. * Strophe.Builder) elem - The stanza to send.
  2350. */
  2351. send: function (elem)
  2352. {
  2353. if (elem === null) { return ; }
  2354. if (typeof(elem.sort) === "function") {
  2355. for (var i = 0; i < elem.length; i++) {
  2356. this._queueData(elem[i]);
  2357. }
  2358. } else if (typeof(elem.tree) === "function") {
  2359. this._queueData(elem.tree());
  2360. } else {
  2361. this._queueData(elem);
  2362. }
  2363. this._proto._send();
  2364. },
  2365. /** Function: flush
  2366. * Immediately send any pending outgoing data.
  2367. *
  2368. * Normally send() queues outgoing data until the next idle period
  2369. * (100ms), which optimizes network use in the common cases when
  2370. * several send()s are called in succession. flush() can be used to
  2371. * immediately send all pending data.
  2372. */
  2373. flush: function ()
  2374. {
  2375. // cancel the pending idle period and run the idle function
  2376. // immediately
  2377. clearTimeout(this._idleTimeout);
  2378. this._onIdle();
  2379. },
  2380. /** Function: sendIQ
  2381. * Helper function to send IQ stanzas.
  2382. *
  2383. * Parameters:
  2384. * (XMLElement) elem - The stanza to send.
  2385. * (Function) callback - The callback function for a successful request.
  2386. * (Function) errback - The callback function for a failed or timed
  2387. * out request. On timeout, the stanza will be null.
  2388. * (Integer) timeout - The time specified in milliseconds for a
  2389. * timeout to occur.
  2390. *
  2391. * Returns:
  2392. * The id used to send the IQ.
  2393. */
  2394. sendIQ: function(elem, callback, errback, timeout) {
  2395. var timeoutHandler = null;
  2396. var that = this;
  2397. if (typeof(elem.tree) === "function") {
  2398. elem = elem.tree();
  2399. }
  2400. var id = elem.getAttribute('id');
  2401. // inject id if not found
  2402. if (!id) {
  2403. id = this.getUniqueId("sendIQ");
  2404. elem.setAttribute("id", id);
  2405. }
  2406. var expectedFrom = elem.getAttribute("to");
  2407. var fulljid = this.jid;
  2408. var handler = this.addHandler(function (stanza) {
  2409. // remove timeout handler if there is one
  2410. if (timeoutHandler) {
  2411. that.deleteTimedHandler(timeoutHandler);
  2412. }
  2413. var acceptable = false;
  2414. var from = stanza.getAttribute("from");
  2415. if (from === expectedFrom ||
  2416. (expectedFrom === null &&
  2417. (from === Strophe.getBareJidFromJid(fulljid) ||
  2418. from === Strophe.getDomainFromJid(fulljid) ||
  2419. from === fulljid))) {
  2420. acceptable = true;
  2421. }
  2422. if (!acceptable) {
  2423. throw {
  2424. name: "StropheError",
  2425. message: "Got answer to IQ from wrong jid:" + from +
  2426. "\nExpected jid: " + expectedFrom
  2427. };
  2428. }
  2429. var iqtype = stanza.getAttribute('type');
  2430. if (iqtype == 'result') {
  2431. if (callback) {
  2432. callback(stanza);
  2433. }
  2434. } else if (iqtype == 'error') {
  2435. if (errback) {
  2436. errback(stanza);
  2437. }
  2438. } else {
  2439. throw {
  2440. name: "StropheError",
  2441. message: "Got bad IQ type of " + iqtype
  2442. };
  2443. }
  2444. }, null, 'iq', ['error', 'result'], id);
  2445. // if timeout specified, setup timeout handler.
  2446. if (timeout) {
  2447. timeoutHandler = this.addTimedHandler(timeout, function () {
  2448. // get rid of normal handler
  2449. that.deleteHandler(handler);
  2450. // call errback on timeout with null stanza
  2451. if (errback) {
  2452. errback(null);
  2453. }
  2454. return false;
  2455. });
  2456. }
  2457. this.send(elem);
  2458. return id;
  2459. },
  2460. /** PrivateFunction: _queueData
  2461. * Queue outgoing data for later sending. Also ensures that the data
  2462. * is a DOMElement.
  2463. */
  2464. _queueData: function (element) {
  2465. if (element === null ||
  2466. !element.tagName ||
  2467. !element.childNodes) {
  2468. throw {
  2469. name: "StropheError",
  2470. message: "Cannot queue non-DOMElement."
  2471. };
  2472. }
  2473. this._data.push(element);
  2474. },
  2475. /** PrivateFunction: _sendRestart
  2476. * Send an xmpp:restart stanza.
  2477. */
  2478. _sendRestart: function ()
  2479. {
  2480. this._data.push("restart");
  2481. this._proto._sendRestart();
  2482. this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
  2483. },
  2484. /** Function: addTimedHandler
  2485. * Add a timed handler to the connection.
  2486. *
  2487. * This function adds a timed handler. The provided handler will
  2488. * be called every period milliseconds until it returns false,
  2489. * the connection is terminated, or the handler is removed. Handlers
  2490. * that wish to continue being invoked should return true.
  2491. *
  2492. * Because of method binding it is necessary to save the result of
  2493. * this function if you wish to remove a handler with
  2494. * deleteTimedHandler().
  2495. *
  2496. * Note that user handlers are not active until authentication is
  2497. * successful.
  2498. *
  2499. * Parameters:
  2500. * (Integer) period - The period of the handler.
  2501. * (Function) handler - The callback function.
  2502. *
  2503. * Returns:
  2504. * A reference to the handler that can be used to remove it.
  2505. */
  2506. addTimedHandler: function (period, handler)
  2507. {
  2508. var thand = new Strophe.TimedHandler(period, handler);
  2509. this.addTimeds.push(thand);
  2510. return thand;
  2511. },
  2512. /** Function: deleteTimedHandler
  2513. * Delete a timed handler for a connection.
  2514. *
  2515. * This function removes a timed handler from the connection. The
  2516. * handRef parameter is *not* the function passed to addTimedHandler(),
  2517. * but is the reference returned from addTimedHandler().
  2518. *
  2519. * Parameters:
  2520. * (Strophe.TimedHandler) handRef - The handler reference.
  2521. */
  2522. deleteTimedHandler: function (handRef)
  2523. {
  2524. // this must be done in the Idle loop so that we don't change
  2525. // the handlers during iteration
  2526. this.removeTimeds.push(handRef);
  2527. },
  2528. /** Function: addHandler
  2529. * Add a stanza handler for the connection.
  2530. *
  2531. * This function adds a stanza handler to the connection. The
  2532. * handler callback will be called for any stanza that matches
  2533. * the parameters. Note that if multiple parameters are supplied,
  2534. * they must all match for the handler to be invoked.
  2535. *
  2536. * The handler will receive the stanza that triggered it as its argument.
  2537. * *The handler should return true if it is to be invoked again;
  2538. * returning false will remove the handler after it returns.*
  2539. *
  2540. * As a convenience, the ns parameters applies to the top level element
  2541. * and also any of its immediate children. This is primarily to make
  2542. * matching /iq/query elements easy.
  2543. *
  2544. * The options argument contains handler matching flags that affect how
  2545. * matches are determined. Currently the only flag is matchBare (a
  2546. * boolean). When matchBare is true, the from parameter and the from
  2547. * attribute on the stanza will be matched as bare JIDs instead of
  2548. * full JIDs. To use this, pass {matchBare: true} as the value of
  2549. * options. The default value for matchBare is false.
  2550. *
  2551. * The return value should be saved if you wish to remove the handler
  2552. * with deleteHandler().
  2553. *
  2554. * Parameters:
  2555. * (Function) handler - The user callback.
  2556. * (String) ns - The namespace to match.
  2557. * (String) name - The stanza name to match.
  2558. * (String) type - The stanza type attribute to match.
  2559. * (String) id - The stanza id attribute to match.
  2560. * (String) from - The stanza from attribute to match.
  2561. * (String) options - The handler options
  2562. *
  2563. * Returns:
  2564. * A reference to the handler that can be used to remove it.
  2565. */
  2566. addHandler: function (handler, ns, name, type, id, from, options)
  2567. {
  2568. var hand = new Strophe.Handler(handler, ns, name, type, id, from, options);
  2569. this.addHandlers.push(hand);
  2570. return hand;
  2571. },
  2572. /** Function: deleteHandler
  2573. * Delete a stanza handler for a connection.
  2574. *
  2575. * This function removes a stanza handler from the connection. The
  2576. * handRef parameter is *not* the function passed to addHandler(),
  2577. * but is the reference returned from addHandler().
  2578. *
  2579. * Parameters:
  2580. * (Strophe.Handler) handRef - The handler reference.
  2581. */
  2582. deleteHandler: function (handRef)
  2583. {
  2584. // this must be done in the Idle loop so that we don't change
  2585. // the handlers during iteration
  2586. this.removeHandlers.push(handRef);
  2587. // If a handler is being deleted while it is being added,
  2588. // prevent it from getting added
  2589. var i = this.addHandlers.indexOf(handRef);
  2590. if (i >= 0) {
  2591. this.addHandlers.splice(i, 1);
  2592. }
  2593. },
  2594. /** Function: disconnect
  2595. * Start the graceful disconnection process.
  2596. *
  2597. * This function starts the disconnection process. This process starts
  2598. * by sending unavailable presence and sending BOSH body of type
  2599. * terminate. A timeout handler makes sure that disconnection happens
  2600. * even if the BOSH server does not respond.
  2601. * If the Connection object isn't connected, at least tries to abort all pending requests
  2602. * so the connection object won't generate successful requests (which were already opened).
  2603. *
  2604. * The user supplied connection callback will be notified of the
  2605. * progress as this process happens.
  2606. *
  2607. * Parameters:
  2608. * (String) reason - The reason the disconnect is occuring.
  2609. */
  2610. disconnect: function (reason)
  2611. {
  2612. this._changeConnectStatus(Strophe.Status.DISCONNECTING, reason);
  2613. Strophe.info("Disconnect was called because: " + reason);
  2614. if (this.connected) {
  2615. var pres = false;
  2616. this.disconnecting = true;
  2617. if (this.authenticated) {
  2618. pres = $pres({
  2619. xmlns: Strophe.NS.CLIENT,
  2620. type: 'unavailable'
  2621. });
  2622. }
  2623. // setup timeout handler
  2624. this._disconnectTimeout = this._addSysTimedHandler(
  2625. 3000, this._onDisconnectTimeout.bind(this));
  2626. this._proto._disconnect(pres);
  2627. } else {
  2628. Strophe.info("Disconnect was called before Strophe connected to the server");
  2629. this._proto._abortAllRequests();
  2630. }
  2631. },
  2632. /** PrivateFunction: _changeConnectStatus
  2633. * _Private_ helper function that makes sure plugins and the user's
  2634. * callback are notified of connection status changes.
  2635. *
  2636. * Parameters:
  2637. * (Integer) status - the new connection status, one of the values
  2638. * in Strophe.Status
  2639. * (String) condition - the error condition or null
  2640. */
  2641. _changeConnectStatus: function (status, condition)
  2642. {
  2643. // notify all plugins listening for status changes
  2644. for (var k in Strophe._connectionPlugins) {
  2645. if (Strophe._connectionPlugins.hasOwnProperty(k)) {
  2646. var plugin = this[k];
  2647. if (plugin.statusChanged) {
  2648. try {
  2649. plugin.statusChanged(status, condition);
  2650. } catch (err) {
  2651. Strophe.error("" + k + " plugin caused an exception " +
  2652. "changing status: " + err);
  2653. }
  2654. }
  2655. }
  2656. }
  2657. // notify the user's callback
  2658. if (this.connect_callback) {
  2659. try {
  2660. this.connect_callback(status, condition);
  2661. } catch (e) {
  2662. Strophe.error("User connection callback caused an " +
  2663. "exception: " + e);
  2664. }
  2665. }
  2666. },
  2667. /** PrivateFunction: _doDisconnect
  2668. * _Private_ function to disconnect.
  2669. *
  2670. * This is the last piece of the disconnection logic. This resets the
  2671. * connection and alerts the user's connection callback.
  2672. */
  2673. _doDisconnect: function (condition)
  2674. {
  2675. if (typeof this._idleTimeout == "number") {
  2676. clearTimeout(this._idleTimeout);
  2677. }
  2678. // Cancel Disconnect Timeout
  2679. if (this._disconnectTimeout !== null) {
  2680. this.deleteTimedHandler(this._disconnectTimeout);
  2681. this._disconnectTimeout = null;
  2682. }
  2683. Strophe.info("_doDisconnect was called");
  2684. this._proto._doDisconnect();
  2685. this.authenticated = false;
  2686. this.disconnecting = false;
  2687. this.restored = false;
  2688. // delete handlers
  2689. this.handlers = [];
  2690. this.timedHandlers = [];
  2691. this.removeTimeds = [];
  2692. this.removeHandlers = [];
  2693. this.addTimeds = [];
  2694. this.addHandlers = [];
  2695. // tell the parent we disconnected
  2696. this._changeConnectStatus(Strophe.Status.DISCONNECTED, condition);
  2697. this.connected = false;
  2698. },
  2699. /** PrivateFunction: _dataRecv
  2700. * _Private_ handler to processes incoming data from the the connection.
  2701. *
  2702. * Except for _connect_cb handling the initial connection request,
  2703. * this function handles the incoming data for all requests. This
  2704. * function also fires stanza handlers that match each incoming
  2705. * stanza.
  2706. *
  2707. * Parameters:
  2708. * (Strophe.Request) req - The request that has data ready.
  2709. * (string) req - The stanza a raw string (optiona).
  2710. */
  2711. _dataRecv: function (req, raw)
  2712. {
  2713. Strophe.info("_dataRecv called");
  2714. var elem = this._proto._reqToData(req);
  2715. if (elem === null) { return; }
  2716. if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
  2717. if (elem.nodeName === this._proto.strip && elem.childNodes.length) {
  2718. this.xmlInput(elem.childNodes[0]);
  2719. } else {
  2720. this.xmlInput(elem);
  2721. }
  2722. }
  2723. if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
  2724. if (raw) {
  2725. this.rawInput(raw);
  2726. } else {
  2727. this.rawInput(Strophe.serialize(elem));
  2728. }
  2729. }
  2730. // remove handlers scheduled for deletion
  2731. var i, hand;
  2732. while (this.removeHandlers.length > 0) {
  2733. hand = this.removeHandlers.pop();
  2734. i = this.handlers.indexOf(hand);
  2735. if (i >= 0) {
  2736. this.handlers.splice(i, 1);
  2737. }
  2738. }
  2739. // add handlers scheduled for addition
  2740. while (this.addHandlers.length > 0) {
  2741. this.handlers.push(this.addHandlers.pop());
  2742. }
  2743. // handle graceful disconnect
  2744. if (this.disconnecting && this._proto._emptyQueue()) {
  2745. this._doDisconnect();
  2746. return;
  2747. }
  2748. var type = elem.getAttribute("type");
  2749. var cond, conflict;
  2750. if (type !== null && type == "terminate") {
  2751. // Don't process stanzas that come in after disconnect
  2752. if (this.disconnecting) {
  2753. return;
  2754. }
  2755. // an error occurred
  2756. cond = elem.getAttribute("condition");
  2757. conflict = elem.getElementsByTagName("conflict");
  2758. if (cond !== null) {
  2759. if (cond == "remote-stream-error" && conflict.length > 0) {
  2760. cond = "conflict";
  2761. }
  2762. this._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
  2763. } else {
  2764. this._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown");
  2765. }
  2766. this._doDisconnect(cond);
  2767. return;
  2768. }
  2769. // send each incoming stanza through the handler chain
  2770. var that = this;
  2771. Strophe.forEachChild(elem, null, function (child) {
  2772. var i, newList;
  2773. // process handlers
  2774. newList = that.handlers;
  2775. that.handlers = [];
  2776. for (i = 0; i < newList.length; i++) {
  2777. var hand = newList[i];
  2778. // encapsulate 'handler.run' not to lose the whole handler list if
  2779. // one of the handlers throws an exception
  2780. try {
  2781. if (hand.isMatch(child) &&
  2782. (that.authenticated || !hand.user)) {
  2783. if (hand.run(child)) {
  2784. that.handlers.push(hand);
  2785. }
  2786. } else {
  2787. that.handlers.push(hand);
  2788. }
  2789. } catch(e) {
  2790. // if the handler throws an exception, we consider it as false
  2791. Strophe.warn('Removing Strophe handlers due to uncaught exception: ' + e.message);
  2792. }
  2793. }
  2794. });
  2795. },
  2796. /** Attribute: mechanisms
  2797. * SASL Mechanisms available for Conncection.
  2798. */
  2799. mechanisms: {},
  2800. /** PrivateFunction: _connect_cb
  2801. * _Private_ handler for initial connection request.
  2802. *
  2803. * This handler is used to process the initial connection request
  2804. * response from the BOSH server. It is used to set up authentication
  2805. * handlers and start the authentication process.
  2806. *
  2807. * SASL authentication will be attempted if available, otherwise
  2808. * the code will fall back to legacy authentication.
  2809. *
  2810. * Parameters:
  2811. * (Strophe.Request) req - The current request.
  2812. * (Function) _callback - low level (xmpp) connect callback function.
  2813. * Useful for plugins with their own xmpp connect callback (when their)
  2814. * want to do something special).
  2815. */
  2816. _connect_cb: function (req, _callback, raw)
  2817. {
  2818. Strophe.info("_connect_cb was called");
  2819. this.connected = true;
  2820. var bodyWrap = this._proto._reqToData(req);
  2821. if (!bodyWrap) { return; }
  2822. if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
  2823. if (bodyWrap.nodeName === this._proto.strip && bodyWrap.childNodes.length) {
  2824. this.xmlInput(bodyWrap.childNodes[0]);
  2825. } else {
  2826. this.xmlInput(bodyWrap);
  2827. }
  2828. }
  2829. if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
  2830. if (raw) {
  2831. this.rawInput(raw);
  2832. } else {
  2833. this.rawInput(Strophe.serialize(bodyWrap));
  2834. }
  2835. }
  2836. var conncheck = this._proto._connect_cb(bodyWrap);
  2837. if (conncheck === Strophe.Status.CONNFAIL) {
  2838. return;
  2839. }
  2840. this._authentication.sasl_scram_sha1 = false;
  2841. this._authentication.sasl_plain = false;
  2842. this._authentication.sasl_digest_md5 = false;
  2843. this._authentication.sasl_anonymous = false;
  2844. this._authentication.legacy_auth = false;
  2845. // Check for the stream:features tag
  2846. var hasFeatures;
  2847. if (bodyWrap.getElementsByTagNameNS) {
  2848. hasFeatures = bodyWrap.getElementsByTagNameNS(Strophe.NS.STREAM, "features").length > 0;
  2849. } else {
  2850. hasFeatures = bodyWrap.getElementsByTagName("stream:features").length > 0 || bodyWrap.getElementsByTagName("features").length > 0;
  2851. }
  2852. var mechanisms = bodyWrap.getElementsByTagName("mechanism");
  2853. var matched = [];
  2854. var i, mech, found_authentication = false;
  2855. if (!hasFeatures) {
  2856. this._proto._no_auth_received(_callback);
  2857. return;
  2858. }
  2859. if (mechanisms.length > 0) {
  2860. for (i = 0; i < mechanisms.length; i++) {
  2861. mech = Strophe.getText(mechanisms[i]);
  2862. if (this.mechanisms[mech]) matched.push(this.mechanisms[mech]);
  2863. }
  2864. }
  2865. this._authentication.legacy_auth =
  2866. bodyWrap.getElementsByTagName("auth").length > 0;
  2867. found_authentication = this._authentication.legacy_auth ||
  2868. matched.length > 0;
  2869. if (!found_authentication) {
  2870. this._proto._no_auth_received(_callback);
  2871. return;
  2872. }
  2873. if (this.do_authentication !== false)
  2874. this.authenticate(matched);
  2875. },
  2876. /** Function: authenticate
  2877. * Set up authentication
  2878. *
  2879. * Contiunues the initial connection request by setting up authentication
  2880. * handlers and start the authentication process.
  2881. *
  2882. * SASL authentication will be attempted if available, otherwise
  2883. * the code will fall back to legacy authentication.
  2884. *
  2885. */
  2886. authenticate: function (matched)
  2887. {
  2888. var i;
  2889. // Sorting matched mechanisms according to priority.
  2890. for (i = 0; i < matched.length - 1; ++i) {
  2891. var higher = i;
  2892. for (var j = i + 1; j < matched.length; ++j) {
  2893. if (matched[j].prototype.priority > matched[higher].prototype.priority) {
  2894. higher = j;
  2895. }
  2896. }
  2897. if (higher != i) {
  2898. var swap = matched[i];
  2899. matched[i] = matched[higher];
  2900. matched[higher] = swap;
  2901. }
  2902. }
  2903. // run each mechanism
  2904. var mechanism_found = false;
  2905. for (i = 0; i < matched.length; ++i) {
  2906. if (!matched[i].test(this)) continue;
  2907. this._sasl_success_handler = this._addSysHandler(
  2908. this._sasl_success_cb.bind(this), null,
  2909. "success", null, null);
  2910. this._sasl_failure_handler = this._addSysHandler(
  2911. this._sasl_failure_cb.bind(this), null,
  2912. "failure", null, null);
  2913. this._sasl_challenge_handler = this._addSysHandler(
  2914. this._sasl_challenge_cb.bind(this), null,
  2915. "challenge", null, null);
  2916. this._sasl_mechanism = new matched[i]();
  2917. this._sasl_mechanism.onStart(this);
  2918. var request_auth_exchange = $build("auth", {
  2919. xmlns: Strophe.NS.SASL,
  2920. mechanism: this._sasl_mechanism.name
  2921. });
  2922. if (this._sasl_mechanism.isClientFirst) {
  2923. var response = this._sasl_mechanism.onChallenge(this, null);
  2924. request_auth_exchange.t(Base64.encode(response));
  2925. }
  2926. this.send(request_auth_exchange.tree());
  2927. mechanism_found = true;
  2928. break;
  2929. }
  2930. if (!mechanism_found) {
  2931. // if none of the mechanism worked
  2932. if (Strophe.getNodeFromJid(this.jid) === null) {
  2933. // we don't have a node, which is required for non-anonymous
  2934. // client connections
  2935. this._changeConnectStatus(Strophe.Status.CONNFAIL,
  2936. 'x-strophe-bad-non-anon-jid');
  2937. this.disconnect('x-strophe-bad-non-anon-jid');
  2938. } else {
  2939. // fall back to legacy authentication
  2940. this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
  2941. this._addSysHandler(this._auth1_cb.bind(this), null, null,
  2942. null, "_auth_1");
  2943. this.send($iq({
  2944. type: "get",
  2945. to: this.domain,
  2946. id: "_auth_1"
  2947. }).c("query", {
  2948. xmlns: Strophe.NS.AUTH
  2949. }).c("username", {}).t(Strophe.getNodeFromJid(this.jid)).tree());
  2950. }
  2951. }
  2952. },
  2953. _sasl_challenge_cb: function(elem) {
  2954. var challenge = Base64.decode(Strophe.getText(elem));
  2955. var response = this._sasl_mechanism.onChallenge(this, challenge);
  2956. var stanza = $build('response', {
  2957. xmlns: Strophe.NS.SASL
  2958. });
  2959. if (response !== "") {
  2960. stanza.t(Base64.encode(response));
  2961. }
  2962. this.send(stanza.tree());
  2963. return true;
  2964. },
  2965. /** PrivateFunction: _auth1_cb
  2966. * _Private_ handler for legacy authentication.
  2967. *
  2968. * This handler is called in response to the initial <iq type='get'/>
  2969. * for legacy authentication. It builds an authentication <iq/> and
  2970. * sends it, creating a handler (calling back to _auth2_cb()) to
  2971. * handle the result
  2972. *
  2973. * Parameters:
  2974. * (XMLElement) elem - The stanza that triggered the callback.
  2975. *
  2976. * Returns:
  2977. * false to remove the handler.
  2978. */
  2979. /* jshint unused:false */
  2980. _auth1_cb: function (elem)
  2981. {
  2982. // build plaintext auth iq
  2983. var iq = $iq({type: "set", id: "_auth_2"})
  2984. .c('query', {xmlns: Strophe.NS.AUTH})
  2985. .c('username', {}).t(Strophe.getNodeFromJid(this.jid))
  2986. .up()
  2987. .c('password').t(this.pass);
  2988. if (!Strophe.getResourceFromJid(this.jid)) {
  2989. // since the user has not supplied a resource, we pick
  2990. // a default one here. unlike other auth methods, the server
  2991. // cannot do this for us.
  2992. this.jid = Strophe.getBareJidFromJid(this.jid) + '/strophe';
  2993. }
  2994. iq.up().c('resource', {}).t(Strophe.getResourceFromJid(this.jid));
  2995. this._addSysHandler(this._auth2_cb.bind(this), null,
  2996. null, null, "_auth_2");
  2997. this.send(iq.tree());
  2998. return false;
  2999. },
  3000. /* jshint unused:true */
  3001. /** PrivateFunction: _sasl_success_cb
  3002. * _Private_ handler for succesful SASL authentication.
  3003. *
  3004. * Parameters:
  3005. * (XMLElement) elem - The matching stanza.
  3006. *
  3007. * Returns:
  3008. * false to remove the handler.
  3009. */
  3010. _sasl_success_cb: function (elem)
  3011. {
  3012. if (this._sasl_data["server-signature"]) {
  3013. var serverSignature;
  3014. var success = Base64.decode(Strophe.getText(elem));
  3015. var attribMatch = /([a-z]+)=([^,]+)(,|$)/;
  3016. var matches = success.match(attribMatch);
  3017. if (matches[1] == "v") {
  3018. serverSignature = matches[2];
  3019. }
  3020. if (serverSignature != this._sasl_data["server-signature"]) {
  3021. // remove old handlers
  3022. this.deleteHandler(this._sasl_failure_handler);
  3023. this._sasl_failure_handler = null;
  3024. if (this._sasl_challenge_handler) {
  3025. this.deleteHandler(this._sasl_challenge_handler);
  3026. this._sasl_challenge_handler = null;
  3027. }
  3028. this._sasl_data = {};
  3029. return this._sasl_failure_cb(null);
  3030. }
  3031. }
  3032. Strophe.info("SASL authentication succeeded.");
  3033. if(this._sasl_mechanism)
  3034. this._sasl_mechanism.onSuccess();
  3035. // remove old handlers
  3036. this.deleteHandler(this._sasl_failure_handler);
  3037. this._sasl_failure_handler = null;
  3038. if (this._sasl_challenge_handler) {
  3039. this.deleteHandler(this._sasl_challenge_handler);
  3040. this._sasl_challenge_handler = null;
  3041. }
  3042. var streamfeature_handlers = [];
  3043. var wrapper = function(handlers, elem) {
  3044. while (handlers.length) {
  3045. this.deleteHandler(handlers.pop());
  3046. }
  3047. this._sasl_auth1_cb.bind(this)(elem);
  3048. return false;
  3049. };
  3050. streamfeature_handlers.push(this._addSysHandler(function(elem) {
  3051. wrapper.bind(this)(streamfeature_handlers, elem);
  3052. }.bind(this), null, "stream:features", null, null));
  3053. streamfeature_handlers.push(this._addSysHandler(function(elem) {
  3054. wrapper.bind(this)(streamfeature_handlers, elem);
  3055. }.bind(this), Strophe.NS.STREAM, "features", null, null));
  3056. // we must send an xmpp:restart now
  3057. this._sendRestart();
  3058. return false;
  3059. },
  3060. /** PrivateFunction: _sasl_auth1_cb
  3061. * _Private_ handler to start stream binding.
  3062. *
  3063. * Parameters:
  3064. * (XMLElement) elem - The matching stanza.
  3065. *
  3066. * Returns:
  3067. * false to remove the handler.
  3068. */
  3069. _sasl_auth1_cb: function (elem)
  3070. {
  3071. // save stream:features for future usage
  3072. this.features = elem;
  3073. var i, child;
  3074. for (i = 0; i < elem.childNodes.length; i++) {
  3075. child = elem.childNodes[i];
  3076. if (child.nodeName == 'bind') {
  3077. this.do_bind = true;
  3078. }
  3079. if (child.nodeName == 'session') {
  3080. this.do_session = true;
  3081. }
  3082. }
  3083. if (!this.do_bind) {
  3084. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
  3085. return false;
  3086. } else {
  3087. this._addSysHandler(this._sasl_bind_cb.bind(this), null, null,
  3088. null, "_bind_auth_2");
  3089. var resource = Strophe.getResourceFromJid(this.jid);
  3090. if (resource) {
  3091. this.send($iq({type: "set", id: "_bind_auth_2"})
  3092. .c('bind', {xmlns: Strophe.NS.BIND})
  3093. .c('resource', {}).t(resource).tree());
  3094. } else {
  3095. this.send($iq({type: "set", id: "_bind_auth_2"})
  3096. .c('bind', {xmlns: Strophe.NS.BIND})
  3097. .tree());
  3098. }
  3099. }
  3100. return false;
  3101. },
  3102. /** PrivateFunction: _sasl_bind_cb
  3103. * _Private_ handler for binding result and session start.
  3104. *
  3105. * Parameters:
  3106. * (XMLElement) elem - The matching stanza.
  3107. *
  3108. * Returns:
  3109. * false to remove the handler.
  3110. */
  3111. _sasl_bind_cb: function (elem)
  3112. {
  3113. if (elem.getAttribute("type") == "error") {
  3114. Strophe.info("SASL binding failed.");
  3115. var conflict = elem.getElementsByTagName("conflict"), condition;
  3116. if (conflict.length > 0) {
  3117. condition = 'conflict';
  3118. }
  3119. this._changeConnectStatus(Strophe.Status.AUTHFAIL, condition);
  3120. return false;
  3121. }
  3122. // TODO - need to grab errors
  3123. var bind = elem.getElementsByTagName("bind");
  3124. var jidNode;
  3125. if (bind.length > 0) {
  3126. // Grab jid
  3127. jidNode = bind[0].getElementsByTagName("jid");
  3128. if (jidNode.length > 0) {
  3129. this.jid = Strophe.getText(jidNode[0]);
  3130. if (this.do_session) {
  3131. this._addSysHandler(this._sasl_session_cb.bind(this),
  3132. null, null, null, "_session_auth_2");
  3133. this.send($iq({type: "set", id: "_session_auth_2"})
  3134. .c('session', {xmlns: Strophe.NS.SESSION})
  3135. .tree());
  3136. } else {
  3137. this.authenticated = true;
  3138. this._changeConnectStatus(Strophe.Status.CONNECTED, null);
  3139. }
  3140. }
  3141. } else {
  3142. Strophe.info("SASL binding failed.");
  3143. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
  3144. return false;
  3145. }
  3146. },
  3147. /** PrivateFunction: _sasl_session_cb
  3148. * _Private_ handler to finish successful SASL connection.
  3149. *
  3150. * This sets Connection.authenticated to true on success, which
  3151. * starts the processing of user handlers.
  3152. *
  3153. * Parameters:
  3154. * (XMLElement) elem - The matching stanza.
  3155. *
  3156. * Returns:
  3157. * false to remove the handler.
  3158. */
  3159. _sasl_session_cb: function (elem)
  3160. {
  3161. if (elem.getAttribute("type") == "result") {
  3162. this.authenticated = true;
  3163. this._changeConnectStatus(Strophe.Status.CONNECTED, null);
  3164. } else if (elem.getAttribute("type") == "error") {
  3165. Strophe.info("Session creation failed.");
  3166. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
  3167. return false;
  3168. }
  3169. return false;
  3170. },
  3171. /** PrivateFunction: _sasl_failure_cb
  3172. * _Private_ handler for SASL authentication failure.
  3173. *
  3174. * Parameters:
  3175. * (XMLElement) elem - The matching stanza.
  3176. *
  3177. * Returns:
  3178. * false to remove the handler.
  3179. */
  3180. /* jshint unused:false */
  3181. _sasl_failure_cb: function (elem)
  3182. {
  3183. // delete unneeded handlers
  3184. if (this._sasl_success_handler) {
  3185. this.deleteHandler(this._sasl_success_handler);
  3186. this._sasl_success_handler = null;
  3187. }
  3188. if (this._sasl_challenge_handler) {
  3189. this.deleteHandler(this._sasl_challenge_handler);
  3190. this._sasl_challenge_handler = null;
  3191. }
  3192. if(this._sasl_mechanism)
  3193. this._sasl_mechanism.onFailure();
  3194. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
  3195. return false;
  3196. },
  3197. /* jshint unused:true */
  3198. /** PrivateFunction: _auth2_cb
  3199. * _Private_ handler to finish legacy authentication.
  3200. *
  3201. * This handler is called when the result from the jabber:iq:auth
  3202. * <iq/> stanza is returned.
  3203. *
  3204. * Parameters:
  3205. * (XMLElement) elem - The stanza that triggered the callback.
  3206. *
  3207. * Returns:
  3208. * false to remove the handler.
  3209. */
  3210. _auth2_cb: function (elem)
  3211. {
  3212. if (elem.getAttribute("type") == "result") {
  3213. this.authenticated = true;
  3214. this._changeConnectStatus(Strophe.Status.CONNECTED, null);
  3215. } else if (elem.getAttribute("type") == "error") {
  3216. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
  3217. this.disconnect('authentication failed');
  3218. }
  3219. return false;
  3220. },
  3221. /** PrivateFunction: _addSysTimedHandler
  3222. * _Private_ function to add a system level timed handler.
  3223. *
  3224. * This function is used to add a Strophe.TimedHandler for the
  3225. * library code. System timed handlers are allowed to run before
  3226. * authentication is complete.
  3227. *
  3228. * Parameters:
  3229. * (Integer) period - The period of the handler.
  3230. * (Function) handler - The callback function.
  3231. */
  3232. _addSysTimedHandler: function (period, handler)
  3233. {
  3234. var thand = new Strophe.TimedHandler(period, handler);
  3235. thand.user = false;
  3236. this.addTimeds.push(thand);
  3237. return thand;
  3238. },
  3239. /** PrivateFunction: _addSysHandler
  3240. * _Private_ function to add a system level stanza handler.
  3241. *
  3242. * This function is used to add a Strophe.Handler for the
  3243. * library code. System stanza handlers are allowed to run before
  3244. * authentication is complete.
  3245. *
  3246. * Parameters:
  3247. * (Function) handler - The callback function.
  3248. * (String) ns - The namespace to match.
  3249. * (String) name - The stanza name to match.
  3250. * (String) type - The stanza type attribute to match.
  3251. * (String) id - The stanza id attribute to match.
  3252. */
  3253. _addSysHandler: function (handler, ns, name, type, id)
  3254. {
  3255. var hand = new Strophe.Handler(handler, ns, name, type, id);
  3256. hand.user = false;
  3257. this.addHandlers.push(hand);
  3258. return hand;
  3259. },
  3260. /** PrivateFunction: _onDisconnectTimeout
  3261. * _Private_ timeout handler for handling non-graceful disconnection.
  3262. *
  3263. * If the graceful disconnect process does not complete within the
  3264. * time allotted, this handler finishes the disconnect anyway.
  3265. *
  3266. * Returns:
  3267. * false to remove the handler.
  3268. */
  3269. _onDisconnectTimeout: function ()
  3270. {
  3271. Strophe.info("_onDisconnectTimeout was called");
  3272. this._proto._onDisconnectTimeout();
  3273. // actually disconnect
  3274. this._doDisconnect();
  3275. return false;
  3276. },
  3277. /** PrivateFunction: _onIdle
  3278. * _Private_ handler to process events during idle cycle.
  3279. *
  3280. * This handler is called every 100ms to fire timed handlers that
  3281. * are ready and keep poll requests going.
  3282. */
  3283. _onIdle: function ()
  3284. {
  3285. var i, thand, since, newList;
  3286. // add timed handlers scheduled for addition
  3287. // NOTE: we add before remove in the case a timed handler is
  3288. // added and then deleted before the next _onIdle() call.
  3289. while (this.addTimeds.length > 0) {
  3290. this.timedHandlers.push(this.addTimeds.pop());
  3291. }
  3292. // remove timed handlers that have been scheduled for deletion
  3293. while (this.removeTimeds.length > 0) {
  3294. thand = this.removeTimeds.pop();
  3295. i = this.timedHandlers.indexOf(thand);
  3296. if (i >= 0) {
  3297. this.timedHandlers.splice(i, 1);
  3298. }
  3299. }
  3300. // call ready timed handlers
  3301. var now = new Date().getTime();
  3302. newList = [];
  3303. for (i = 0; i < this.timedHandlers.length; i++) {
  3304. thand = this.timedHandlers[i];
  3305. if (this.authenticated || !thand.user) {
  3306. since = thand.lastCalled + thand.period;
  3307. if (since - now <= 0) {
  3308. if (thand.run()) {
  3309. newList.push(thand);
  3310. }
  3311. } else {
  3312. newList.push(thand);
  3313. }
  3314. }
  3315. }
  3316. this.timedHandlers = newList;
  3317. clearTimeout(this._idleTimeout);
  3318. this._proto._onIdle();
  3319. // reactivate the timer only if connected
  3320. if (this.connected) {
  3321. this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
  3322. }
  3323. }
  3324. };
  3325. /** Class: Strophe.SASLMechanism
  3326. *
  3327. * encapsulates SASL authentication mechanisms.
  3328. *
  3329. * User code may override the priority for each mechanism or disable it completely.
  3330. * See <priority> for information about changing priority and <test> for informatian on
  3331. * how to disable a mechanism.
  3332. *
  3333. * By default, all mechanisms are enabled and the priorities are
  3334. *
  3335. * SCRAM-SHA1 - 40
  3336. * DIGEST-MD5 - 30
  3337. * Plain - 20
  3338. */
  3339. /**
  3340. * PrivateConstructor: Strophe.SASLMechanism
  3341. * SASL auth mechanism abstraction.
  3342. *
  3343. * Parameters:
  3344. * (String) name - SASL Mechanism name.
  3345. * (Boolean) isClientFirst - If client should send response first without challenge.
  3346. * (Number) priority - Priority.
  3347. *
  3348. * Returns:
  3349. * A new Strophe.SASLMechanism object.
  3350. */
  3351. Strophe.SASLMechanism = function(name, isClientFirst, priority) {
  3352. /** PrivateVariable: name
  3353. * Mechanism name.
  3354. */
  3355. this.name = name;
  3356. /** PrivateVariable: isClientFirst
  3357. * If client sends response without initial server challenge.
  3358. */
  3359. this.isClientFirst = isClientFirst;
  3360. /** Variable: priority
  3361. * Determines which <SASLMechanism> is chosen for authentication (Higher is better).
  3362. * Users may override this to prioritize mechanisms differently.
  3363. *
  3364. * In the default configuration the priorities are
  3365. *
  3366. * SCRAM-SHA1 - 40
  3367. * DIGEST-MD5 - 30
  3368. * Plain - 20
  3369. *
  3370. * Example: (This will cause Strophe to choose the mechanism that the server sent first)
  3371. *
  3372. * > Strophe.SASLMD5.priority = Strophe.SASLSHA1.priority;
  3373. *
  3374. * See <SASL mechanisms> for a list of available mechanisms.
  3375. *
  3376. */
  3377. this.priority = priority;
  3378. };
  3379. Strophe.SASLMechanism.prototype = {
  3380. /**
  3381. * Function: test
  3382. * Checks if mechanism able to run.
  3383. * To disable a mechanism, make this return false;
  3384. *
  3385. * To disable plain authentication run
  3386. * > Strophe.SASLPlain.test = function() {
  3387. * > return false;
  3388. * > }
  3389. *
  3390. * See <SASL mechanisms> for a list of available mechanisms.
  3391. *
  3392. * Parameters:
  3393. * (Strophe.Connection) connection - Target Connection.
  3394. *
  3395. * Returns:
  3396. * (Boolean) If mechanism was able to run.
  3397. */
  3398. /* jshint unused:false */
  3399. test: function(connection) {
  3400. return true;
  3401. },
  3402. /* jshint unused:true */
  3403. /** PrivateFunction: onStart
  3404. * Called before starting mechanism on some connection.
  3405. *
  3406. * Parameters:
  3407. * (Strophe.Connection) connection - Target Connection.
  3408. */
  3409. onStart: function(connection)
  3410. {
  3411. this._connection = connection;
  3412. },
  3413. /** PrivateFunction: onChallenge
  3414. * Called by protocol implementation on incoming challenge. If client is
  3415. * first (isClientFirst == true) challenge will be null on the first call.
  3416. *
  3417. * Parameters:
  3418. * (Strophe.Connection) connection - Target Connection.
  3419. * (String) challenge - current challenge to handle.
  3420. *
  3421. * Returns:
  3422. * (String) Mechanism response.
  3423. */
  3424. /* jshint unused:false */
  3425. onChallenge: function(connection, challenge) {
  3426. throw new Error("You should implement challenge handling!");
  3427. },
  3428. /* jshint unused:true */
  3429. /** PrivateFunction: onFailure
  3430. * Protocol informs mechanism implementation about SASL failure.
  3431. */
  3432. onFailure: function() {
  3433. this._connection = null;
  3434. },
  3435. /** PrivateFunction: onSuccess
  3436. * Protocol informs mechanism implementation about SASL success.
  3437. */
  3438. onSuccess: function() {
  3439. this._connection = null;
  3440. }
  3441. };
  3442. /** Constants: SASL mechanisms
  3443. * Available authentication mechanisms
  3444. *
  3445. * Strophe.SASLAnonymous - SASL Anonymous authentication.
  3446. * Strophe.SASLPlain - SASL Plain authentication.
  3447. * Strophe.SASLMD5 - SASL Digest-MD5 authentication
  3448. * Strophe.SASLSHA1 - SASL SCRAM-SHA1 authentication
  3449. */
  3450. // Building SASL callbacks
  3451. /** PrivateConstructor: SASLAnonymous
  3452. * SASL Anonymous authentication.
  3453. */
  3454. Strophe.SASLAnonymous = function() {};
  3455. Strophe.SASLAnonymous.prototype = new Strophe.SASLMechanism("ANONYMOUS", false, 10);
  3456. Strophe.SASLAnonymous.test = function(connection) {
  3457. return connection.authcid === null;
  3458. };
  3459. Strophe.Connection.prototype.mechanisms[Strophe.SASLAnonymous.prototype.name] = Strophe.SASLAnonymous;
  3460. /** PrivateConstructor: SASLPlain
  3461. * SASL Plain authentication.
  3462. */
  3463. Strophe.SASLPlain = function() {};
  3464. Strophe.SASLPlain.prototype = new Strophe.SASLMechanism("PLAIN", true, 20);
  3465. Strophe.SASLPlain.test = function(connection) {
  3466. return connection.authcid !== null;
  3467. };
  3468. Strophe.SASLPlain.prototype.onChallenge = function(connection) {
  3469. var auth_str = connection.authzid;
  3470. auth_str = auth_str + "\u0000";
  3471. auth_str = auth_str + connection.authcid;
  3472. auth_str = auth_str + "\u0000";
  3473. auth_str = auth_str + connection.pass;
  3474. return auth_str;
  3475. };
  3476. Strophe.Connection.prototype.mechanisms[Strophe.SASLPlain.prototype.name] = Strophe.SASLPlain;
  3477. /** PrivateConstructor: SASLSHA1
  3478. * SASL SCRAM SHA 1 authentication.
  3479. */
  3480. Strophe.SASLSHA1 = function() {};
  3481. /* TEST:
  3482. * This is a simple example of a SCRAM-SHA-1 authentication exchange
  3483. * when the client doesn't support channel bindings (username 'user' and
  3484. * password 'pencil' are used):
  3485. *
  3486. * C: n,,n=user,r=fyko+d2lbbFgONRv9qkxdawL
  3487. * S: r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,
  3488. * i=4096
  3489. * C: c=biws,r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,
  3490. * p=v0X8v3Bz2T0CJGbJQyF0X+HI4Ts=
  3491. * S: v=rmF9pqV8S7suAoZWja4dJRkFsKQ=
  3492. *
  3493. */
  3494. Strophe.SASLSHA1.prototype = new Strophe.SASLMechanism("SCRAM-SHA-1", true, 40);
  3495. Strophe.SASLSHA1.test = function(connection) {
  3496. return connection.authcid !== null;
  3497. };
  3498. Strophe.SASLSHA1.prototype.onChallenge = function(connection, challenge, test_cnonce) {
  3499. var cnonce = test_cnonce || MD5.hexdigest(Math.random() * 1234567890);
  3500. var auth_str = "n=" + connection.authcid;
  3501. auth_str += ",r=";
  3502. auth_str += cnonce;
  3503. connection._sasl_data.cnonce = cnonce;
  3504. connection._sasl_data["client-first-message-bare"] = auth_str;
  3505. auth_str = "n,," + auth_str;
  3506. this.onChallenge = function (connection, challenge)
  3507. {
  3508. var nonce, salt, iter, Hi, U, U_old, i, k;
  3509. var clientKey, serverKey, clientSignature;
  3510. var responseText = "c=biws,";
  3511. var authMessage = connection._sasl_data["client-first-message-bare"] + "," +
  3512. challenge + ",";
  3513. var cnonce = connection._sasl_data.cnonce;
  3514. var attribMatch = /([a-z]+)=([^,]+)(,|$)/;
  3515. while (challenge.match(attribMatch)) {
  3516. var matches = challenge.match(attribMatch);
  3517. challenge = challenge.replace(matches[0], "");
  3518. switch (matches[1]) {
  3519. case "r":
  3520. nonce = matches[2];
  3521. break;
  3522. case "s":
  3523. salt = matches[2];
  3524. break;
  3525. case "i":
  3526. iter = matches[2];
  3527. break;
  3528. }
  3529. }
  3530. if (nonce.substr(0, cnonce.length) !== cnonce) {
  3531. connection._sasl_data = {};
  3532. return connection._sasl_failure_cb();
  3533. }
  3534. responseText += "r=" + nonce;
  3535. authMessage += responseText;
  3536. salt = Base64.decode(salt);
  3537. salt += "\x00\x00\x00\x01";
  3538. Hi = U_old = SHA1.core_hmac_sha1(connection.pass, salt);
  3539. for (i = 1; i < iter; i++) {
  3540. U = SHA1.core_hmac_sha1(connection.pass, SHA1.binb2str(U_old));
  3541. for (k = 0; k < 5; k++) {
  3542. Hi[k] ^= U[k];
  3543. }
  3544. U_old = U;
  3545. }
  3546. Hi = SHA1.binb2str(Hi);
  3547. clientKey = SHA1.core_hmac_sha1(Hi, "Client Key");
  3548. serverKey = SHA1.str_hmac_sha1(Hi, "Server Key");
  3549. clientSignature = SHA1.core_hmac_sha1(SHA1.str_sha1(SHA1.binb2str(clientKey)), authMessage);
  3550. connection._sasl_data["server-signature"] = SHA1.b64_hmac_sha1(serverKey, authMessage);
  3551. for (k = 0; k < 5; k++) {
  3552. clientKey[k] ^= clientSignature[k];
  3553. }
  3554. responseText += ",p=" + Base64.encode(SHA1.binb2str(clientKey));
  3555. return responseText;
  3556. }.bind(this);
  3557. return auth_str;
  3558. };
  3559. Strophe.Connection.prototype.mechanisms[Strophe.SASLSHA1.prototype.name] = Strophe.SASLSHA1;
  3560. /** PrivateConstructor: SASLMD5
  3561. * SASL DIGEST MD5 authentication.
  3562. */
  3563. Strophe.SASLMD5 = function() {};
  3564. Strophe.SASLMD5.prototype = new Strophe.SASLMechanism("DIGEST-MD5", false, 30);
  3565. Strophe.SASLMD5.test = function(connection) {
  3566. return connection.authcid !== null;
  3567. };
  3568. /** PrivateFunction: _quote
  3569. * _Private_ utility function to backslash escape and quote strings.
  3570. *
  3571. * Parameters:
  3572. * (String) str - The string to be quoted.
  3573. *
  3574. * Returns:
  3575. * quoted string
  3576. */
  3577. Strophe.SASLMD5.prototype._quote = function (str)
  3578. {
  3579. return '"' + str.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"';
  3580. //" end string workaround for emacs
  3581. };
  3582. Strophe.SASLMD5.prototype.onChallenge = function(connection, challenge, test_cnonce) {
  3583. var attribMatch = /([a-z]+)=("[^"]+"|[^,"]+)(?:,|$)/;
  3584. var cnonce = test_cnonce || MD5.hexdigest("" + (Math.random() * 1234567890));
  3585. var realm = "";
  3586. var host = null;
  3587. var nonce = "";
  3588. var qop = "";
  3589. var matches;
  3590. while (challenge.match(attribMatch)) {
  3591. matches = challenge.match(attribMatch);
  3592. challenge = challenge.replace(matches[0], "");
  3593. matches[2] = matches[2].replace(/^"(.+)"$/, "$1");
  3594. switch (matches[1]) {
  3595. case "realm":
  3596. realm = matches[2];
  3597. break;
  3598. case "nonce":
  3599. nonce = matches[2];
  3600. break;
  3601. case "qop":
  3602. qop = matches[2];
  3603. break;
  3604. case "host":
  3605. host = matches[2];
  3606. break;
  3607. }
  3608. }
  3609. var digest_uri = connection.servtype + "/" + connection.domain;
  3610. if (host !== null) {
  3611. digest_uri = digest_uri + "/" + host;
  3612. }
  3613. var A1 = MD5.hash(connection.authcid +
  3614. ":" + realm + ":" + this._connection.pass) +
  3615. ":" + nonce + ":" + cnonce;
  3616. var A2 = 'AUTHENTICATE:' + digest_uri;
  3617. var responseText = "";
  3618. responseText += 'charset=utf-8,';
  3619. responseText += 'username=' +
  3620. this._quote(connection.authcid) + ',';
  3621. responseText += 'realm=' + this._quote(realm) + ',';
  3622. responseText += 'nonce=' + this._quote(nonce) + ',';
  3623. responseText += 'nc=00000001,';
  3624. responseText += 'cnonce=' + this._quote(cnonce) + ',';
  3625. responseText += 'digest-uri=' + this._quote(digest_uri) + ',';
  3626. responseText += 'response=' + MD5.hexdigest(MD5.hexdigest(A1) + ":" +
  3627. nonce + ":00000001:" +
  3628. cnonce + ":auth:" +
  3629. MD5.hexdigest(A2)) + ",";
  3630. responseText += 'qop=auth';
  3631. this.onChallenge = function ()
  3632. {
  3633. return "";
  3634. }.bind(this);
  3635. return responseText;
  3636. };
  3637. Strophe.Connection.prototype.mechanisms[Strophe.SASLMD5.prototype.name] = Strophe.SASLMD5;
  3638. return {
  3639. Strophe: Strophe,
  3640. $build: $build,
  3641. $msg: $msg,
  3642. $iq: $iq,
  3643. $pres: $pres,
  3644. SHA1: SHA1,
  3645. Base64: Base64,
  3646. MD5: MD5,
  3647. };
  3648. }));
  3649. /*
  3650. This program is distributed under the terms of the MIT license.
  3651. Please see the LICENSE file for details.
  3652. Copyright 2006-2008, OGG, LLC
  3653. */
  3654. /* jshint undef: true, unused: true:, noarg: true, latedef: true */
  3655. /* global define, window, setTimeout, clearTimeout, XMLHttpRequest, ActiveXObject, Strophe, $build */
  3656. (function (root, factory) {
  3657. if (typeof define === 'function' && define.amd) {
  3658. define('strophe-bosh', ['strophe-core'], function (core) {
  3659. return factory(
  3660. core.Strophe,
  3661. core.$build
  3662. );
  3663. });
  3664. } else {
  3665. // Browser globals
  3666. return factory(Strophe, $build);
  3667. }
  3668. }(this, function (Strophe, $build) {
  3669. /** PrivateClass: Strophe.Request
  3670. * _Private_ helper class that provides a cross implementation abstraction
  3671. * for a BOSH related XMLHttpRequest.
  3672. *
  3673. * The Strophe.Request class is used internally to encapsulate BOSH request
  3674. * information. It is not meant to be used from user's code.
  3675. */
  3676. /** PrivateConstructor: Strophe.Request
  3677. * Create and initialize a new Strophe.Request object.
  3678. *
  3679. * Parameters:
  3680. * (XMLElement) elem - The XML data to be sent in the request.
  3681. * (Function) func - The function that will be called when the
  3682. * XMLHttpRequest readyState changes.
  3683. * (Integer) rid - The BOSH rid attribute associated with this request.
  3684. * (Integer) sends - The number of times this same request has been
  3685. * sent.
  3686. */
  3687. Strophe.Request = function (elem, func, rid, sends)
  3688. {
  3689. this.id = ++Strophe._requestId;
  3690. this.xmlData = elem;
  3691. this.data = Strophe.serialize(elem);
  3692. // save original function in case we need to make a new request
  3693. // from this one.
  3694. this.origFunc = func;
  3695. this.func = func;
  3696. this.rid = rid;
  3697. this.date = NaN;
  3698. this.sends = sends || 0;
  3699. this.abort = false;
  3700. this.dead = null;
  3701. this.age = function () {
  3702. if (!this.date) { return 0; }
  3703. var now = new Date();
  3704. return (now - this.date) / 1000;
  3705. };
  3706. this.timeDead = function () {
  3707. if (!this.dead) { return 0; }
  3708. var now = new Date();
  3709. return (now - this.dead) / 1000;
  3710. };
  3711. this.xhr = this._newXHR();
  3712. };
  3713. Strophe.Request.prototype = {
  3714. /** PrivateFunction: getResponse
  3715. * Get a response from the underlying XMLHttpRequest.
  3716. *
  3717. * This function attempts to get a response from the request and checks
  3718. * for errors.
  3719. *
  3720. * Throws:
  3721. * "parsererror" - A parser error occured.
  3722. *
  3723. * Returns:
  3724. * The DOM element tree of the response.
  3725. */
  3726. getResponse: function ()
  3727. {
  3728. var node = null;
  3729. if (this.xhr.responseXML && this.xhr.responseXML.documentElement) {
  3730. node = this.xhr.responseXML.documentElement;
  3731. if (node.tagName == "parsererror") {
  3732. Strophe.error("invalid response received");
  3733. Strophe.error("responseText: " + this.xhr.responseText);
  3734. Strophe.error("responseXML: " +
  3735. Strophe.serialize(this.xhr.responseXML));
  3736. throw "parsererror";
  3737. }
  3738. } else if (this.xhr.responseText) {
  3739. Strophe.error("invalid response received");
  3740. Strophe.error("responseText: " + this.xhr.responseText);
  3741. Strophe.error("responseXML: " +
  3742. Strophe.serialize(this.xhr.responseXML));
  3743. }
  3744. return node;
  3745. },
  3746. /** PrivateFunction: _newXHR
  3747. * _Private_ helper function to create XMLHttpRequests.
  3748. *
  3749. * This function creates XMLHttpRequests across all implementations.
  3750. *
  3751. * Returns:
  3752. * A new XMLHttpRequest.
  3753. */
  3754. _newXHR: function ()
  3755. {
  3756. var xhr = null;
  3757. if (window.XMLHttpRequest) {
  3758. xhr = new XMLHttpRequest();
  3759. if (xhr.overrideMimeType) {
  3760. xhr.overrideMimeType("text/xml; charset=utf-8");
  3761. }
  3762. } else if (window.ActiveXObject) {
  3763. xhr = new ActiveXObject("Microsoft.XMLHTTP");
  3764. }
  3765. // use Function.bind() to prepend ourselves as an argument
  3766. xhr.onreadystatechange = this.func.bind(null, this);
  3767. return xhr;
  3768. }
  3769. };
  3770. /** Class: Strophe.Bosh
  3771. * _Private_ helper class that handles BOSH Connections
  3772. *
  3773. * The Strophe.Bosh class is used internally by Strophe.Connection
  3774. * to encapsulate BOSH sessions. It is not meant to be used from user's code.
  3775. */
  3776. /** File: bosh.js
  3777. * A JavaScript library to enable BOSH in Strophejs.
  3778. *
  3779. * this library uses Bidirectional-streams Over Synchronous HTTP (BOSH)
  3780. * to emulate a persistent, stateful, two-way connection to an XMPP server.
  3781. * More information on BOSH can be found in XEP 124.
  3782. */
  3783. /** PrivateConstructor: Strophe.Bosh
  3784. * Create and initialize a Strophe.Bosh object.
  3785. *
  3786. * Parameters:
  3787. * (Strophe.Connection) connection - The Strophe.Connection that will use BOSH.
  3788. *
  3789. * Returns:
  3790. * A new Strophe.Bosh object.
  3791. */
  3792. Strophe.Bosh = function(connection) {
  3793. this._conn = connection;
  3794. /* request id for body tags */
  3795. this.rid = Math.floor(Math.random() * 4294967295);
  3796. /* The current session ID. */
  3797. this.sid = null;
  3798. // default BOSH values
  3799. this.hold = 1;
  3800. this.wait = 60;
  3801. this.window = 5;
  3802. this.errors = 0;
  3803. this._requests = [];
  3804. };
  3805. Strophe.Bosh.prototype = {
  3806. /** Variable: strip
  3807. *
  3808. * BOSH-Connections will have all stanzas wrapped in a <body> tag when
  3809. * passed to <Strophe.Connection.xmlInput> or <Strophe.Connection.xmlOutput>.
  3810. * To strip this tag, User code can set <Strophe.Bosh.strip> to "body":
  3811. *
  3812. * > Strophe.Bosh.prototype.strip = "body";
  3813. *
  3814. * This will enable stripping of the body tag in both
  3815. * <Strophe.Connection.xmlInput> and <Strophe.Connection.xmlOutput>.
  3816. */
  3817. strip: null,
  3818. /** PrivateFunction: _buildBody
  3819. * _Private_ helper function to generate the <body/> wrapper for BOSH.
  3820. *
  3821. * Returns:
  3822. * A Strophe.Builder with a <body/> element.
  3823. */
  3824. _buildBody: function ()
  3825. {
  3826. var bodyWrap = $build('body', {
  3827. rid: this.rid++,
  3828. xmlns: Strophe.NS.HTTPBIND
  3829. });
  3830. if (this.sid !== null) {
  3831. bodyWrap.attrs({sid: this.sid});
  3832. }
  3833. if (this._conn.options.keepalive) {
  3834. this._cacheSession();
  3835. }
  3836. return bodyWrap;
  3837. },
  3838. /** PrivateFunction: _reset
  3839. * Reset the connection.
  3840. *
  3841. * This function is called by the reset function of the Strophe Connection
  3842. */
  3843. _reset: function ()
  3844. {
  3845. this.rid = Math.floor(Math.random() * 4294967295);
  3846. this.sid = null;
  3847. this.errors = 0;
  3848. window.sessionStorage.removeItem('strophe-bosh-session');
  3849. },
  3850. /** PrivateFunction: _connect
  3851. * _Private_ function that initializes the BOSH connection.
  3852. *
  3853. * Creates and sends the Request that initializes the BOSH connection.
  3854. */
  3855. _connect: function (wait, hold, route)
  3856. {
  3857. this.wait = wait || this.wait;
  3858. this.hold = hold || this.hold;
  3859. this.errors = 0;
  3860. // build the body tag
  3861. var body = this._buildBody().attrs({
  3862. to: this._conn.domain,
  3863. "xml:lang": "en",
  3864. wait: this.wait,
  3865. hold: this.hold,
  3866. content: "text/xml; charset=utf-8",
  3867. ver: "1.6",
  3868. "xmpp:version": "1.0",
  3869. "xmlns:xmpp": Strophe.NS.BOSH
  3870. });
  3871. if(route){
  3872. body.attrs({
  3873. route: route
  3874. });
  3875. }
  3876. var _connect_cb = this._conn._connect_cb;
  3877. this._requests.push(
  3878. new Strophe.Request(body.tree(),
  3879. this._onRequestStateChange.bind(
  3880. this, _connect_cb.bind(this._conn)),
  3881. body.tree().getAttribute("rid")));
  3882. this._throttledRequestHandler();
  3883. },
  3884. /** PrivateFunction: _attach
  3885. * Attach to an already created and authenticated BOSH session.
  3886. *
  3887. * This function is provided to allow Strophe to attach to BOSH
  3888. * sessions which have been created externally, perhaps by a Web
  3889. * application. This is often used to support auto-login type features
  3890. * without putting user credentials into the page.
  3891. *
  3892. * Parameters:
  3893. * (String) jid - The full JID that is bound by the session.
  3894. * (String) sid - The SID of the BOSH session.
  3895. * (String) rid - The current RID of the BOSH session. This RID
  3896. * will be used by the next request.
  3897. * (Function) callback The connect callback function.
  3898. * (Integer) wait - The optional HTTPBIND wait value. This is the
  3899. * time the server will wait before returning an empty result for
  3900. * a request. The default setting of 60 seconds is recommended.
  3901. * Other settings will require tweaks to the Strophe.TIMEOUT value.
  3902. * (Integer) hold - The optional HTTPBIND hold value. This is the
  3903. * number of connections the server will hold at one time. This
  3904. * should almost always be set to 1 (the default).
  3905. * (Integer) wind - The optional HTTBIND window value. This is the
  3906. * allowed range of request ids that are valid. The default is 5.
  3907. */
  3908. _attach: function (jid, sid, rid, callback, wait, hold, wind)
  3909. {
  3910. this._conn.jid = jid;
  3911. this.sid = sid;
  3912. this.rid = rid;
  3913. this._conn.connect_callback = callback;
  3914. this._conn.domain = Strophe.getDomainFromJid(this._conn.jid);
  3915. this._conn.authenticated = true;
  3916. this._conn.connected = true;
  3917. this.wait = wait || this.wait;
  3918. this.hold = hold || this.hold;
  3919. this.window = wind || this.window;
  3920. this._conn._changeConnectStatus(Strophe.Status.ATTACHED, null);
  3921. },
  3922. /** PrivateFunction: _restore
  3923. * Attempt to restore a cached BOSH session
  3924. *
  3925. * Parameters:
  3926. * (String) jid - The full JID that is bound by the session.
  3927. * This parameter is optional but recommended, specifically in cases
  3928. * where prebinded BOSH sessions are used where it's important to know
  3929. * that the right session is being restored.
  3930. * (Function) callback The connect callback function.
  3931. * (Integer) wait - The optional HTTPBIND wait value. This is the
  3932. * time the server will wait before returning an empty result for
  3933. * a request. The default setting of 60 seconds is recommended.
  3934. * Other settings will require tweaks to the Strophe.TIMEOUT value.
  3935. * (Integer) hold - The optional HTTPBIND hold value. This is the
  3936. * number of connections the server will hold at one time. This
  3937. * should almost always be set to 1 (the default).
  3938. * (Integer) wind - The optional HTTBIND window value. This is the
  3939. * allowed range of request ids that are valid. The default is 5.
  3940. */
  3941. _restore: function (jid, callback, wait, hold, wind)
  3942. {
  3943. var session = JSON.parse(window.sessionStorage.getItem('strophe-bosh-session'));
  3944. if (typeof session !== "undefined" &&
  3945. session !== null &&
  3946. session.rid &&
  3947. session.sid &&
  3948. session.jid &&
  3949. (typeof jid === "undefined" || Strophe.getBareJidFromJid(session.jid) == Strophe.getBareJidFromJid(jid)))
  3950. {
  3951. this._conn.restored = true;
  3952. this._attach(session.jid, session.sid, session.rid, callback, wait, hold, wind);
  3953. } else {
  3954. throw { name: "StropheSessionError", message: "_restore: no restoreable session." };
  3955. }
  3956. },
  3957. /** PrivateFunction: _cacheSession
  3958. * _Private_ handler for the beforeunload event.
  3959. *
  3960. * This handler is used to process the Bosh-part of the initial request.
  3961. * Parameters:
  3962. * (Strophe.Request) bodyWrap - The received stanza.
  3963. */
  3964. _cacheSession: function ()
  3965. {
  3966. if (this._conn.authenticated) {
  3967. if (this._conn.jid && this.rid && this.sid) {
  3968. window.sessionStorage.setItem('strophe-bosh-session', JSON.stringify({
  3969. 'jid': this._conn.jid,
  3970. 'rid': this.rid,
  3971. 'sid': this.sid
  3972. }));
  3973. }
  3974. } else {
  3975. window.sessionStorage.removeItem('strophe-bosh-session');
  3976. }
  3977. },
  3978. /** PrivateFunction: _connect_cb
  3979. * _Private_ handler for initial connection request.
  3980. *
  3981. * This handler is used to process the Bosh-part of the initial request.
  3982. * Parameters:
  3983. * (Strophe.Request) bodyWrap - The received stanza.
  3984. */
  3985. _connect_cb: function (bodyWrap)
  3986. {
  3987. var typ = bodyWrap.getAttribute("type");
  3988. var cond, conflict;
  3989. if (typ !== null && typ == "terminate") {
  3990. // an error occurred
  3991. cond = bodyWrap.getAttribute("condition");
  3992. Strophe.error("BOSH-Connection failed: " + cond);
  3993. conflict = bodyWrap.getElementsByTagName("conflict");
  3994. if (cond !== null) {
  3995. if (cond == "remote-stream-error" && conflict.length > 0) {
  3996. cond = "conflict";
  3997. }
  3998. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
  3999. } else {
  4000. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown");
  4001. }
  4002. this._conn._doDisconnect(cond);
  4003. return Strophe.Status.CONNFAIL;
  4004. }
  4005. // check to make sure we don't overwrite these if _connect_cb is
  4006. // called multiple times in the case of missing stream:features
  4007. if (!this.sid) {
  4008. this.sid = bodyWrap.getAttribute("sid");
  4009. }
  4010. var wind = bodyWrap.getAttribute('requests');
  4011. if (wind) { this.window = parseInt(wind, 10); }
  4012. var hold = bodyWrap.getAttribute('hold');
  4013. if (hold) { this.hold = parseInt(hold, 10); }
  4014. var wait = bodyWrap.getAttribute('wait');
  4015. if (wait) { this.wait = parseInt(wait, 10); }
  4016. },
  4017. /** PrivateFunction: _disconnect
  4018. * _Private_ part of Connection.disconnect for Bosh
  4019. *
  4020. * Parameters:
  4021. * (Request) pres - This stanza will be sent before disconnecting.
  4022. */
  4023. _disconnect: function (pres)
  4024. {
  4025. this._sendTerminate(pres);
  4026. },
  4027. /** PrivateFunction: _doDisconnect
  4028. * _Private_ function to disconnect.
  4029. *
  4030. * Resets the SID and RID.
  4031. */
  4032. _doDisconnect: function ()
  4033. {
  4034. this.sid = null;
  4035. this.rid = Math.floor(Math.random() * 4294967295);
  4036. window.sessionStorage.removeItem('strophe-bosh-session');
  4037. },
  4038. /** PrivateFunction: _emptyQueue
  4039. * _Private_ function to check if the Request queue is empty.
  4040. *
  4041. * Returns:
  4042. * True, if there are no Requests queued, False otherwise.
  4043. */
  4044. _emptyQueue: function ()
  4045. {
  4046. return this._requests.length === 0;
  4047. },
  4048. /** PrivateFunction: _hitError
  4049. * _Private_ function to handle the error count.
  4050. *
  4051. * Requests are resent automatically until their error count reaches
  4052. * 5. Each time an error is encountered, this function is called to
  4053. * increment the count and disconnect if the count is too high.
  4054. *
  4055. * Parameters:
  4056. * (Integer) reqStatus - The request status.
  4057. */
  4058. _hitError: function (reqStatus)
  4059. {
  4060. this.errors++;
  4061. Strophe.warn("request errored, status: " + reqStatus +
  4062. ", number of errors: " + this.errors);
  4063. if (this.errors > 4) {
  4064. this._conn._onDisconnectTimeout();
  4065. }
  4066. },
  4067. /** PrivateFunction: _no_auth_received
  4068. *
  4069. * Called on stream start/restart when no stream:features
  4070. * has been received and sends a blank poll request.
  4071. */
  4072. _no_auth_received: function (_callback)
  4073. {
  4074. if (_callback) {
  4075. _callback = _callback.bind(this._conn);
  4076. } else {
  4077. _callback = this._conn._connect_cb.bind(this._conn);
  4078. }
  4079. var body = this._buildBody();
  4080. this._requests.push(
  4081. new Strophe.Request(body.tree(),
  4082. this._onRequestStateChange.bind(
  4083. this, _callback.bind(this._conn)),
  4084. body.tree().getAttribute("rid")));
  4085. this._throttledRequestHandler();
  4086. },
  4087. /** PrivateFunction: _onDisconnectTimeout
  4088. * _Private_ timeout handler for handling non-graceful disconnection.
  4089. *
  4090. * Cancels all remaining Requests and clears the queue.
  4091. */
  4092. _onDisconnectTimeout: function () {
  4093. this._abortAllRequests();
  4094. },
  4095. /** PrivateFunction: _abortAllRequests
  4096. * _Private_ helper function that makes sure all pending requests are aborted.
  4097. */
  4098. _abortAllRequests: function _abortAllRequests() {
  4099. var req;
  4100. while (this._requests.length > 0) {
  4101. req = this._requests.pop();
  4102. req.abort = true;
  4103. req.xhr.abort();
  4104. // jslint complains, but this is fine. setting to empty func
  4105. // is necessary for IE6
  4106. req.xhr.onreadystatechange = function () {}; // jshint ignore:line
  4107. }
  4108. },
  4109. /** PrivateFunction: _onIdle
  4110. * _Private_ handler called by Strophe.Connection._onIdle
  4111. *
  4112. * Sends all queued Requests or polls with empty Request if there are none.
  4113. */
  4114. _onIdle: function () {
  4115. var data = this._conn._data;
  4116. // if no requests are in progress, poll
  4117. if (this._conn.authenticated && this._requests.length === 0 &&
  4118. data.length === 0 && !this._conn.disconnecting) {
  4119. Strophe.info("no requests during idle cycle, sending " +
  4120. "blank request");
  4121. data.push(null);
  4122. }
  4123. if (this._conn.paused) {
  4124. return;
  4125. }
  4126. if (this._requests.length < 2 && data.length > 0) {
  4127. var body = this._buildBody();
  4128. for (var i = 0; i < data.length; i++) {
  4129. if (data[i] !== null) {
  4130. if (data[i] === "restart") {
  4131. body.attrs({
  4132. to: this._conn.domain,
  4133. "xml:lang": "en",
  4134. "xmpp:restart": "true",
  4135. "xmlns:xmpp": Strophe.NS.BOSH
  4136. });
  4137. } else {
  4138. body.cnode(data[i]).up();
  4139. }
  4140. }
  4141. }
  4142. delete this._conn._data;
  4143. this._conn._data = [];
  4144. this._requests.push(
  4145. new Strophe.Request(body.tree(),
  4146. this._onRequestStateChange.bind(
  4147. this, this._conn._dataRecv.bind(this._conn)),
  4148. body.tree().getAttribute("rid")));
  4149. this._throttledRequestHandler();
  4150. }
  4151. if (this._requests.length > 0) {
  4152. var time_elapsed = this._requests[0].age();
  4153. if (this._requests[0].dead !== null) {
  4154. if (this._requests[0].timeDead() >
  4155. Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)) {
  4156. this._throttledRequestHandler();
  4157. }
  4158. }
  4159. if (time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)) {
  4160. Strophe.warn("Request " +
  4161. this._requests[0].id +
  4162. " timed out, over " + Math.floor(Strophe.TIMEOUT * this.wait) +
  4163. " seconds since last activity");
  4164. this._throttledRequestHandler();
  4165. }
  4166. }
  4167. },
  4168. /** PrivateFunction: _onRequestStateChange
  4169. * _Private_ handler for Strophe.Request state changes.
  4170. *
  4171. * This function is called when the XMLHttpRequest readyState changes.
  4172. * It contains a lot of error handling logic for the many ways that
  4173. * requests can fail, and calls the request callback when requests
  4174. * succeed.
  4175. *
  4176. * Parameters:
  4177. * (Function) func - The handler for the request.
  4178. * (Strophe.Request) req - The request that is changing readyState.
  4179. */
  4180. _onRequestStateChange: function (func, req)
  4181. {
  4182. Strophe.debug("request id " + req.id +
  4183. "." + req.sends + " state changed to " +
  4184. req.xhr.readyState);
  4185. if (req.abort) {
  4186. req.abort = false;
  4187. return;
  4188. }
  4189. // request complete
  4190. var reqStatus;
  4191. if (req.xhr.readyState == 4) {
  4192. reqStatus = 0;
  4193. try {
  4194. reqStatus = req.xhr.status;
  4195. } catch (e) {
  4196. // ignore errors from undefined status attribute. works
  4197. // around a browser bug
  4198. }
  4199. if (typeof(reqStatus) == "undefined") {
  4200. reqStatus = 0;
  4201. }
  4202. if (this.disconnecting) {
  4203. if (reqStatus >= 400) {
  4204. this._hitError(reqStatus);
  4205. return;
  4206. }
  4207. }
  4208. var reqIs0 = (this._requests[0] == req);
  4209. var reqIs1 = (this._requests[1] == req);
  4210. if ((reqStatus > 0 && reqStatus < 500) || req.sends > 5) {
  4211. // remove from internal queue
  4212. this._removeRequest(req);
  4213. Strophe.debug("request id " +
  4214. req.id +
  4215. " should now be removed");
  4216. }
  4217. // request succeeded
  4218. if (reqStatus == 200) {
  4219. // if request 1 finished, or request 0 finished and request
  4220. // 1 is over Strophe.SECONDARY_TIMEOUT seconds old, we need to
  4221. // restart the other - both will be in the first spot, as the
  4222. // completed request has been removed from the queue already
  4223. if (reqIs1 ||
  4224. (reqIs0 && this._requests.length > 0 &&
  4225. this._requests[0].age() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait))) {
  4226. this._restartRequest(0);
  4227. }
  4228. // call handler
  4229. Strophe.debug("request id " +
  4230. req.id + "." +
  4231. req.sends + " got 200");
  4232. func(req);
  4233. this.errors = 0;
  4234. } else {
  4235. Strophe.error("request id " +
  4236. req.id + "." +
  4237. req.sends + " error " + reqStatus +
  4238. " happened");
  4239. if (reqStatus === 0 ||
  4240. (reqStatus >= 400 && reqStatus < 600) ||
  4241. reqStatus >= 12000) {
  4242. this._hitError(reqStatus);
  4243. if (reqStatus >= 400 && reqStatus < 500) {
  4244. this._conn._changeConnectStatus(Strophe.Status.DISCONNECTING, null);
  4245. this._conn._doDisconnect();
  4246. }
  4247. }
  4248. }
  4249. if (!((reqStatus > 0 && reqStatus < 500) ||
  4250. req.sends > 5)) {
  4251. this._throttledRequestHandler();
  4252. }
  4253. }
  4254. },
  4255. /** PrivateFunction: _processRequest
  4256. * _Private_ function to process a request in the queue.
  4257. *
  4258. * This function takes requests off the queue and sends them and
  4259. * restarts dead requests.
  4260. *
  4261. * Parameters:
  4262. * (Integer) i - The index of the request in the queue.
  4263. */
  4264. _processRequest: function (i)
  4265. {
  4266. var self = this;
  4267. var req = this._requests[i];
  4268. var reqStatus = -1;
  4269. try {
  4270. if (req.xhr.readyState == 4) {
  4271. reqStatus = req.xhr.status;
  4272. }
  4273. } catch (e) {
  4274. Strophe.error("caught an error in _requests[" + i +
  4275. "], reqStatus: " + reqStatus);
  4276. }
  4277. if (typeof(reqStatus) == "undefined") {
  4278. reqStatus = -1;
  4279. }
  4280. // make sure we limit the number of retries
  4281. if (req.sends > this._conn.maxRetries) {
  4282. this._conn._onDisconnectTimeout();
  4283. return;
  4284. }
  4285. var time_elapsed = req.age();
  4286. var primaryTimeout = (!isNaN(time_elapsed) &&
  4287. time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait));
  4288. var secondaryTimeout = (req.dead !== null &&
  4289. req.timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait));
  4290. var requestCompletedWithServerError = (req.xhr.readyState == 4 &&
  4291. (reqStatus < 1 ||
  4292. reqStatus >= 500));
  4293. if (primaryTimeout || secondaryTimeout ||
  4294. requestCompletedWithServerError) {
  4295. if (secondaryTimeout) {
  4296. Strophe.error("Request " +
  4297. this._requests[i].id +
  4298. " timed out (secondary), restarting");
  4299. }
  4300. req.abort = true;
  4301. req.xhr.abort();
  4302. // setting to null fails on IE6, so set to empty function
  4303. req.xhr.onreadystatechange = function () {};
  4304. this._requests[i] = new Strophe.Request(req.xmlData,
  4305. req.origFunc,
  4306. req.rid,
  4307. req.sends);
  4308. req = this._requests[i];
  4309. }
  4310. if (req.xhr.readyState === 0) {
  4311. Strophe.debug("request id " + req.id +
  4312. "." + req.sends + " posting");
  4313. try {
  4314. req.xhr.open("POST", this._conn.service, this._conn.options.sync ? false : true);
  4315. req.xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  4316. } catch (e2) {
  4317. Strophe.error("XHR open failed.");
  4318. if (!this._conn.connected) {
  4319. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,
  4320. "bad-service");
  4321. }
  4322. this._conn.disconnect();
  4323. return;
  4324. }
  4325. // Fires the XHR request -- may be invoked immediately
  4326. // or on a gradually expanding retry window for reconnects
  4327. var sendFunc = function () {
  4328. req.date = new Date();
  4329. if (self._conn.options.customHeaders){
  4330. var headers = self._conn.options.customHeaders;
  4331. for (var header in headers) {
  4332. if (headers.hasOwnProperty(header)) {
  4333. req.xhr.setRequestHeader(header, headers[header]);
  4334. }
  4335. }
  4336. }
  4337. req.xhr.send(req.data);
  4338. };
  4339. // Implement progressive backoff for reconnects --
  4340. // First retry (send == 1) should also be instantaneous
  4341. if (req.sends > 1) {
  4342. // Using a cube of the retry number creates a nicely
  4343. // expanding retry window
  4344. var backoff = Math.min(Math.floor(Strophe.TIMEOUT * this.wait),
  4345. Math.pow(req.sends, 3)) * 1000;
  4346. setTimeout(sendFunc, backoff);
  4347. } else {
  4348. sendFunc();
  4349. }
  4350. req.sends++;
  4351. if (this._conn.xmlOutput !== Strophe.Connection.prototype.xmlOutput) {
  4352. if (req.xmlData.nodeName === this.strip && req.xmlData.childNodes.length) {
  4353. this._conn.xmlOutput(req.xmlData.childNodes[0]);
  4354. } else {
  4355. this._conn.xmlOutput(req.xmlData);
  4356. }
  4357. }
  4358. if (this._conn.rawOutput !== Strophe.Connection.prototype.rawOutput) {
  4359. this._conn.rawOutput(req.data);
  4360. }
  4361. } else {
  4362. Strophe.debug("_processRequest: " +
  4363. (i === 0 ? "first" : "second") +
  4364. " request has readyState of " +
  4365. req.xhr.readyState);
  4366. }
  4367. },
  4368. /** PrivateFunction: _removeRequest
  4369. * _Private_ function to remove a request from the queue.
  4370. *
  4371. * Parameters:
  4372. * (Strophe.Request) req - The request to remove.
  4373. */
  4374. _removeRequest: function (req)
  4375. {
  4376. Strophe.debug("removing request");
  4377. var i;
  4378. for (i = this._requests.length - 1; i >= 0; i--) {
  4379. if (req == this._requests[i]) {
  4380. this._requests.splice(i, 1);
  4381. }
  4382. }
  4383. // IE6 fails on setting to null, so set to empty function
  4384. req.xhr.onreadystatechange = function () {};
  4385. this._throttledRequestHandler();
  4386. },
  4387. /** PrivateFunction: _restartRequest
  4388. * _Private_ function to restart a request that is presumed dead.
  4389. *
  4390. * Parameters:
  4391. * (Integer) i - The index of the request in the queue.
  4392. */
  4393. _restartRequest: function (i)
  4394. {
  4395. var req = this._requests[i];
  4396. if (req.dead === null) {
  4397. req.dead = new Date();
  4398. }
  4399. this._processRequest(i);
  4400. },
  4401. /** PrivateFunction: _reqToData
  4402. * _Private_ function to get a stanza out of a request.
  4403. *
  4404. * Tries to extract a stanza out of a Request Object.
  4405. * When this fails the current connection will be disconnected.
  4406. *
  4407. * Parameters:
  4408. * (Object) req - The Request.
  4409. *
  4410. * Returns:
  4411. * The stanza that was passed.
  4412. */
  4413. _reqToData: function (req)
  4414. {
  4415. try {
  4416. return req.getResponse();
  4417. } catch (e) {
  4418. if (e != "parsererror") { throw e; }
  4419. this._conn.disconnect("strophe-parsererror");
  4420. }
  4421. },
  4422. /** PrivateFunction: _sendTerminate
  4423. * _Private_ function to send initial disconnect sequence.
  4424. *
  4425. * This is the first step in a graceful disconnect. It sends
  4426. * the BOSH server a terminate body and includes an unavailable
  4427. * presence if authentication has completed.
  4428. */
  4429. _sendTerminate: function (pres)
  4430. {
  4431. Strophe.info("_sendTerminate was called");
  4432. var body = this._buildBody().attrs({type: "terminate"});
  4433. if (pres) {
  4434. body.cnode(pres.tree());
  4435. }
  4436. var req = new Strophe.Request(body.tree(),
  4437. this._onRequestStateChange.bind(
  4438. this, this._conn._dataRecv.bind(this._conn)),
  4439. body.tree().getAttribute("rid"));
  4440. this._requests.push(req);
  4441. this._throttledRequestHandler();
  4442. },
  4443. /** PrivateFunction: _send
  4444. * _Private_ part of the Connection.send function for BOSH
  4445. *
  4446. * Just triggers the RequestHandler to send the messages that are in the queue
  4447. */
  4448. _send: function () {
  4449. clearTimeout(this._conn._idleTimeout);
  4450. this._throttledRequestHandler();
  4451. this._conn._idleTimeout = setTimeout(this._conn._onIdle.bind(this._conn), 100);
  4452. },
  4453. /** PrivateFunction: _sendRestart
  4454. *
  4455. * Send an xmpp:restart stanza.
  4456. */
  4457. _sendRestart: function ()
  4458. {
  4459. this._throttledRequestHandler();
  4460. clearTimeout(this._conn._idleTimeout);
  4461. },
  4462. /** PrivateFunction: _throttledRequestHandler
  4463. * _Private_ function to throttle requests to the connection window.
  4464. *
  4465. * This function makes sure we don't send requests so fast that the
  4466. * request ids overflow the connection window in the case that one
  4467. * request died.
  4468. */
  4469. _throttledRequestHandler: function ()
  4470. {
  4471. if (!this._requests) {
  4472. Strophe.debug("_throttledRequestHandler called with " +
  4473. "undefined requests");
  4474. } else {
  4475. Strophe.debug("_throttledRequestHandler called with " +
  4476. this._requests.length + " requests");
  4477. }
  4478. if (!this._requests || this._requests.length === 0) {
  4479. return;
  4480. }
  4481. if (this._requests.length > 0) {
  4482. this._processRequest(0);
  4483. }
  4484. if (this._requests.length > 1 &&
  4485. Math.abs(this._requests[0].rid -
  4486. this._requests[1].rid) < this.window) {
  4487. this._processRequest(1);
  4488. }
  4489. }
  4490. };
  4491. return Strophe;
  4492. }));
  4493. /*
  4494. This program is distributed under the terms of the MIT license.
  4495. Please see the LICENSE file for details.
  4496. Copyright 2006-2008, OGG, LLC
  4497. */
  4498. /* jshint undef: true, unused: true:, noarg: true, latedef: true */
  4499. /* global define, window, clearTimeout, WebSocket, DOMParser, Strophe, $build */
  4500. (function (root, factory) {
  4501. if (typeof define === 'function' && define.amd) {
  4502. define('strophe-websocket', ['strophe-core'], function (core) {
  4503. return factory(
  4504. core.Strophe,
  4505. core.$build
  4506. );
  4507. });
  4508. } else {
  4509. // Browser globals
  4510. return factory(Strophe, $build);
  4511. }
  4512. }(this, function (Strophe, $build) {
  4513. /** Class: Strophe.WebSocket
  4514. * _Private_ helper class that handles WebSocket Connections
  4515. *
  4516. * The Strophe.WebSocket class is used internally by Strophe.Connection
  4517. * to encapsulate WebSocket sessions. It is not meant to be used from user's code.
  4518. */
  4519. /** File: websocket.js
  4520. * A JavaScript library to enable XMPP over Websocket in Strophejs.
  4521. *
  4522. * This file implements XMPP over WebSockets for Strophejs.
  4523. * If a Connection is established with a Websocket url (ws://...)
  4524. * Strophe will use WebSockets.
  4525. * For more information on XMPP-over-WebSocket see RFC 7395:
  4526. * http://tools.ietf.org/html/rfc7395
  4527. *
  4528. * WebSocket support implemented by Andreas Guth (andreas.guth@rwth-aachen.de)
  4529. */
  4530. /** PrivateConstructor: Strophe.Websocket
  4531. * Create and initialize a Strophe.WebSocket object.
  4532. * Currently only sets the connection Object.
  4533. *
  4534. * Parameters:
  4535. * (Strophe.Connection) connection - The Strophe.Connection that will use WebSockets.
  4536. *
  4537. * Returns:
  4538. * A new Strophe.WebSocket object.
  4539. */
  4540. Strophe.Websocket = function(connection) {
  4541. this._conn = connection;
  4542. this.strip = "wrapper";
  4543. var service = connection.service;
  4544. if (service.indexOf("ws:") !== 0 && service.indexOf("wss:") !== 0) {
  4545. // If the service is not an absolute URL, assume it is a path and put the absolute
  4546. // URL together from options, current URL and the path.
  4547. var new_service = "";
  4548. if (connection.options.protocol === "ws" && window.location.protocol !== "https:") {
  4549. new_service += "ws";
  4550. } else {
  4551. new_service += "wss";
  4552. }
  4553. new_service += "://" + window.location.host;
  4554. if (service.indexOf("/") !== 0) {
  4555. new_service += window.location.pathname + service;
  4556. } else {
  4557. new_service += service;
  4558. }
  4559. connection.service = new_service;
  4560. }
  4561. };
  4562. Strophe.Websocket.prototype = {
  4563. /** PrivateFunction: _buildStream
  4564. * _Private_ helper function to generate the <stream> start tag for WebSockets
  4565. *
  4566. * Returns:
  4567. * A Strophe.Builder with a <stream> element.
  4568. */
  4569. _buildStream: function ()
  4570. {
  4571. return $build("open", {
  4572. "xmlns": Strophe.NS.FRAMING,
  4573. "to": this._conn.domain,
  4574. "version": '1.0'
  4575. });
  4576. },
  4577. /** PrivateFunction: _check_streamerror
  4578. * _Private_ checks a message for stream:error
  4579. *
  4580. * Parameters:
  4581. * (Strophe.Request) bodyWrap - The received stanza.
  4582. * connectstatus - The ConnectStatus that will be set on error.
  4583. * Returns:
  4584. * true if there was a streamerror, false otherwise.
  4585. */
  4586. _check_streamerror: function (bodyWrap, connectstatus) {
  4587. var errors;
  4588. if (bodyWrap.getElementsByTagNameNS) {
  4589. errors = bodyWrap.getElementsByTagNameNS(Strophe.NS.STREAM, "error");
  4590. } else {
  4591. errors = bodyWrap.getElementsByTagName("stream:error");
  4592. }
  4593. if (errors.length === 0) {
  4594. return false;
  4595. }
  4596. var error = errors[0];
  4597. var condition = "";
  4598. var text = "";
  4599. var ns = "urn:ietf:params:xml:ns:xmpp-streams";
  4600. for (var i = 0; i < error.childNodes.length; i++) {
  4601. var e = error.childNodes[i];
  4602. if (e.getAttribute("xmlns") !== ns) {
  4603. break;
  4604. } if (e.nodeName === "text") {
  4605. text = e.textContent;
  4606. } else {
  4607. condition = e.nodeName;
  4608. }
  4609. }
  4610. var errorString = "WebSocket stream error: ";
  4611. if (condition) {
  4612. errorString += condition;
  4613. } else {
  4614. errorString += "unknown";
  4615. }
  4616. if (text) {
  4617. errorString += " - " + condition;
  4618. }
  4619. Strophe.error(errorString);
  4620. // close the connection on stream_error
  4621. this._conn._changeConnectStatus(connectstatus, condition);
  4622. this._conn._doDisconnect();
  4623. return true;
  4624. },
  4625. /** PrivateFunction: _reset
  4626. * Reset the connection.
  4627. *
  4628. * This function is called by the reset function of the Strophe Connection.
  4629. * Is not needed by WebSockets.
  4630. */
  4631. _reset: function ()
  4632. {
  4633. return;
  4634. },
  4635. /** PrivateFunction: _connect
  4636. * _Private_ function called by Strophe.Connection.connect
  4637. *
  4638. * Creates a WebSocket for a connection and assigns Callbacks to it.
  4639. * Does nothing if there already is a WebSocket.
  4640. */
  4641. _connect: function () {
  4642. // Ensure that there is no open WebSocket from a previous Connection.
  4643. this._closeSocket();
  4644. // Create the new WobSocket
  4645. this.socket = new WebSocket(this._conn.service, "xmpp");
  4646. this.socket.onopen = this._onOpen.bind(this);
  4647. this.socket.onerror = this._onError.bind(this);
  4648. this.socket.onclose = this._onClose.bind(this);
  4649. this.socket.onmessage = this._connect_cb_wrapper.bind(this);
  4650. },
  4651. /** PrivateFunction: _connect_cb
  4652. * _Private_ function called by Strophe.Connection._connect_cb
  4653. *
  4654. * checks for stream:error
  4655. *
  4656. * Parameters:
  4657. * (Strophe.Request) bodyWrap - The received stanza.
  4658. */
  4659. _connect_cb: function(bodyWrap) {
  4660. var error = this._check_streamerror(bodyWrap, Strophe.Status.CONNFAIL);
  4661. if (error) {
  4662. return Strophe.Status.CONNFAIL;
  4663. }
  4664. },
  4665. /** PrivateFunction: _handleStreamStart
  4666. * _Private_ function that checks the opening <open /> tag for errors.
  4667. *
  4668. * Disconnects if there is an error and returns false, true otherwise.
  4669. *
  4670. * Parameters:
  4671. * (Node) message - Stanza containing the <open /> tag.
  4672. */
  4673. _handleStreamStart: function(message) {
  4674. var error = false;
  4675. // Check for errors in the <open /> tag
  4676. var ns = message.getAttribute("xmlns");
  4677. if (typeof ns !== "string") {
  4678. error = "Missing xmlns in <open />";
  4679. } else if (ns !== Strophe.NS.FRAMING) {
  4680. error = "Wrong xmlns in <open />: " + ns;
  4681. }
  4682. var ver = message.getAttribute("version");
  4683. if (typeof ver !== "string") {
  4684. error = "Missing version in <open />";
  4685. } else if (ver !== "1.0") {
  4686. error = "Wrong version in <open />: " + ver;
  4687. }
  4688. if (error) {
  4689. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, error);
  4690. this._conn._doDisconnect();
  4691. return false;
  4692. }
  4693. return true;
  4694. },
  4695. /** PrivateFunction: _connect_cb_wrapper
  4696. * _Private_ function that handles the first connection messages.
  4697. *
  4698. * On receiving an opening stream tag this callback replaces itself with the real
  4699. * message handler. On receiving a stream error the connection is terminated.
  4700. */
  4701. _connect_cb_wrapper: function(message) {
  4702. if (message.data.indexOf("<open ") === 0 || message.data.indexOf("<?xml") === 0) {
  4703. // Strip the XML Declaration, if there is one
  4704. var data = message.data.replace(/^(<\?.*?\?>\s*)*/, "");
  4705. if (data === '') return;
  4706. var streamStart = new DOMParser().parseFromString(data, "text/xml").documentElement;
  4707. this._conn.xmlInput(streamStart);
  4708. this._conn.rawInput(message.data);
  4709. //_handleStreamSteart will check for XML errors and disconnect on error
  4710. if (this._handleStreamStart(streamStart)) {
  4711. //_connect_cb will check for stream:error and disconnect on error
  4712. this._connect_cb(streamStart);
  4713. }
  4714. } else if (message.data.indexOf("<close ") === 0) { //'<close xmlns="urn:ietf:params:xml:ns:xmpp-framing />') {
  4715. this._conn.rawInput(message.data);
  4716. this._conn.xmlInput(message);
  4717. var see_uri = message.getAttribute("see-other-uri");
  4718. if (see_uri) {
  4719. this._conn._changeConnectStatus(Strophe.Status.REDIRECT, "Received see-other-uri, resetting connection");
  4720. this._conn.reset();
  4721. this._conn.service = see_uri;
  4722. this._connect();
  4723. } else {
  4724. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "Received closing stream");
  4725. this._conn._doDisconnect();
  4726. }
  4727. } else {
  4728. var string = this._streamWrap(message.data);
  4729. var elem = new DOMParser().parseFromString(string, "text/xml").documentElement;
  4730. this.socket.onmessage = this._onMessage.bind(this);
  4731. this._conn._connect_cb(elem, null, message.data);
  4732. }
  4733. },
  4734. /** PrivateFunction: _disconnect
  4735. * _Private_ function called by Strophe.Connection.disconnect
  4736. *
  4737. * Disconnects and sends a last stanza if one is given
  4738. *
  4739. * Parameters:
  4740. * (Request) pres - This stanza will be sent before disconnecting.
  4741. */
  4742. _disconnect: function (pres)
  4743. {
  4744. if (this.socket && this.socket.readyState !== WebSocket.CLOSED) {
  4745. if (pres) {
  4746. this._conn.send(pres);
  4747. }
  4748. var close = $build("close", { "xmlns": Strophe.NS.FRAMING, });
  4749. this._conn.xmlOutput(close);
  4750. var closeString = Strophe.serialize(close);
  4751. this._conn.rawOutput(closeString);
  4752. try {
  4753. this.socket.send(closeString);
  4754. } catch (e) {
  4755. Strophe.info("Couldn't send <close /> tag.");
  4756. }
  4757. }
  4758. this._conn._doDisconnect();
  4759. },
  4760. /** PrivateFunction: _doDisconnect
  4761. * _Private_ function to disconnect.
  4762. *
  4763. * Just closes the Socket for WebSockets
  4764. */
  4765. _doDisconnect: function ()
  4766. {
  4767. Strophe.info("WebSockets _doDisconnect was called");
  4768. this._closeSocket();
  4769. },
  4770. /** PrivateFunction _streamWrap
  4771. * _Private_ helper function to wrap a stanza in a <stream> tag.
  4772. * This is used so Strophe can process stanzas from WebSockets like BOSH
  4773. */
  4774. _streamWrap: function (stanza)
  4775. {
  4776. return "<wrapper>" + stanza + '</wrapper>';
  4777. },
  4778. /** PrivateFunction: _closeSocket
  4779. * _Private_ function to close the WebSocket.
  4780. *
  4781. * Closes the socket if it is still open and deletes it
  4782. */
  4783. _closeSocket: function ()
  4784. {
  4785. if (this.socket) { try {
  4786. this.socket.close();
  4787. } catch (e) {} }
  4788. this.socket = null;
  4789. },
  4790. /** PrivateFunction: _emptyQueue
  4791. * _Private_ function to check if the message queue is empty.
  4792. *
  4793. * Returns:
  4794. * True, because WebSocket messages are send immediately after queueing.
  4795. */
  4796. _emptyQueue: function ()
  4797. {
  4798. return true;
  4799. },
  4800. /** PrivateFunction: _onClose
  4801. * _Private_ function to handle websockets closing.
  4802. *
  4803. * Nothing to do here for WebSockets
  4804. */
  4805. _onClose: function() {
  4806. if(this._conn.connected && !this._conn.disconnecting) {
  4807. Strophe.error("Websocket closed unexcectedly");
  4808. this._conn._doDisconnect();
  4809. } else {
  4810. Strophe.info("Websocket closed");
  4811. }
  4812. },
  4813. /** PrivateFunction: _no_auth_received
  4814. *
  4815. * Called on stream start/restart when no stream:features
  4816. * has been received.
  4817. */
  4818. _no_auth_received: function (_callback)
  4819. {
  4820. Strophe.error("Server did not send any auth methods");
  4821. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "Server did not send any auth methods");
  4822. if (_callback) {
  4823. _callback = _callback.bind(this._conn);
  4824. _callback();
  4825. }
  4826. this._conn._doDisconnect();
  4827. },
  4828. /** PrivateFunction: _onDisconnectTimeout
  4829. * _Private_ timeout handler for handling non-graceful disconnection.
  4830. *
  4831. * This does nothing for WebSockets
  4832. */
  4833. _onDisconnectTimeout: function () {},
  4834. /** PrivateFunction: _abortAllRequests
  4835. * _Private_ helper function that makes sure all pending requests are aborted.
  4836. */
  4837. _abortAllRequests: function () {},
  4838. /** PrivateFunction: _onError
  4839. * _Private_ function to handle websockets errors.
  4840. *
  4841. * Parameters:
  4842. * (Object) error - The websocket error.
  4843. */
  4844. _onError: function(error) {
  4845. Strophe.error("Websocket error " + error);
  4846. this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "The WebSocket connection could not be established was disconnected.");
  4847. this._disconnect();
  4848. },
  4849. /** PrivateFunction: _onIdle
  4850. * _Private_ function called by Strophe.Connection._onIdle
  4851. *
  4852. * sends all queued stanzas
  4853. */
  4854. _onIdle: function () {
  4855. var data = this._conn._data;
  4856. if (data.length > 0 && !this._conn.paused) {
  4857. for (var i = 0; i < data.length; i++) {
  4858. if (data[i] !== null) {
  4859. var stanza, rawStanza;
  4860. if (data[i] === "restart") {
  4861. stanza = this._buildStream().tree();
  4862. } else {
  4863. stanza = data[i];
  4864. }
  4865. rawStanza = Strophe.serialize(stanza);
  4866. this._conn.xmlOutput(stanza);
  4867. this._conn.rawOutput(rawStanza);
  4868. this.socket.send(rawStanza);
  4869. }
  4870. }
  4871. this._conn._data = [];
  4872. }
  4873. },
  4874. /** PrivateFunction: _onMessage
  4875. * _Private_ function to handle websockets messages.
  4876. *
  4877. * This function parses each of the messages as if they are full documents. [TODO : We may actually want to use a SAX Push parser].
  4878. *
  4879. * Since all XMPP traffic starts with "<stream:stream version='1.0' xml:lang='en' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='3697395463' from='SERVER'>"
  4880. * The first stanza will always fail to be parsed...
  4881. * Addtionnaly, the seconds stanza will always be a <stream:features> with the stream NS defined in the previous stanza... so we need to 'force' the inclusion of the NS in this stanza!
  4882. *
  4883. * Parameters:
  4884. * (string) message - The websocket message.
  4885. */
  4886. _onMessage: function(message) {
  4887. var elem, data;
  4888. // check for closing stream
  4889. var close = '<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';
  4890. if (message.data === close) {
  4891. this._conn.rawInput(close);
  4892. this._conn.xmlInput(message);
  4893. if (!this._conn.disconnecting) {
  4894. this._conn._doDisconnect();
  4895. }
  4896. return;
  4897. } else if (message.data.search("<open ") === 0) {
  4898. // This handles stream restarts
  4899. elem = new DOMParser().parseFromString(message.data, "text/xml").documentElement;
  4900. if (!this._handleStreamStart(elem)) {
  4901. return;
  4902. }
  4903. } else {
  4904. data = this._streamWrap(message.data);
  4905. elem = new DOMParser().parseFromString(data, "text/xml").documentElement;
  4906. }
  4907. if (this._check_streamerror(elem, Strophe.Status.ERROR)) {
  4908. return;
  4909. }
  4910. //handle unavailable presence stanza before disconnecting
  4911. if (this._conn.disconnecting &&
  4912. elem.firstChild.nodeName === "presence" &&
  4913. elem.firstChild.getAttribute("type") === "unavailable") {
  4914. this._conn.xmlInput(elem);
  4915. this._conn.rawInput(Strophe.serialize(elem));
  4916. // if we are already disconnecting we will ignore the unavailable stanza and
  4917. // wait for the </stream:stream> tag before we close the connection
  4918. return;
  4919. }
  4920. this._conn._dataRecv(elem, message.data);
  4921. },
  4922. /** PrivateFunction: _onOpen
  4923. * _Private_ function to handle websockets connection setup.
  4924. *
  4925. * The opening stream tag is sent here.
  4926. */
  4927. _onOpen: function() {
  4928. Strophe.info("Websocket open");
  4929. var start = this._buildStream();
  4930. this._conn.xmlOutput(start.tree());
  4931. var startString = Strophe.serialize(start);
  4932. this._conn.rawOutput(startString);
  4933. this.socket.send(startString);
  4934. },
  4935. /** PrivateFunction: _reqToData
  4936. * _Private_ function to get a stanza out of a request.
  4937. *
  4938. * WebSockets don't use requests, so the passed argument is just returned.
  4939. *
  4940. * Parameters:
  4941. * (Object) stanza - The stanza.
  4942. *
  4943. * Returns:
  4944. * The stanza that was passed.
  4945. */
  4946. _reqToData: function (stanza)
  4947. {
  4948. return stanza;
  4949. },
  4950. /** PrivateFunction: _send
  4951. * _Private_ part of the Connection.send function for WebSocket
  4952. *
  4953. * Just flushes the messages that are in the queue
  4954. */
  4955. _send: function () {
  4956. this._conn.flush();
  4957. },
  4958. /** PrivateFunction: _sendRestart
  4959. *
  4960. * Send an xmpp:restart stanza.
  4961. */
  4962. _sendRestart: function ()
  4963. {
  4964. clearTimeout(this._conn._idleTimeout);
  4965. this._conn._onIdle.bind(this._conn)();
  4966. }
  4967. };
  4968. return Strophe;
  4969. }));
  4970. /* jshint ignore:start */
  4971. if (callback) {
  4972. return callback(Strophe, $build, $msg, $iq, $pres);
  4973. }
  4974. })(function (Strophe, build, msg, iq, pres) {
  4975. window.Strophe = Strophe;
  4976. window.$build = build;
  4977. window.$msg = msg;
  4978. window.$iq = iq;
  4979. window.$pres = pres;
  4980. });
  4981. /* jshint ignore:end */