strophe-custom-2.0.0.js 169 KB

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