You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

strophe.js 179KB

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