strophe.js 137 KB

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