strophe.js 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201
  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. result = this.handler(elem);
  1754. if (e.sourceURL) {
  1755. Strophe.fatal("error: " + this.handler +
  1756. " " + e.sourceURL + ":" +
  1757. e.line + " - " + e.name + ": " + e.message);
  1758. } else if (e.fileName) {
  1759. if (typeof(console) != "undefined") {
  1760. console.trace();
  1761. console.error(this.handler, " - error - ", e, e.message);
  1762. }
  1763. Strophe.fatal("error: " + this.handler + " " +
  1764. e.fileName + ":" + e.lineNumber + " - " +
  1765. e.name + ": " + e.message);
  1766. } else {
  1767. Strophe.fatal("error: " + e.message + "\n" + e.stack);
  1768. }
  1769. throw e;
  1770. }
  1771. return result;
  1772. },
  1773. /** PrivateFunction: toString
  1774. * Get a String representation of the Strophe.Handler object.
  1775. *
  1776. * Returns:
  1777. * A String.
  1778. */
  1779. toString: function ()
  1780. {
  1781. return "{Handler: " + this.handler + "(" + this.name + "," +
  1782. this.id + "," + this.ns + ")}";
  1783. }
  1784. };
  1785. /** PrivateClass: Strophe.TimedHandler
  1786. * _Private_ helper class for managing timed handlers.
  1787. *
  1788. * A Strophe.TimedHandler encapsulates a user provided callback that
  1789. * should be called after a certain period of time or at regular
  1790. * intervals. The return value of the callback determines whether the
  1791. * Strophe.TimedHandler will continue to fire.
  1792. *
  1793. * Users will not use Strophe.TimedHandler objects directly, but instead
  1794. * they will use Strophe.Connection.addTimedHandler() and
  1795. * Strophe.Connection.deleteTimedHandler().
  1796. */
  1797. /** PrivateConstructor: Strophe.TimedHandler
  1798. * Create and initialize a new Strophe.TimedHandler object.
  1799. *
  1800. * Parameters:
  1801. * (Integer) period - The number of milliseconds to wait before the
  1802. * handler is called.
  1803. * (Function) handler - The callback to run when the handler fires. This
  1804. * function should take no arguments.
  1805. *
  1806. * Returns:
  1807. * A new Strophe.TimedHandler object.
  1808. */
  1809. Strophe.TimedHandler = function (period, handler)
  1810. {
  1811. this.period = period;
  1812. this.handler = handler;
  1813. this.lastCalled = new Date().getTime();
  1814. this.user = true;
  1815. };
  1816. Strophe.TimedHandler.prototype = {
  1817. /** PrivateFunction: run
  1818. * Run the callback for the Strophe.TimedHandler.
  1819. *
  1820. * Returns:
  1821. * true if the Strophe.TimedHandler should be called again, and false
  1822. * otherwise.
  1823. */
  1824. run: function ()
  1825. {
  1826. this.lastCalled = new Date().getTime();
  1827. return this.handler();
  1828. },
  1829. /** PrivateFunction: reset
  1830. * Reset the last called time for the Strophe.TimedHandler.
  1831. */
  1832. reset: function ()
  1833. {
  1834. this.lastCalled = new Date().getTime();
  1835. },
  1836. /** PrivateFunction: toString
  1837. * Get a string representation of the Strophe.TimedHandler object.
  1838. *
  1839. * Returns:
  1840. * The string representation.
  1841. */
  1842. toString: function ()
  1843. {
  1844. return "{TimedHandler: " + this.handler + "(" + this.period +")}";
  1845. }
  1846. };
  1847. /** PrivateClass: Strophe.Request
  1848. * _Private_ helper class that provides a cross implementation abstraction
  1849. * for a BOSH related XMLHttpRequest.
  1850. *
  1851. * The Strophe.Request class is used internally to encapsulate BOSH request
  1852. * information. It is not meant to be used from user's code.
  1853. */
  1854. /** PrivateConstructor: Strophe.Request
  1855. * Create and initialize a new Strophe.Request object.
  1856. *
  1857. * Parameters:
  1858. * (XMLElement) elem - The XML data to be sent in the request.
  1859. * (Function) func - The function that will be called when the
  1860. * XMLHttpRequest readyState changes.
  1861. * (Integer) rid - The BOSH rid attribute associated with this request.
  1862. * (Integer) sends - The number of times this same request has been
  1863. * sent.
  1864. */
  1865. Strophe.Request = function (elem, func, rid, sends)
  1866. {
  1867. this.id = ++Strophe._requestId;
  1868. this.xmlData = elem;
  1869. this.data = Strophe.serialize(elem);
  1870. // save original function in case we need to make a new request
  1871. // from this one.
  1872. this.origFunc = func;
  1873. this.func = func;
  1874. this.rid = rid;
  1875. this.date = NaN;
  1876. this.sends = sends || 0;
  1877. this.abort = false;
  1878. this.dead = null;
  1879. this.age = function () {
  1880. if (!this.date) { return 0; }
  1881. var now = new Date();
  1882. return (now - this.date) / 1000;
  1883. };
  1884. this.timeDead = function () {
  1885. if (!this.dead) { return 0; }
  1886. var now = new Date();
  1887. return (now - this.dead) / 1000;
  1888. };
  1889. this.xhr = this._newXHR();
  1890. };
  1891. Strophe.Request.prototype = {
  1892. /** PrivateFunction: getResponse
  1893. * Get a response from the underlying XMLHttpRequest.
  1894. *
  1895. * This function attempts to get a response from the request and checks
  1896. * for errors.
  1897. *
  1898. * Throws:
  1899. * "parsererror" - A parser error occured.
  1900. *
  1901. * Returns:
  1902. * The DOM element tree of the response.
  1903. */
  1904. getResponse: function ()
  1905. {
  1906. var node = null;
  1907. if (this.xhr.responseXML && this.xhr.responseXML.documentElement) {
  1908. node = this.xhr.responseXML.documentElement;
  1909. if (node.tagName == "parsererror") {
  1910. Strophe.error("invalid response received");
  1911. Strophe.error("responseText: " + this.xhr.responseText);
  1912. Strophe.error("responseXML: " +
  1913. Strophe.serialize(this.xhr.responseXML));
  1914. throw "parsererror";
  1915. }
  1916. } else if (this.xhr.responseText) {
  1917. Strophe.error("invalid response received");
  1918. Strophe.error("responseText: " + this.xhr.responseText);
  1919. Strophe.error("responseXML: " +
  1920. Strophe.serialize(this.xhr.responseXML));
  1921. }
  1922. return node;
  1923. },
  1924. /** PrivateFunction: _newXHR
  1925. * _Private_ helper function to create XMLHttpRequests.
  1926. *
  1927. * This function creates XMLHttpRequests across all implementations.
  1928. *
  1929. * Returns:
  1930. * A new XMLHttpRequest.
  1931. */
  1932. _newXHR: function ()
  1933. {
  1934. var xhr = null;
  1935. if (window.XMLHttpRequest) {
  1936. xhr = new XMLHttpRequest();
  1937. if (xhr.overrideMimeType) {
  1938. xhr.overrideMimeType("text/xml");
  1939. }
  1940. } else if (window.ActiveXObject) {
  1941. xhr = new ActiveXObject("Microsoft.XMLHTTP");
  1942. }
  1943. // use Function.bind() to prepend ourselves as an argument
  1944. xhr.onreadystatechange = this.func.bind(null, this);
  1945. return xhr;
  1946. }
  1947. };
  1948. /** Class: Strophe.Connection
  1949. * XMPP Connection manager.
  1950. *
  1951. * This class is the main part of Strophe. It manages a BOSH connection
  1952. * to an XMPP server and dispatches events to the user callbacks as
  1953. * data arrives. It supports SASL PLAIN, SASL DIGEST-MD5, and legacy
  1954. * authentication.
  1955. *
  1956. * After creating a Strophe.Connection object, the user will typically
  1957. * call connect() with a user supplied callback to handle connection level
  1958. * events like authentication failure, disconnection, or connection
  1959. * complete.
  1960. *
  1961. * The user will also have several event handlers defined by using
  1962. * addHandler() and addTimedHandler(). These will allow the user code to
  1963. * respond to interesting stanzas or do something periodically with the
  1964. * connection. These handlers will be active once authentication is
  1965. * finished.
  1966. *
  1967. * To send data to the connection, use send().
  1968. */
  1969. /** Constructor: Strophe.Connection
  1970. * Create and initialize a Strophe.Connection object.
  1971. *
  1972. * Parameters:
  1973. * (String) service - The BOSH service URL.
  1974. *
  1975. * Returns:
  1976. * A new Strophe.Connection object.
  1977. */
  1978. Strophe.Connection = function (service)
  1979. {
  1980. /* The path to the httpbind service. */
  1981. this.service = service;
  1982. /* The connected JID. */
  1983. this.jid = "";
  1984. /* the JIDs domain */
  1985. this.domain = null;
  1986. /* request id for body tags */
  1987. this.rid = Math.floor(Math.random() * 4294967295);
  1988. /* The current session ID. */
  1989. this.sid = null;
  1990. this.streamId = null;
  1991. /* stream:features */
  1992. this.features = null;
  1993. // SASL
  1994. this._sasl_data = [];
  1995. this.do_session = false;
  1996. this.do_bind = false;
  1997. // handler lists
  1998. this.timedHandlers = [];
  1999. this.handlers = [];
  2000. this.removeTimeds = [];
  2001. this.removeHandlers = [];
  2002. this.addTimeds = [];
  2003. this.addHandlers = [];
  2004. this._authentication = {};
  2005. this._idleTimeout = null;
  2006. this._disconnectTimeout = null;
  2007. this.do_authentication = true;
  2008. this.authenticated = false;
  2009. this.disconnecting = false;
  2010. this.connected = false;
  2011. this.errors = 0;
  2012. this.paused = false;
  2013. // default BOSH values
  2014. this.hold = 1;
  2015. this.wait = 60;
  2016. this.window = 5;
  2017. this._data = [];
  2018. this._requests = [];
  2019. this._uniqueId = Math.round(Math.random() * 10000);
  2020. this._sasl_success_handler = null;
  2021. this._sasl_failure_handler = null;
  2022. this._sasl_challenge_handler = null;
  2023. // Max retries before disconnecting
  2024. this.maxRetries = 5;
  2025. // setup onIdle callback every 1/10th of a second
  2026. this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
  2027. // initialize plugins
  2028. for (var k in Strophe._connectionPlugins) {
  2029. if (Strophe._connectionPlugins.hasOwnProperty(k)) {
  2030. var ptype = Strophe._connectionPlugins[k];
  2031. // jslint complaints about the below line, but this is fine
  2032. var F = function () {};
  2033. F.prototype = ptype;
  2034. this[k] = new F();
  2035. this[k].init(this);
  2036. }
  2037. }
  2038. };
  2039. Strophe.Connection.prototype = {
  2040. /** Function: reset
  2041. * Reset the connection.
  2042. *
  2043. * This function should be called after a connection is disconnected
  2044. * before that connection is reused.
  2045. */
  2046. reset: function ()
  2047. {
  2048. this.rid = Math.floor(Math.random() * 4294967295);
  2049. this.sid = null;
  2050. this.streamId = null;
  2051. // SASL
  2052. this.do_session = false;
  2053. this.do_bind = false;
  2054. // handler lists
  2055. this.timedHandlers = [];
  2056. this.handlers = [];
  2057. this.removeTimeds = [];
  2058. this.removeHandlers = [];
  2059. this.addTimeds = [];
  2060. this.addHandlers = [];
  2061. this._authentication = {};
  2062. this.authenticated = false;
  2063. this.disconnecting = false;
  2064. this.connected = false;
  2065. this.errors = 0;
  2066. this._requests = [];
  2067. this._uniqueId = Math.round(Math.random()*10000);
  2068. },
  2069. /** Function: pause
  2070. * Pause the request manager.
  2071. *
  2072. * This will prevent Strophe from sending any more requests to the
  2073. * server. This is very useful for temporarily pausing while a lot
  2074. * of send() calls are happening quickly. This causes Strophe to
  2075. * send the data in a single request, saving many request trips.
  2076. */
  2077. pause: function ()
  2078. {
  2079. this.paused = true;
  2080. },
  2081. /** Function: resume
  2082. * Resume the request manager.
  2083. *
  2084. * This resumes after pause() has been called.
  2085. */
  2086. resume: function ()
  2087. {
  2088. this.paused = false;
  2089. },
  2090. /** Function: getUniqueId
  2091. * Generate a unique ID for use in <iq/> elements.
  2092. *
  2093. * All <iq/> stanzas are required to have unique id attributes. This
  2094. * function makes creating these easy. Each connection instance has
  2095. * a counter which starts from zero, and the value of this counter
  2096. * plus a colon followed by the suffix becomes the unique id. If no
  2097. * suffix is supplied, the counter is used as the unique id.
  2098. *
  2099. * Suffixes are used to make debugging easier when reading the stream
  2100. * data, and their use is recommended. The counter resets to 0 for
  2101. * every new connection for the same reason. For connections to the
  2102. * same server that authenticate the same way, all the ids should be
  2103. * the same, which makes it easy to see changes. This is useful for
  2104. * automated testing as well.
  2105. *
  2106. * Parameters:
  2107. * (String) suffix - A optional suffix to append to the id.
  2108. *
  2109. * Returns:
  2110. * A unique string to be used for the id attribute.
  2111. */
  2112. getUniqueId: function (suffix)
  2113. {
  2114. if (typeof(suffix) == "string" || typeof(suffix) == "number") {
  2115. return ++this._uniqueId + ":" + suffix;
  2116. } else {
  2117. return ++this._uniqueId + "";
  2118. }
  2119. },
  2120. /** Function: connect
  2121. * Starts the connection process.
  2122. *
  2123. * As the connection process proceeds, the user supplied callback will
  2124. * be triggered multiple times with status updates. The callback
  2125. * should take two arguments - the status code and the error condition.
  2126. *
  2127. * The status code will be one of the values in the Strophe.Status
  2128. * constants. The error condition will be one of the conditions
  2129. * defined in RFC 3920 or the condition 'strophe-parsererror'.
  2130. *
  2131. * Please see XEP 124 for a more detailed explanation of the optional
  2132. * parameters below.
  2133. *
  2134. * Parameters:
  2135. * (String) jid - The user's JID. This may be a bare JID,
  2136. * or a full JID. If a node is not supplied, SASL ANONYMOUS
  2137. * authentication will be attempted.
  2138. * (String) pass - The user's password.
  2139. * (Function) callback - The connect callback function.
  2140. * (Integer) wait - The optional HTTPBIND wait value. This is the
  2141. * time the server will wait before returning an empty result for
  2142. * a request. The default setting of 60 seconds is recommended.
  2143. * (Integer) hold - The optional HTTPBIND hold value. This is the
  2144. * number of connections the server will hold at one time. This
  2145. * should almost always be set to 1 (the default).
  2146. * (String) route
  2147. */
  2148. connect: function (jid, pass, callback, wait, hold, route)
  2149. {
  2150. this.jid = jid;
  2151. this.pass = pass;
  2152. this.connect_callback = callback;
  2153. this.disconnecting = false;
  2154. this.connected = false;
  2155. this.authenticated = false;
  2156. this.errors = 0;
  2157. this.wait = wait || this.wait;
  2158. this.hold = hold || this.hold;
  2159. // parse jid for domain and resource
  2160. this.domain = this.domain || Strophe.getDomainFromJid(this.jid);
  2161. // build the body tag
  2162. var body = this._buildBody().attrs({
  2163. to: this.domain,
  2164. "xml:lang": "en",
  2165. wait: this.wait,
  2166. hold: this.hold,
  2167. content: "text/xml; charset=utf-8",
  2168. ver: "1.6",
  2169. "xmpp:version": "1.0",
  2170. "xmlns:xmpp": Strophe.NS.BOSH
  2171. });
  2172. if(route){
  2173. body.attrs({
  2174. route: route
  2175. });
  2176. }
  2177. this._changeConnectStatus(Strophe.Status.CONNECTING, null);
  2178. var _connect_cb = this._connect_callback || this._connect_cb;
  2179. this._connect_callback = null;
  2180. this._requests.push(
  2181. new Strophe.Request(body.tree(),
  2182. this._onRequestStateChange.bind(
  2183. this, _connect_cb.bind(this)),
  2184. body.tree().getAttribute("rid")));
  2185. this._throttledRequestHandler();
  2186. },
  2187. /** Function: attach
  2188. * Attach to an already created and authenticated BOSH session.
  2189. *
  2190. * This function is provided to allow Strophe to attach to BOSH
  2191. * sessions which have been created externally, perhaps by a Web
  2192. * application. This is often used to support auto-login type features
  2193. * without putting user credentials into the page.
  2194. *
  2195. * Parameters:
  2196. * (String) jid - The full JID that is bound by the session.
  2197. * (String) sid - The SID of the BOSH session.
  2198. * (String) rid - The current RID of the BOSH session. This RID
  2199. * will be used by the next request.
  2200. * (Function) callback The connect callback function.
  2201. * (Integer) wait - The optional HTTPBIND wait value. This is the
  2202. * time the server will wait before returning an empty result for
  2203. * a request. The default setting of 60 seconds is recommended.
  2204. * Other settings will require tweaks to the Strophe.TIMEOUT value.
  2205. * (Integer) hold - The optional HTTPBIND hold value. This is the
  2206. * number of connections the server will hold at one time. This
  2207. * should almost always be set to 1 (the default).
  2208. * (Integer) wind - The optional HTTBIND window value. This is the
  2209. * allowed range of request ids that are valid. The default is 5.
  2210. */
  2211. attach: function (jid, sid, rid, callback, wait, hold, wind)
  2212. {
  2213. this.jid = jid;
  2214. this.sid = sid;
  2215. this.rid = rid;
  2216. this.connect_callback = callback;
  2217. this.domain = Strophe.getDomainFromJid(this.jid);
  2218. this.authenticated = true;
  2219. this.connected = true;
  2220. this.wait = wait || this.wait;
  2221. this.hold = hold || this.hold;
  2222. this.window = wind || this.window;
  2223. this._changeConnectStatus(Strophe.Status.ATTACHED, null);
  2224. },
  2225. /** Function: xmlInput
  2226. * User overrideable function that receives XML data coming into the
  2227. * connection.
  2228. *
  2229. * The default function does nothing. User code can override this with
  2230. * > Strophe.Connection.xmlInput = function (elem) {
  2231. * > (user code)
  2232. * > };
  2233. *
  2234. * Parameters:
  2235. * (XMLElement) elem - The XML data received by the connection.
  2236. */
  2237. xmlInput: function (elem)
  2238. {
  2239. return;
  2240. },
  2241. /** Function: xmlOutput
  2242. * User overrideable function that receives XML data sent to the
  2243. * connection.
  2244. *
  2245. * The default function does nothing. User code can override this with
  2246. * > Strophe.Connection.xmlOutput = function (elem) {
  2247. * > (user code)
  2248. * > };
  2249. *
  2250. * Parameters:
  2251. * (XMLElement) elem - The XMLdata sent by the connection.
  2252. */
  2253. xmlOutput: function (elem)
  2254. {
  2255. return;
  2256. },
  2257. /** Function: rawInput
  2258. * User overrideable function that receives raw data coming into the
  2259. * connection.
  2260. *
  2261. * The default function does nothing. User code can override this with
  2262. * > Strophe.Connection.rawInput = function (data) {
  2263. * > (user code)
  2264. * > };
  2265. *
  2266. * Parameters:
  2267. * (String) data - The data received by the connection.
  2268. */
  2269. rawInput: function (data)
  2270. {
  2271. return;
  2272. },
  2273. /** Function: rawOutput
  2274. * User overrideable function that receives raw data sent to the
  2275. * connection.
  2276. *
  2277. * The default function does nothing. User code can override this with
  2278. * > Strophe.Connection.rawOutput = function (data) {
  2279. * > (user code)
  2280. * > };
  2281. *
  2282. * Parameters:
  2283. * (String) data - The data sent by the connection.
  2284. */
  2285. rawOutput: function (data)
  2286. {
  2287. return;
  2288. },
  2289. /** Function: send
  2290. * Send a stanza.
  2291. *
  2292. * This function is called to push data onto the send queue to
  2293. * go out over the wire. Whenever a request is sent to the BOSH
  2294. * server, all pending data is sent and the queue is flushed.
  2295. *
  2296. * Parameters:
  2297. * (XMLElement |
  2298. * [XMLElement] |
  2299. * Strophe.Builder) elem - The stanza to send.
  2300. */
  2301. send: function (elem)
  2302. {
  2303. if (elem === null) { return ; }
  2304. if (typeof(elem.sort) === "function") {
  2305. for (var i = 0; i < elem.length; i++) {
  2306. this._queueData(elem[i]);
  2307. }
  2308. } else if (typeof(elem.tree) === "function") {
  2309. this._queueData(elem.tree());
  2310. } else {
  2311. this._queueData(elem);
  2312. }
  2313. this._throttledRequestHandler();
  2314. clearTimeout(this._idleTimeout);
  2315. this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
  2316. },
  2317. /** Function: flush
  2318. * Immediately send any pending outgoing data.
  2319. *
  2320. * Normally send() queues outgoing data until the next idle period
  2321. * (100ms), which optimizes network use in the common cases when
  2322. * several send()s are called in succession. flush() can be used to
  2323. * immediately send all pending data.
  2324. */
  2325. flush: function ()
  2326. {
  2327. // cancel the pending idle period and run the idle function
  2328. // immediately
  2329. clearTimeout(this._idleTimeout);
  2330. this._onIdle();
  2331. },
  2332. /** Function: sendIQ
  2333. * Helper function to send IQ stanzas.
  2334. *
  2335. * Parameters:
  2336. * (XMLElement) elem - The stanza to send.
  2337. * (Function) callback - The callback function for a successful request.
  2338. * (Function) errback - The callback function for a failed or timed
  2339. * out request. On timeout, the stanza will be null.
  2340. * (Integer) timeout - The time specified in milliseconds for a
  2341. * timeout to occur.
  2342. *
  2343. * Returns:
  2344. * The id used to send the IQ.
  2345. */
  2346. sendIQ: function(elem, callback, errback, timeout) {
  2347. var timeoutHandler = null;
  2348. var that = this;
  2349. if (typeof(elem.tree) === "function") {
  2350. elem = elem.tree();
  2351. }
  2352. var id = elem.getAttribute('id');
  2353. // inject id if not found
  2354. if (!id) {
  2355. id = this.getUniqueId("sendIQ");
  2356. elem.setAttribute("id", id);
  2357. }
  2358. var handler = this.addHandler(function (stanza) {
  2359. // remove timeout handler if there is one
  2360. if (timeoutHandler) {
  2361. that.deleteTimedHandler(timeoutHandler);
  2362. }
  2363. var iqtype = stanza.getAttribute('type');
  2364. if (iqtype == 'result') {
  2365. if (callback) {
  2366. callback(stanza);
  2367. }
  2368. } else if (iqtype == 'error') {
  2369. if (errback) {
  2370. errback(stanza);
  2371. }
  2372. } else {
  2373. throw {
  2374. name: "StropheError",
  2375. message: "Got bad IQ type of " + iqtype
  2376. };
  2377. }
  2378. }, null, 'iq', null, id);
  2379. // if timeout specified, setup timeout handler.
  2380. if (timeout) {
  2381. timeoutHandler = this.addTimedHandler(timeout, function () {
  2382. // get rid of normal handler
  2383. that.deleteHandler(handler);
  2384. // call errback on timeout with null stanza
  2385. if (errback) {
  2386. errback(null);
  2387. }
  2388. return false;
  2389. });
  2390. }
  2391. this.send(elem);
  2392. return id;
  2393. },
  2394. /** PrivateFunction: _queueData
  2395. * Queue outgoing data for later sending. Also ensures that the data
  2396. * is a DOMElement.
  2397. */
  2398. _queueData: function (element) {
  2399. if (element === null ||
  2400. !element.tagName ||
  2401. !element.childNodes) {
  2402. throw {
  2403. name: "StropheError",
  2404. message: "Cannot queue non-DOMElement."
  2405. };
  2406. }
  2407. this._data.push(element);
  2408. },
  2409. /** PrivateFunction: _sendRestart
  2410. * Send an xmpp:restart stanza.
  2411. */
  2412. _sendRestart: function ()
  2413. {
  2414. this._data.push("restart");
  2415. this._throttledRequestHandler();
  2416. clearTimeout(this._idleTimeout);
  2417. this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
  2418. },
  2419. /** Function: addTimedHandler
  2420. * Add a timed handler to the connection.
  2421. *
  2422. * This function adds a timed handler. The provided handler will
  2423. * be called every period milliseconds until it returns false,
  2424. * the connection is terminated, or the handler is removed. Handlers
  2425. * that wish to continue being invoked should return true.
  2426. *
  2427. * Because of method binding it is necessary to save the result of
  2428. * this function if you wish to remove a handler with
  2429. * deleteTimedHandler().
  2430. *
  2431. * Note that user handlers are not active until authentication is
  2432. * successful.
  2433. *
  2434. * Parameters:
  2435. * (Integer) period - The period of the handler.
  2436. * (Function) handler - The callback function.
  2437. *
  2438. * Returns:
  2439. * A reference to the handler that can be used to remove it.
  2440. */
  2441. addTimedHandler: function (period, handler)
  2442. {
  2443. var thand = new Strophe.TimedHandler(period, handler);
  2444. this.addTimeds.push(thand);
  2445. return thand;
  2446. },
  2447. /** Function: deleteTimedHandler
  2448. * Delete a timed handler for a connection.
  2449. *
  2450. * This function removes a timed handler from the connection. The
  2451. * handRef parameter is *not* the function passed to addTimedHandler(),
  2452. * but is the reference returned from addTimedHandler().
  2453. *
  2454. * Parameters:
  2455. * (Strophe.TimedHandler) handRef - The handler reference.
  2456. */
  2457. deleteTimedHandler: function (handRef)
  2458. {
  2459. // this must be done in the Idle loop so that we don't change
  2460. // the handlers during iteration
  2461. this.removeTimeds.push(handRef);
  2462. },
  2463. /** Function: addHandler
  2464. * Add a stanza handler for the connection.
  2465. *
  2466. * This function adds a stanza handler to the connection. The
  2467. * handler callback will be called for any stanza that matches
  2468. * the parameters. Note that if multiple parameters are supplied,
  2469. * they must all match for the handler to be invoked.
  2470. *
  2471. * The handler will receive the stanza that triggered it as its argument.
  2472. * The handler should return true if it is to be invoked again;
  2473. * returning false will remove the handler after it returns.
  2474. *
  2475. * As a convenience, the ns parameters applies to the top level element
  2476. * and also any of its immediate children. This is primarily to make
  2477. * matching /iq/query elements easy.
  2478. *
  2479. * The options argument contains handler matching flags that affect how
  2480. * matches are determined. Currently the only flag is matchBare (a
  2481. * boolean). When matchBare is true, the from parameter and the from
  2482. * attribute on the stanza will be matched as bare JIDs instead of
  2483. * full JIDs. To use this, pass {matchBare: true} as the value of
  2484. * options. The default value for matchBare is false.
  2485. *
  2486. * The return value should be saved if you wish to remove the handler
  2487. * with deleteHandler().
  2488. *
  2489. * Parameters:
  2490. * (Function) handler - The user callback.
  2491. * (String) ns - The namespace to match.
  2492. * (String) name - The stanza name to match.
  2493. * (String) type - The stanza type attribute to match.
  2494. * (String) id - The stanza id attribute to match.
  2495. * (String) from - The stanza from attribute to match.
  2496. * (String) options - The handler options
  2497. *
  2498. * Returns:
  2499. * A reference to the handler that can be used to remove it.
  2500. */
  2501. addHandler: function (handler, ns, name, type, id, from, options)
  2502. {
  2503. var hand = new Strophe.Handler(handler, ns, name, type, id, from, options);
  2504. this.addHandlers.push(hand);
  2505. return hand;
  2506. },
  2507. /** Function: deleteHandler
  2508. * Delete a stanza handler for a connection.
  2509. *
  2510. * This function removes a stanza handler from the connection. The
  2511. * handRef parameter is *not* the function passed to addHandler(),
  2512. * but is the reference returned from addHandler().
  2513. *
  2514. * Parameters:
  2515. * (Strophe.Handler) handRef - The handler reference.
  2516. */
  2517. deleteHandler: function (handRef)
  2518. {
  2519. // this must be done in the Idle loop so that we don't change
  2520. // the handlers during iteration
  2521. this.removeHandlers.push(handRef);
  2522. },
  2523. /** Function: disconnect
  2524. * Start the graceful disconnection process.
  2525. *
  2526. * This function starts the disconnection process. This process starts
  2527. * by sending unavailable presence and sending BOSH body of type
  2528. * terminate. A timeout handler makes sure that disconnection happens
  2529. * even if the BOSH server does not respond.
  2530. *
  2531. * The user supplied connection callback will be notified of the
  2532. * progress as this process happens.
  2533. *
  2534. * Parameters:
  2535. * (String) reason - The reason the disconnect is occuring.
  2536. */
  2537. disconnect: function (reason)
  2538. {
  2539. this._changeConnectStatus(Strophe.Status.DISCONNECTING, reason);
  2540. Strophe.info("Disconnect was called because: " + reason);
  2541. if (this.connected) {
  2542. // setup timeout handler
  2543. this._disconnectTimeout = this._addSysTimedHandler(
  2544. 3000, this._onDisconnectTimeout.bind(this));
  2545. this._sendTerminate();
  2546. }
  2547. },
  2548. /** PrivateFunction: _changeConnectStatus
  2549. * _Private_ helper function that makes sure plugins and the user's
  2550. * callback are notified of connection status changes.
  2551. *
  2552. * Parameters:
  2553. * (Integer) status - the new connection status, one of the values
  2554. * in Strophe.Status
  2555. * (String) condition - the error condition or null
  2556. */
  2557. _changeConnectStatus: function (status, condition)
  2558. {
  2559. // notify all plugins listening for status changes
  2560. for (var k in Strophe._connectionPlugins) {
  2561. if (Strophe._connectionPlugins.hasOwnProperty(k)) {
  2562. var plugin = this[k];
  2563. if (plugin.statusChanged) {
  2564. try {
  2565. plugin.statusChanged(status, condition);
  2566. } catch (err) {
  2567. Strophe.error("" + k + " plugin caused an exception " +
  2568. "changing status: " + err);
  2569. }
  2570. }
  2571. }
  2572. }
  2573. // notify the user's callback
  2574. if (this.connect_callback) {
  2575. try {
  2576. this.connect_callback(status, condition);
  2577. } catch (e) {
  2578. Strophe.error("User connection callback caused an " +
  2579. "exception: " + e);
  2580. }
  2581. }
  2582. },
  2583. /** PrivateFunction: _buildBody
  2584. * _Private_ helper function to generate the <body/> wrapper for BOSH.
  2585. *
  2586. * Returns:
  2587. * A Strophe.Builder with a <body/> element.
  2588. */
  2589. _buildBody: function ()
  2590. {
  2591. var bodyWrap = $build('body', {
  2592. rid: this.rid++,
  2593. xmlns: Strophe.NS.HTTPBIND
  2594. });
  2595. if (this.sid !== null) {
  2596. bodyWrap.attrs({sid: this.sid});
  2597. }
  2598. return bodyWrap;
  2599. },
  2600. /** PrivateFunction: _removeRequest
  2601. * _Private_ function to remove a request from the queue.
  2602. *
  2603. * Parameters:
  2604. * (Strophe.Request) req - The request to remove.
  2605. */
  2606. _removeRequest: function (req)
  2607. {
  2608. Strophe.debug("removing request");
  2609. var i;
  2610. for (i = this._requests.length - 1; i >= 0; i--) {
  2611. if (req == this._requests[i]) {
  2612. this._requests.splice(i, 1);
  2613. }
  2614. }
  2615. // IE6 fails on setting to null, so set to empty function
  2616. req.xhr.onreadystatechange = function () {};
  2617. this._throttledRequestHandler();
  2618. },
  2619. /** PrivateFunction: _restartRequest
  2620. * _Private_ function to restart a request that is presumed dead.
  2621. *
  2622. * Parameters:
  2623. * (Integer) i - The index of the request in the queue.
  2624. */
  2625. _restartRequest: function (i)
  2626. {
  2627. var req = this._requests[i];
  2628. if (req.dead === null) {
  2629. req.dead = new Date();
  2630. }
  2631. this._processRequest(i);
  2632. },
  2633. /** PrivateFunction: _processRequest
  2634. * _Private_ function to process a request in the queue.
  2635. *
  2636. * This function takes requests off the queue and sends them and
  2637. * restarts dead requests.
  2638. *
  2639. * Parameters:
  2640. * (Integer) i - The index of the request in the queue.
  2641. */
  2642. _processRequest: function (i)
  2643. {
  2644. var req = this._requests[i];
  2645. var reqStatus = -1;
  2646. try {
  2647. if (req.xhr.readyState == 4) {
  2648. reqStatus = req.xhr.status;
  2649. }
  2650. } catch (e) {
  2651. Strophe.error("caught an error in _requests[" + i +
  2652. "], reqStatus: " + reqStatus);
  2653. }
  2654. if (typeof(reqStatus) == "undefined") {
  2655. reqStatus = -1;
  2656. }
  2657. // make sure we limit the number of retries
  2658. if (req.sends > this.maxRetries) {
  2659. this._onDisconnectTimeout();
  2660. return;
  2661. }
  2662. var time_elapsed = req.age();
  2663. var primaryTimeout = (!isNaN(time_elapsed) &&
  2664. time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait));
  2665. var secondaryTimeout = (req.dead !== null &&
  2666. req.timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait));
  2667. var requestCompletedWithServerError = (req.xhr.readyState == 4 &&
  2668. (reqStatus < 1 ||
  2669. reqStatus >= 500));
  2670. if (primaryTimeout || secondaryTimeout ||
  2671. requestCompletedWithServerError) {
  2672. if (secondaryTimeout) {
  2673. Strophe.error("Request " +
  2674. this._requests[i].id +
  2675. " timed out (secondary), restarting");
  2676. }
  2677. req.abort = true;
  2678. req.xhr.abort();
  2679. // setting to null fails on IE6, so set to empty function
  2680. req.xhr.onreadystatechange = function () {};
  2681. this._requests[i] = new Strophe.Request(req.xmlData,
  2682. req.origFunc,
  2683. req.rid,
  2684. req.sends);
  2685. req = this._requests[i];
  2686. }
  2687. if (req.xhr.readyState === 0) {
  2688. Strophe.debug("request id " + req.id +
  2689. "." + req.sends + " posting");
  2690. try {
  2691. req.xhr.open("POST", this.service, true);
  2692. } catch (e2) {
  2693. Strophe.error("XHR open failed.");
  2694. if (!this.connected) {
  2695. this._changeConnectStatus(Strophe.Status.CONNFAIL,
  2696. "bad-service");
  2697. }
  2698. this.disconnect();
  2699. return;
  2700. }
  2701. // Fires the XHR request -- may be invoked immediately
  2702. // or on a gradually expanding retry window for reconnects
  2703. var sendFunc = function () {
  2704. req.date = new Date();
  2705. req.xhr.send(req.data);
  2706. };
  2707. // Implement progressive backoff for reconnects --
  2708. // First retry (send == 1) should also be instantaneous
  2709. if (req.sends > 1) {
  2710. // Using a cube of the retry number creates a nicely
  2711. // expanding retry window
  2712. var backoff = Math.min(Math.floor(Strophe.TIMEOUT * this.wait),
  2713. Math.pow(req.sends, 3)) * 1000;
  2714. setTimeout(sendFunc, backoff);
  2715. } else {
  2716. sendFunc();
  2717. }
  2718. req.sends++;
  2719. if (this.xmlOutput !== Strophe.Connection.prototype.xmlOutput) {
  2720. this.xmlOutput(req.xmlData);
  2721. }
  2722. if (this.rawOutput !== Strophe.Connection.prototype.rawOutput) {
  2723. this.rawOutput(req.data);
  2724. }
  2725. } else {
  2726. Strophe.debug("_processRequest: " +
  2727. (i === 0 ? "first" : "second") +
  2728. " request has readyState of " +
  2729. req.xhr.readyState);
  2730. }
  2731. },
  2732. /** PrivateFunction: _throttledRequestHandler
  2733. * _Private_ function to throttle requests to the connection window.
  2734. *
  2735. * This function makes sure we don't send requests so fast that the
  2736. * request ids overflow the connection window in the case that one
  2737. * request died.
  2738. */
  2739. _throttledRequestHandler: function ()
  2740. {
  2741. if (!this._requests) {
  2742. Strophe.debug("_throttledRequestHandler called with " +
  2743. "undefined requests");
  2744. } else {
  2745. Strophe.debug("_throttledRequestHandler called with " +
  2746. this._requests.length + " requests");
  2747. }
  2748. if (!this._requests || this._requests.length === 0) {
  2749. return;
  2750. }
  2751. if (this._requests.length > 0) {
  2752. this._processRequest(0);
  2753. }
  2754. if (this._requests.length > 1 &&
  2755. Math.abs(this._requests[0].rid -
  2756. this._requests[1].rid) < this.window) {
  2757. this._processRequest(1);
  2758. }
  2759. },
  2760. /** PrivateFunction: _onRequestStateChange
  2761. * _Private_ handler for Strophe.Request state changes.
  2762. *
  2763. * This function is called when the XMLHttpRequest readyState changes.
  2764. * It contains a lot of error handling logic for the many ways that
  2765. * requests can fail, and calls the request callback when requests
  2766. * succeed.
  2767. *
  2768. * Parameters:
  2769. * (Function) func - The handler for the request.
  2770. * (Strophe.Request) req - The request that is changing readyState.
  2771. */
  2772. _onRequestStateChange: function (func, req)
  2773. {
  2774. Strophe.debug("request id " + req.id +
  2775. "." + req.sends + " state changed to " +
  2776. req.xhr.readyState);
  2777. if (req.abort) {
  2778. req.abort = false;
  2779. return;
  2780. }
  2781. // request complete
  2782. var reqStatus;
  2783. if (req.xhr.readyState == 4) {
  2784. reqStatus = 0;
  2785. try {
  2786. reqStatus = req.xhr.status;
  2787. } catch (e) {
  2788. // ignore errors from undefined status attribute. works
  2789. // around a browser bug
  2790. }
  2791. if (typeof(reqStatus) == "undefined") {
  2792. reqStatus = 0;
  2793. }
  2794. if (this.disconnecting) {
  2795. if (reqStatus >= 400) {
  2796. this._hitError(reqStatus);
  2797. return;
  2798. }
  2799. }
  2800. var reqIs0 = (this._requests[0] == req);
  2801. var reqIs1 = (this._requests[1] == req);
  2802. if ((reqStatus > 0 && reqStatus < 500) || req.sends > 5) {
  2803. // remove from internal queue
  2804. this._removeRequest(req);
  2805. Strophe.debug("request id " +
  2806. req.id +
  2807. " should now be removed");
  2808. }
  2809. // request succeeded
  2810. if (reqStatus == 200) {
  2811. // if request 1 finished, or request 0 finished and request
  2812. // 1 is over Strophe.SECONDARY_TIMEOUT seconds old, we need to
  2813. // restart the other - both will be in the first spot, as the
  2814. // completed request has been removed from the queue already
  2815. if (reqIs1 ||
  2816. (reqIs0 && this._requests.length > 0 &&
  2817. this._requests[0].age() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait))) {
  2818. this._restartRequest(0);
  2819. }
  2820. // call handler
  2821. Strophe.debug("request id " +
  2822. req.id + "." +
  2823. req.sends + " got 200");
  2824. func(req);
  2825. this.errors = 0;
  2826. } else {
  2827. Strophe.error("request id " +
  2828. req.id + "." +
  2829. req.sends + " error " + reqStatus +
  2830. " happened");
  2831. if (reqStatus === 0 ||
  2832. (reqStatus >= 400 && reqStatus < 600) ||
  2833. reqStatus >= 12000) {
  2834. this._hitError(reqStatus);
  2835. if (reqStatus >= 400 && reqStatus < 500) {
  2836. this._changeConnectStatus(Strophe.Status.DISCONNECTING,
  2837. null);
  2838. this._doDisconnect();
  2839. }
  2840. }
  2841. }
  2842. if (!((reqStatus > 0 && reqStatus < 500) ||
  2843. req.sends > 5)) {
  2844. this._throttledRequestHandler();
  2845. }
  2846. }
  2847. },
  2848. /** PrivateFunction: _hitError
  2849. * _Private_ function to handle the error count.
  2850. *
  2851. * Requests are resent automatically until their error count reaches
  2852. * 5. Each time an error is encountered, this function is called to
  2853. * increment the count and disconnect if the count is too high.
  2854. *
  2855. * Parameters:
  2856. * (Integer) reqStatus - The request status.
  2857. */
  2858. _hitError: function (reqStatus)
  2859. {
  2860. this.errors++;
  2861. Strophe.warn("request errored, status: " + reqStatus +
  2862. ", number of errors: " + this.errors);
  2863. if (this.errors > 4) {
  2864. this._onDisconnectTimeout();
  2865. }
  2866. },
  2867. /** PrivateFunction: _doDisconnect
  2868. * _Private_ function to disconnect.
  2869. *
  2870. * This is the last piece of the disconnection logic. This resets the
  2871. * connection and alerts the user's connection callback.
  2872. */
  2873. _doDisconnect: function ()
  2874. {
  2875. Strophe.info("_doDisconnect was called");
  2876. this.authenticated = false;
  2877. this.disconnecting = false;
  2878. this.sid = null;
  2879. this.streamId = null;
  2880. this.rid = Math.floor(Math.random() * 4294967295);
  2881. // tell the parent we disconnected
  2882. if (this.connected) {
  2883. this._changeConnectStatus(Strophe.Status.DISCONNECTED, null);
  2884. this.connected = false;
  2885. }
  2886. // delete handlers
  2887. this.handlers = [];
  2888. this.timedHandlers = [];
  2889. this.removeTimeds = [];
  2890. this.removeHandlers = [];
  2891. this.addTimeds = [];
  2892. this.addHandlers = [];
  2893. },
  2894. /** PrivateFunction: _dataRecv
  2895. * _Private_ handler to processes incoming data from the the connection.
  2896. *
  2897. * Except for _connect_cb handling the initial connection request,
  2898. * this function handles the incoming data for all requests. This
  2899. * function also fires stanza handlers that match each incoming
  2900. * stanza.
  2901. *
  2902. * Parameters:
  2903. * (Strophe.Request) req - The request that has data ready.
  2904. */
  2905. _dataRecv: function (req)
  2906. {
  2907. try {
  2908. var elem = req.getResponse();
  2909. } catch (e) {
  2910. if (e != "parsererror") { throw e; }
  2911. this.disconnect("strophe-parsererror");
  2912. }
  2913. if (elem === null) { return; }
  2914. if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
  2915. this.xmlInput(elem);
  2916. }
  2917. if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
  2918. this.rawInput(Strophe.serialize(elem));
  2919. }
  2920. // remove handlers scheduled for deletion
  2921. var i, hand;
  2922. while (this.removeHandlers.length > 0) {
  2923. hand = this.removeHandlers.pop();
  2924. i = this.handlers.indexOf(hand);
  2925. if (i >= 0) {
  2926. this.handlers.splice(i, 1);
  2927. }
  2928. }
  2929. // add handlers scheduled for addition
  2930. while (this.addHandlers.length > 0) {
  2931. this.handlers.push(this.addHandlers.pop());
  2932. }
  2933. // handle graceful disconnect
  2934. if (this.disconnecting && this._requests.length === 0) {
  2935. this.deleteTimedHandler(this._disconnectTimeout);
  2936. this._disconnectTimeout = null;
  2937. this._doDisconnect();
  2938. return;
  2939. }
  2940. var typ = elem.getAttribute("type");
  2941. var cond, conflict;
  2942. if (typ !== null && typ == "terminate") {
  2943. // Don't process stanzas that come in after disconnect
  2944. if (this.disconnecting) {
  2945. return;
  2946. }
  2947. // an error occurred
  2948. cond = elem.getAttribute("condition");
  2949. conflict = elem.getElementsByTagName("conflict");
  2950. if (cond !== null) {
  2951. if (cond == "remote-stream-error" && conflict.length > 0) {
  2952. cond = "conflict";
  2953. }
  2954. this._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
  2955. } else {
  2956. this._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown");
  2957. }
  2958. this.disconnect();
  2959. return;
  2960. }
  2961. // send each incoming stanza through the handler chain
  2962. var that = this;
  2963. Strophe.forEachChild(elem, null, function (child) {
  2964. var i, newList;
  2965. // process handlers
  2966. newList = that.handlers;
  2967. that.handlers = [];
  2968. for (i = 0; i < newList.length; i++) {
  2969. var hand = newList[i];
  2970. // encapsulate 'handler.run' not to lose the whole handler list if
  2971. // one of the handlers throws an exception
  2972. try {
  2973. if (hand.isMatch(child) &&
  2974. (that.authenticated || !hand.user)) {
  2975. if (hand.run(child)) {
  2976. that.handlers.push(hand);
  2977. }
  2978. } else {
  2979. that.handlers.push(hand);
  2980. }
  2981. } catch(e) {
  2982. //if the handler throws an exception, we consider it as false
  2983. }
  2984. }
  2985. });
  2986. },
  2987. /** PrivateFunction: _sendTerminate
  2988. * _Private_ function to send initial disconnect sequence.
  2989. *
  2990. * This is the first step in a graceful disconnect. It sends
  2991. * the BOSH server a terminate body and includes an unavailable
  2992. * presence if authentication has completed.
  2993. */
  2994. _sendTerminate: function ()
  2995. {
  2996. Strophe.info("_sendTerminate was called");
  2997. var body = this._buildBody().attrs({type: "terminate"});
  2998. if (this.authenticated) {
  2999. body.c('presence', {
  3000. xmlns: Strophe.NS.CLIENT,
  3001. type: 'unavailable'
  3002. });
  3003. }
  3004. this.disconnecting = true;
  3005. var req = new Strophe.Request(body.tree(),
  3006. this._onRequestStateChange.bind(
  3007. this, this._dataRecv.bind(this)),
  3008. body.tree().getAttribute("rid"));
  3009. this._requests.push(req);
  3010. this._throttledRequestHandler();
  3011. },
  3012. /** PrivateFunction: _connect_cb
  3013. * _Private_ handler for initial connection request.
  3014. *
  3015. * This handler is used to process the initial connection request
  3016. * response from the BOSH server. It is used to set up authentication
  3017. * handlers and start the authentication process.
  3018. *
  3019. * SASL authentication will be attempted if available, otherwise
  3020. * the code will fall back to legacy authentication.
  3021. *
  3022. * Parameters:
  3023. * (Strophe.Request) req - The current request.
  3024. * (Function) _callback - low level (xmpp) connect callback function.
  3025. * Useful for plugins with their own xmpp connect callback (when their)
  3026. * want to do something special).
  3027. */
  3028. _connect_cb: function (req, _callback)
  3029. {
  3030. Strophe.info("_connect_cb was called");
  3031. this.connected = true;
  3032. var bodyWrap = req.getResponse();
  3033. if (!bodyWrap) { return; }
  3034. if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
  3035. this.xmlInput(bodyWrap);
  3036. }
  3037. if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
  3038. this.rawInput(Strophe.serialize(bodyWrap));
  3039. }
  3040. var typ = bodyWrap.getAttribute("type");
  3041. var cond, conflict;
  3042. if (typ !== null && typ == "terminate") {
  3043. // an error occurred
  3044. cond = bodyWrap.getAttribute("condition");
  3045. conflict = bodyWrap.getElementsByTagName("conflict");
  3046. if (cond !== null) {
  3047. if (cond == "remote-stream-error" && conflict.length > 0) {
  3048. cond = "conflict";
  3049. }
  3050. this._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
  3051. } else {
  3052. this._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown");
  3053. }
  3054. return;
  3055. }
  3056. // check to make sure we don't overwrite these if _connect_cb is
  3057. // called multiple times in the case of missing stream:features
  3058. if (!this.sid) {
  3059. this.sid = bodyWrap.getAttribute("sid");
  3060. }
  3061. if (!this.stream_id) {
  3062. this.stream_id = bodyWrap.getAttribute("authid");
  3063. }
  3064. var wind = bodyWrap.getAttribute('requests');
  3065. if (wind) { this.window = parseInt(wind, 10); }
  3066. var hold = bodyWrap.getAttribute('hold');
  3067. if (hold) { this.hold = parseInt(hold, 10); }
  3068. var wait = bodyWrap.getAttribute('wait');
  3069. if (wait) { this.wait = parseInt(wait, 10); }
  3070. this._authentication.sasl_scram_sha1 = false;
  3071. this._authentication.sasl_plain = false;
  3072. this._authentication.sasl_digest_md5 = false;
  3073. this._authentication.sasl_anonymous = false;
  3074. this._authentication.legacy_auth = false;
  3075. // Check for the stream:features tag
  3076. var hasFeatures = bodyWrap.getElementsByTagName("stream:features").length > 0;
  3077. if (!hasFeatures) {
  3078. hasFeatures = bodyWrap.getElementsByTagName("features").length > 0;
  3079. }
  3080. var mechanisms = bodyWrap.getElementsByTagName("mechanism");
  3081. var i, mech, auth_str, hashed_auth_str,
  3082. found_authentication = false;
  3083. if (hasFeatures && mechanisms.length > 0) {
  3084. var missmatchedmechs = 0;
  3085. for (i = 0; i < mechanisms.length; i++) {
  3086. mech = Strophe.getText(mechanisms[i]);
  3087. if (mech == 'SCRAM-SHA-1') {
  3088. this._authentication.sasl_scram_sha1 = true;
  3089. } else if (mech == 'DIGEST-MD5') {
  3090. this._authentication.sasl_digest_md5 = true;
  3091. } else if (mech == 'PLAIN') {
  3092. this._authentication.sasl_plain = true;
  3093. } else if (mech == 'ANONYMOUS') {
  3094. this._authentication.sasl_anonymous = true;
  3095. } else missmatchedmechs++;
  3096. }
  3097. this._authentication.legacy_auth =
  3098. bodyWrap.getElementsByTagName("auth").length > 0;
  3099. found_authentication =
  3100. this._authentication.legacy_auth ||
  3101. missmatchedmechs < mechanisms.length;
  3102. }
  3103. if (!found_authentication) {
  3104. _callback = _callback || this._connect_cb;
  3105. // we didn't get stream:features yet, so we need wait for it
  3106. // by sending a blank poll request
  3107. var body = this._buildBody();
  3108. this._requests.push(
  3109. new Strophe.Request(body.tree(),
  3110. this._onRequestStateChange.bind(
  3111. this, _callback.bind(this)),
  3112. body.tree().getAttribute("rid")));
  3113. this._throttledRequestHandler();
  3114. return;
  3115. }
  3116. if (this.do_authentication !== false)
  3117. this.authenticate();
  3118. },
  3119. /** Function: authenticate
  3120. * Set up authentication
  3121. *
  3122. * Contiunues the initial connection request by setting up authentication
  3123. * handlers and start the authentication process.
  3124. *
  3125. * SASL authentication will be attempted if available, otherwise
  3126. * the code will fall back to legacy authentication.
  3127. *
  3128. */
  3129. authenticate: function ()
  3130. {
  3131. if (Strophe.getNodeFromJid(this.jid) === null &&
  3132. this._authentication.sasl_anonymous) {
  3133. this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
  3134. this._sasl_success_handler = this._addSysHandler(
  3135. this._sasl_success_cb.bind(this), null,
  3136. "success", null, null);
  3137. this._sasl_failure_handler = this._addSysHandler(
  3138. this._sasl_failure_cb.bind(this), null,
  3139. "failure", null, null);
  3140. this.send($build("auth", {
  3141. xmlns: Strophe.NS.SASL,
  3142. mechanism: "ANONYMOUS"
  3143. }).tree());
  3144. } else if (Strophe.getNodeFromJid(this.jid) === null) {
  3145. // we don't have a node, which is required for non-anonymous
  3146. // client connections
  3147. this._changeConnectStatus(Strophe.Status.CONNFAIL,
  3148. 'x-strophe-bad-non-anon-jid');
  3149. this.disconnect();
  3150. } else if (this._authentication.sasl_scram_sha1) {
  3151. var cnonce = MD5.hexdigest(Math.random() * 1234567890);
  3152. var auth_str = "n=" + Strophe.getNodeFromJid(this.jid);
  3153. auth_str += ",r=";
  3154. auth_str += cnonce;
  3155. this._sasl_data["cnonce"] = cnonce;
  3156. this._sasl_data["client-first-message-bare"] = auth_str;
  3157. auth_str = "n,," + auth_str;
  3158. this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
  3159. this._sasl_challenge_handler = this._addSysHandler(
  3160. this._sasl_scram_challenge_cb.bind(this), null,
  3161. "challenge", null, null);
  3162. this._sasl_failure_handler = this._addSysHandler(
  3163. this._sasl_failure_cb.bind(this), null,
  3164. "failure", null, null);
  3165. this.send($build("auth", {
  3166. xmlns: Strophe.NS.SASL,
  3167. mechanism: "SCRAM-SHA-1"
  3168. }).t(Base64.encode(auth_str)).tree());
  3169. } else if (this._authentication.sasl_digest_md5) {
  3170. this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
  3171. this._sasl_challenge_handler = this._addSysHandler(
  3172. this._sasl_digest_challenge1_cb.bind(this), null,
  3173. "challenge", null, null);
  3174. this._sasl_failure_handler = this._addSysHandler(
  3175. this._sasl_failure_cb.bind(this), null,
  3176. "failure", null, null);
  3177. this.send($build("auth", {
  3178. xmlns: Strophe.NS.SASL,
  3179. mechanism: "DIGEST-MD5"
  3180. }).tree());
  3181. } else if (this._authentication.sasl_plain) {
  3182. // Build the plain auth string (barejid null
  3183. // username null password) and base 64 encoded.
  3184. auth_str = Strophe.getBareJidFromJid(this.jid);
  3185. auth_str = auth_str + "\u0000";
  3186. auth_str = auth_str + Strophe.getNodeFromJid(this.jid);
  3187. auth_str = auth_str + "\u0000";
  3188. auth_str = auth_str + this.pass;
  3189. this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
  3190. this._sasl_success_handler = this._addSysHandler(
  3191. this._sasl_success_cb.bind(this), null,
  3192. "success", null, null);
  3193. this._sasl_failure_handler = this._addSysHandler(
  3194. this._sasl_failure_cb.bind(this), null,
  3195. "failure", null, null);
  3196. hashed_auth_str = Base64.encode(auth_str);
  3197. this.send($build("auth", {
  3198. xmlns: Strophe.NS.SASL,
  3199. mechanism: "PLAIN"
  3200. }).t(hashed_auth_str).tree());
  3201. } else {
  3202. this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
  3203. this._addSysHandler(this._auth1_cb.bind(this), null, null,
  3204. null, "_auth_1");
  3205. this.send($iq({
  3206. type: "get",
  3207. to: this.domain,
  3208. id: "_auth_1"
  3209. }).c("query", {
  3210. xmlns: Strophe.NS.AUTH
  3211. }).c("username", {}).t(Strophe.getNodeFromJid(this.jid)).tree());
  3212. }
  3213. },
  3214. /** PrivateFunction: _sasl_digest_challenge1_cb
  3215. * _Private_ handler for DIGEST-MD5 SASL authentication.
  3216. *
  3217. * Parameters:
  3218. * (XMLElement) elem - The challenge stanza.
  3219. *
  3220. * Returns:
  3221. * false to remove the handler.
  3222. */
  3223. _sasl_digest_challenge1_cb: function (elem)
  3224. {
  3225. var attribMatch = /([a-z]+)=("[^"]+"|[^,"]+)(?:,|$)/;
  3226. var challenge = Base64.decode(Strophe.getText(elem));
  3227. var cnonce = MD5.hexdigest("" + (Math.random() * 1234567890));
  3228. var realm = "";
  3229. var host = null;
  3230. var nonce = "";
  3231. var qop = "";
  3232. var matches;
  3233. // remove unneeded handlers
  3234. this.deleteHandler(this._sasl_failure_handler);
  3235. while (challenge.match(attribMatch)) {
  3236. matches = challenge.match(attribMatch);
  3237. challenge = challenge.replace(matches[0], "");
  3238. matches[2] = matches[2].replace(/^"(.+)"$/, "$1");
  3239. switch (matches[1]) {
  3240. case "realm":
  3241. realm = matches[2];
  3242. break;
  3243. case "nonce":
  3244. nonce = matches[2];
  3245. break;
  3246. case "qop":
  3247. qop = matches[2];
  3248. break;
  3249. case "host":
  3250. host = matches[2];
  3251. break;
  3252. }
  3253. }
  3254. var digest_uri = "xmpp/" + this.domain;
  3255. if (host !== null) {
  3256. digest_uri = digest_uri + "/" + host;
  3257. }
  3258. var A1 = MD5.hash(Strophe.getNodeFromJid(this.jid) +
  3259. ":" + realm + ":" + this.pass) +
  3260. ":" + nonce + ":" + cnonce;
  3261. var A2 = 'AUTHENTICATE:' + digest_uri;
  3262. var responseText = "";
  3263. responseText += 'username=' +
  3264. this._quote(Strophe.getNodeFromJid(this.jid)) + ',';
  3265. responseText += 'realm=' + this._quote(realm) + ',';
  3266. responseText += 'nonce=' + this._quote(nonce) + ',';
  3267. responseText += 'cnonce=' + this._quote(cnonce) + ',';
  3268. responseText += 'nc="00000001",';
  3269. responseText += 'qop="auth",';
  3270. responseText += 'digest-uri=' + this._quote(digest_uri) + ',';
  3271. responseText += 'response=' + this._quote(
  3272. MD5.hexdigest(MD5.hexdigest(A1) + ":" +
  3273. nonce + ":00000001:" +
  3274. cnonce + ":auth:" +
  3275. MD5.hexdigest(A2))) + ',';
  3276. responseText += 'charset="utf-8"';
  3277. this._sasl_challenge_handler = this._addSysHandler(
  3278. this._sasl_digest_challenge2_cb.bind(this), null,
  3279. "challenge", null, null);
  3280. this._sasl_success_handler = this._addSysHandler(
  3281. this._sasl_success_cb.bind(this), null,
  3282. "success", null, null);
  3283. this._sasl_failure_handler = this._addSysHandler(
  3284. this._sasl_failure_cb.bind(this), null,
  3285. "failure", null, null);
  3286. this.send($build('response', {
  3287. xmlns: Strophe.NS.SASL
  3288. }).t(Base64.encode(responseText)).tree());
  3289. return false;
  3290. },
  3291. /** PrivateFunction: _quote
  3292. * _Private_ utility function to backslash escape and quote strings.
  3293. *
  3294. * Parameters:
  3295. * (String) str - The string to be quoted.
  3296. *
  3297. * Returns:
  3298. * quoted string
  3299. */
  3300. _quote: function (str)
  3301. {
  3302. return '"' + str.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"';
  3303. //" end string workaround for emacs
  3304. },
  3305. /** PrivateFunction: _sasl_digest_challenge2_cb
  3306. * _Private_ handler for second step of DIGEST-MD5 SASL authentication.
  3307. *
  3308. * Parameters:
  3309. * (XMLElement) elem - The challenge stanza.
  3310. *
  3311. * Returns:
  3312. * false to remove the handler.
  3313. */
  3314. _sasl_digest_challenge2_cb: function (elem)
  3315. {
  3316. // remove unneeded handlers
  3317. this.deleteHandler(this._sasl_success_handler);
  3318. this.deleteHandler(this._sasl_failure_handler);
  3319. this._sasl_success_handler = this._addSysHandler(
  3320. this._sasl_success_cb.bind(this), null,
  3321. "success", null, null);
  3322. this._sasl_failure_handler = this._addSysHandler(
  3323. this._sasl_failure_cb.bind(this), null,
  3324. "failure", null, null);
  3325. this.send($build('response', {xmlns: Strophe.NS.SASL}).tree());
  3326. return false;
  3327. },
  3328. /** PrivateFunction: _sasl_scram_challenge_cb
  3329. * _Private_ handler for SCRAM-SHA-1 SASL authentication.
  3330. *
  3331. * Parameters:
  3332. * (XMLElement) elem - The challenge stanza.
  3333. *
  3334. * Returns:
  3335. * false to remove the handler.
  3336. */
  3337. _sasl_scram_challenge_cb: function (elem)
  3338. {
  3339. var nonce, salt, iter, Hi, U, U_old;
  3340. var clientKey, serverKey, clientSignature;
  3341. var responseText = "c=biws,";
  3342. var challenge = Base64.decode(Strophe.getText(elem));
  3343. var authMessage = this._sasl_data["client-first-message-bare"] + "," +
  3344. challenge + ",";
  3345. var cnonce = this._sasl_data["cnonce"]
  3346. var attribMatch = /([a-z]+)=([^,]+)(,|$)/;
  3347. // remove unneeded handlers
  3348. this.deleteHandler(this._sasl_failure_handler);
  3349. while (challenge.match(attribMatch)) {
  3350. matches = challenge.match(attribMatch);
  3351. challenge = challenge.replace(matches[0], "");
  3352. switch (matches[1]) {
  3353. case "r":
  3354. nonce = matches[2];
  3355. break;
  3356. case "s":
  3357. salt = matches[2];
  3358. break;
  3359. case "i":
  3360. iter = matches[2];
  3361. break;
  3362. }
  3363. }
  3364. if (!(nonce.substr(0, cnonce.length) === cnonce)) {
  3365. this._sasl_data = [];
  3366. return this._sasl_failure_cb(null);
  3367. }
  3368. responseText += "r=" + nonce;
  3369. authMessage += responseText;
  3370. salt = Base64.decode(salt);
  3371. salt += "\0\0\0\1";
  3372. Hi = U_old = core_hmac_sha1(this.pass, salt);
  3373. for (i = 1; i < iter; i++) {
  3374. U = core_hmac_sha1(this.pass, binb2str(U_old));
  3375. for (k = 0; k < 5; k++) {
  3376. Hi[k] ^= U[k];
  3377. }
  3378. U_old = U;
  3379. }
  3380. Hi = binb2str(Hi);
  3381. clientKey = core_hmac_sha1(Hi, "Client Key");
  3382. serverKey = str_hmac_sha1(Hi, "Server Key");
  3383. clientSignature = core_hmac_sha1(str_sha1(binb2str(clientKey)), authMessage);
  3384. this._sasl_data["server-signature"] = b64_hmac_sha1(serverKey, authMessage);
  3385. for (k = 0; k < 5; k++) {
  3386. clientKey[k] ^= clientSignature[k];
  3387. }
  3388. responseText += ",p=" + Base64.encode(binb2str(clientKey));
  3389. this._sasl_success_handler = this._addSysHandler(
  3390. this._sasl_success_cb.bind(this), null,
  3391. "success", null, null);
  3392. this._sasl_failure_handler = this._addSysHandler(
  3393. this._sasl_failure_cb.bind(this), null,
  3394. "failure", null, null);
  3395. this.send($build('response', {
  3396. xmlns: Strophe.NS.SASL
  3397. }).t(Base64.encode(responseText)).tree());
  3398. return false;
  3399. },
  3400. /** PrivateFunction: _auth1_cb
  3401. * _Private_ handler for legacy authentication.
  3402. *
  3403. * This handler is called in response to the initial <iq type='get'/>
  3404. * for legacy authentication. It builds an authentication <iq/> and
  3405. * sends it, creating a handler (calling back to _auth2_cb()) to
  3406. * handle the result
  3407. *
  3408. * Parameters:
  3409. * (XMLElement) elem - The stanza that triggered the callback.
  3410. *
  3411. * Returns:
  3412. * false to remove the handler.
  3413. */
  3414. _auth1_cb: function (elem)
  3415. {
  3416. // build plaintext auth iq
  3417. var iq = $iq({type: "set", id: "_auth_2"})
  3418. .c('query', {xmlns: Strophe.NS.AUTH})
  3419. .c('username', {}).t(Strophe.getNodeFromJid(this.jid))
  3420. .up()
  3421. .c('password').t(this.pass);
  3422. if (!Strophe.getResourceFromJid(this.jid)) {
  3423. // since the user has not supplied a resource, we pick
  3424. // a default one here. unlike other auth methods, the server
  3425. // cannot do this for us.
  3426. this.jid = Strophe.getBareJidFromJid(this.jid) + '/strophe';
  3427. }
  3428. iq.up().c('resource', {}).t(Strophe.getResourceFromJid(this.jid));
  3429. this._addSysHandler(this._auth2_cb.bind(this), null,
  3430. null, null, "_auth_2");
  3431. this.send(iq.tree());
  3432. return false;
  3433. },
  3434. /** PrivateFunction: _sasl_success_cb
  3435. * _Private_ handler for succesful SASL authentication.
  3436. *
  3437. * Parameters:
  3438. * (XMLElement) elem - The matching stanza.
  3439. *
  3440. * Returns:
  3441. * false to remove the handler.
  3442. */
  3443. _sasl_success_cb: function (elem)
  3444. {
  3445. if (this._sasl_data["server-signature"]) {
  3446. var serverSignature;
  3447. var success = Base64.decode(Strophe.getText(elem));
  3448. var attribMatch = /([a-z]+)=([^,]+)(,|$)/;
  3449. matches = success.match(attribMatch);
  3450. if (matches[1] == "v") {
  3451. serverSignature = matches[2];
  3452. }
  3453. if (serverSignature != this._sasl_data["server-signature"]) {
  3454. // remove old handlers
  3455. this.deleteHandler(this._sasl_failure_handler);
  3456. this._sasl_failure_handler = null;
  3457. if (this._sasl_challenge_handler) {
  3458. this.deleteHandler(this._sasl_challenge_handler);
  3459. this._sasl_challenge_handler = null;
  3460. }
  3461. this._sasl_data = [];
  3462. return this._sasl_failure_cb(null);
  3463. }
  3464. }
  3465. Strophe.info("SASL authentication succeeded.");
  3466. // remove old handlers
  3467. this.deleteHandler(this._sasl_failure_handler);
  3468. this._sasl_failure_handler = null;
  3469. if (this._sasl_challenge_handler) {
  3470. this.deleteHandler(this._sasl_challenge_handler);
  3471. this._sasl_challenge_handler = null;
  3472. }
  3473. this._addSysHandler(this._sasl_auth1_cb.bind(this), null,
  3474. "stream:features", null, null);
  3475. // we must send an xmpp:restart now
  3476. this._sendRestart();
  3477. return false;
  3478. },
  3479. /** PrivateFunction: _sasl_auth1_cb
  3480. * _Private_ handler to start stream binding.
  3481. *
  3482. * Parameters:
  3483. * (XMLElement) elem - The matching stanza.
  3484. *
  3485. * Returns:
  3486. * false to remove the handler.
  3487. */
  3488. _sasl_auth1_cb: function (elem)
  3489. {
  3490. // save stream:features for future usage
  3491. this.features = elem;
  3492. var i, child;
  3493. for (i = 0; i < elem.childNodes.length; i++) {
  3494. child = elem.childNodes[i];
  3495. if (child.nodeName == 'bind') {
  3496. this.do_bind = true;
  3497. }
  3498. if (child.nodeName == 'session') {
  3499. this.do_session = true;
  3500. }
  3501. }
  3502. if (!this.do_bind) {
  3503. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
  3504. return false;
  3505. } else {
  3506. this._addSysHandler(this._sasl_bind_cb.bind(this), null, null,
  3507. null, "_bind_auth_2");
  3508. var resource = Strophe.getResourceFromJid(this.jid);
  3509. if (resource) {
  3510. this.send($iq({type: "set", id: "_bind_auth_2"})
  3511. .c('bind', {xmlns: Strophe.NS.BIND})
  3512. .c('resource', {}).t(resource).tree());
  3513. } else {
  3514. this.send($iq({type: "set", id: "_bind_auth_2"})
  3515. .c('bind', {xmlns: Strophe.NS.BIND})
  3516. .tree());
  3517. }
  3518. }
  3519. return false;
  3520. },
  3521. /** PrivateFunction: _sasl_bind_cb
  3522. * _Private_ handler for binding result and session start.
  3523. *
  3524. * Parameters:
  3525. * (XMLElement) elem - The matching stanza.
  3526. *
  3527. * Returns:
  3528. * false to remove the handler.
  3529. */
  3530. _sasl_bind_cb: function (elem)
  3531. {
  3532. if (elem.getAttribute("type") == "error") {
  3533. Strophe.info("SASL binding failed.");
  3534. var conflict = elem.getElementsByTagName("conflict"), condition;
  3535. if (conflict.length > 0) {
  3536. condition = 'conflict';
  3537. }
  3538. this._changeConnectStatus(Strophe.Status.AUTHFAIL, condition);
  3539. return false;
  3540. }
  3541. // TODO - need to grab errors
  3542. var bind = elem.getElementsByTagName("bind");
  3543. var jidNode;
  3544. if (bind.length > 0) {
  3545. // Grab jid
  3546. jidNode = bind[0].getElementsByTagName("jid");
  3547. if (jidNode.length > 0) {
  3548. this.jid = Strophe.getText(jidNode[0]);
  3549. if (this.do_session) {
  3550. this._addSysHandler(this._sasl_session_cb.bind(this),
  3551. null, null, null, "_session_auth_2");
  3552. this.send($iq({type: "set", id: "_session_auth_2"})
  3553. .c('session', {xmlns: Strophe.NS.SESSION})
  3554. .tree());
  3555. } else {
  3556. this.authenticated = true;
  3557. this._changeConnectStatus(Strophe.Status.CONNECTED, null);
  3558. }
  3559. }
  3560. } else {
  3561. Strophe.info("SASL binding failed.");
  3562. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
  3563. return false;
  3564. }
  3565. },
  3566. /** PrivateFunction: _sasl_session_cb
  3567. * _Private_ handler to finish successful SASL connection.
  3568. *
  3569. * This sets Connection.authenticated to true on success, which
  3570. * starts the processing of user handlers.
  3571. *
  3572. * Parameters:
  3573. * (XMLElement) elem - The matching stanza.
  3574. *
  3575. * Returns:
  3576. * false to remove the handler.
  3577. */
  3578. _sasl_session_cb: function (elem)
  3579. {
  3580. if (elem.getAttribute("type") == "result") {
  3581. this.authenticated = true;
  3582. this._changeConnectStatus(Strophe.Status.CONNECTED, null);
  3583. } else if (elem.getAttribute("type") == "error") {
  3584. Strophe.info("Session creation failed.");
  3585. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
  3586. return false;
  3587. }
  3588. return false;
  3589. },
  3590. /** PrivateFunction: _sasl_failure_cb
  3591. * _Private_ handler for SASL authentication failure.
  3592. *
  3593. * Parameters:
  3594. * (XMLElement) elem - The matching stanza.
  3595. *
  3596. * Returns:
  3597. * false to remove the handler.
  3598. */
  3599. _sasl_failure_cb: function (elem)
  3600. {
  3601. // delete unneeded handlers
  3602. if (this._sasl_success_handler) {
  3603. this.deleteHandler(this._sasl_success_handler);
  3604. this._sasl_success_handler = null;
  3605. }
  3606. if (this._sasl_challenge_handler) {
  3607. this.deleteHandler(this._sasl_challenge_handler);
  3608. this._sasl_challenge_handler = null;
  3609. }
  3610. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
  3611. return false;
  3612. },
  3613. /** PrivateFunction: _auth2_cb
  3614. * _Private_ handler to finish legacy authentication.
  3615. *
  3616. * This handler is called when the result from the jabber:iq:auth
  3617. * <iq/> stanza is returned.
  3618. *
  3619. * Parameters:
  3620. * (XMLElement) elem - The stanza that triggered the callback.
  3621. *
  3622. * Returns:
  3623. * false to remove the handler.
  3624. */
  3625. _auth2_cb: function (elem)
  3626. {
  3627. if (elem.getAttribute("type") == "result") {
  3628. this.authenticated = true;
  3629. this._changeConnectStatus(Strophe.Status.CONNECTED, null);
  3630. } else if (elem.getAttribute("type") == "error") {
  3631. this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
  3632. this.disconnect();
  3633. }
  3634. return false;
  3635. },
  3636. /** PrivateFunction: _addSysTimedHandler
  3637. * _Private_ function to add a system level timed handler.
  3638. *
  3639. * This function is used to add a Strophe.TimedHandler for the
  3640. * library code. System timed handlers are allowed to run before
  3641. * authentication is complete.
  3642. *
  3643. * Parameters:
  3644. * (Integer) period - The period of the handler.
  3645. * (Function) handler - The callback function.
  3646. */
  3647. _addSysTimedHandler: function (period, handler)
  3648. {
  3649. var thand = new Strophe.TimedHandler(period, handler);
  3650. thand.user = false;
  3651. this.addTimeds.push(thand);
  3652. return thand;
  3653. },
  3654. /** PrivateFunction: _addSysHandler
  3655. * _Private_ function to add a system level stanza handler.
  3656. *
  3657. * This function is used to add a Strophe.Handler for the
  3658. * library code. System stanza handlers are allowed to run before
  3659. * authentication is complete.
  3660. *
  3661. * Parameters:
  3662. * (Function) handler - The callback function.
  3663. * (String) ns - The namespace to match.
  3664. * (String) name - The stanza name to match.
  3665. * (String) type - The stanza type attribute to match.
  3666. * (String) id - The stanza id attribute to match.
  3667. */
  3668. _addSysHandler: function (handler, ns, name, type, id)
  3669. {
  3670. var hand = new Strophe.Handler(handler, ns, name, type, id);
  3671. hand.user = false;
  3672. this.addHandlers.push(hand);
  3673. return hand;
  3674. },
  3675. /** PrivateFunction: _onDisconnectTimeout
  3676. * _Private_ timeout handler for handling non-graceful disconnection.
  3677. *
  3678. * If the graceful disconnect process does not complete within the
  3679. * time allotted, this handler finishes the disconnect anyway.
  3680. *
  3681. * Returns:
  3682. * false to remove the handler.
  3683. */
  3684. _onDisconnectTimeout: function ()
  3685. {
  3686. Strophe.info("_onDisconnectTimeout was called");
  3687. // cancel all remaining requests and clear the queue
  3688. var req;
  3689. while (this._requests.length > 0) {
  3690. req = this._requests.pop();
  3691. req.abort = true;
  3692. req.xhr.abort();
  3693. // jslint complains, but this is fine. setting to empty func
  3694. // is necessary for IE6
  3695. req.xhr.onreadystatechange = function () {};
  3696. }
  3697. // actually disconnect
  3698. this._doDisconnect();
  3699. return false;
  3700. },
  3701. /** PrivateFunction: _onIdle
  3702. * _Private_ handler to process events during idle cycle.
  3703. *
  3704. * This handler is called every 100ms to fire timed handlers that
  3705. * are ready and keep poll requests going.
  3706. */
  3707. _onIdle: function ()
  3708. {
  3709. var i, thand, since, newList;
  3710. // add timed handlers scheduled for addition
  3711. // NOTE: we add before remove in the case a timed handler is
  3712. // added and then deleted before the next _onIdle() call.
  3713. while (this.addTimeds.length > 0) {
  3714. this.timedHandlers.push(this.addTimeds.pop());
  3715. }
  3716. // remove timed handlers that have been scheduled for deletion
  3717. while (this.removeTimeds.length > 0) {
  3718. thand = this.removeTimeds.pop();
  3719. i = this.timedHandlers.indexOf(thand);
  3720. if (i >= 0) {
  3721. this.timedHandlers.splice(i, 1);
  3722. }
  3723. }
  3724. // call ready timed handlers
  3725. var now = new Date().getTime();
  3726. newList = [];
  3727. for (i = 0; i < this.timedHandlers.length; i++) {
  3728. thand = this.timedHandlers[i];
  3729. if (this.authenticated || !thand.user) {
  3730. since = thand.lastCalled + thand.period;
  3731. if (since - now <= 0) {
  3732. if (thand.run()) {
  3733. newList.push(thand);
  3734. }
  3735. } else {
  3736. newList.push(thand);
  3737. }
  3738. }
  3739. }
  3740. this.timedHandlers = newList;
  3741. var body, time_elapsed;
  3742. // if no requests are in progress, poll
  3743. if (this.authenticated && this._requests.length === 0 &&
  3744. this._data.length === 0 && !this.disconnecting) {
  3745. Strophe.info("no requests during idle cycle, sending " +
  3746. "blank request");
  3747. this._data.push(null);
  3748. }
  3749. if (this._requests.length < 2 && this._data.length > 0 &&
  3750. !this.paused) {
  3751. body = this._buildBody();
  3752. for (i = 0; i < this._data.length; i++) {
  3753. if (this._data[i] !== null) {
  3754. if (this._data[i] === "restart") {
  3755. body.attrs({
  3756. to: this.domain,
  3757. "xml:lang": "en",
  3758. "xmpp:restart": "true",
  3759. "xmlns:xmpp": Strophe.NS.BOSH
  3760. });
  3761. } else {
  3762. body.cnode(this._data[i]).up();
  3763. }
  3764. }
  3765. }
  3766. delete this._data;
  3767. this._data = [];
  3768. this._requests.push(
  3769. new Strophe.Request(body.tree(),
  3770. this._onRequestStateChange.bind(
  3771. this, this._dataRecv.bind(this)),
  3772. body.tree().getAttribute("rid")));
  3773. this._processRequest(this._requests.length - 1);
  3774. }
  3775. if (this._requests.length > 0) {
  3776. time_elapsed = this._requests[0].age();
  3777. if (this._requests[0].dead !== null) {
  3778. if (this._requests[0].timeDead() >
  3779. Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)) {
  3780. this._throttledRequestHandler();
  3781. }
  3782. }
  3783. if (time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)) {
  3784. Strophe.warn("Request " +
  3785. this._requests[0].id +
  3786. " timed out, over " + Math.floor(Strophe.TIMEOUT * this.wait) +
  3787. " seconds since last activity");
  3788. this._throttledRequestHandler();
  3789. }
  3790. }
  3791. clearTimeout(this._idleTimeout);
  3792. // reactivate the timer only if connected
  3793. if (this.connected) {
  3794. this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
  3795. }
  3796. }
  3797. };
  3798. if (callback) {
  3799. callback(Strophe, $build, $msg, $iq, $pres);
  3800. }
  3801. })(function () {
  3802. window.Strophe = arguments[0];
  3803. window.$build = arguments[1];
  3804. window.$msg = arguments[2];
  3805. window.$iq = arguments[3];
  3806. window.$pres = arguments[4];
  3807. });